pytorch 把MNIST数据集转换成图片和txt的方法


Posted in Python onMay 20, 2018

本文介绍了pytorch 把MNIST数据集转换成图片和txt的方法,分享给大家,具体如下:

1.下载Mnist 数据集

import os
# third-party library
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt 
# torch.manual_seed(1)  # reproducible
DOWNLOAD_MNIST = False
 
# Mnist digits dataset
if not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'):
  # not mnist dir or mnist is empyt dir
  DOWNLOAD_MNIST = True
 
train_data = torchvision.datasets.MNIST(
  root='./mnist/',
  train=True,                   # this is training data
  transform=torchvision.transforms.ToTensor(),  # Converts a PIL.Image or numpy.ndarray to
                          # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
  download=DOWNLOAD_MNIST,
)

下载下来的其实可以直接用了,但是我们这边想把它们转换成图片和txt,这样好看些,为后面用自己的图片和txt作为准备

2. 保存为图片和txt

import os
from skimage import io
import torchvision.datasets.mnist as mnist
import numpy 
root = "./mnist/raw/"
train_set = (
  mnist.read_image_file(os.path.join(root, 'train-images-idx3-ubyte')),
  mnist.read_label_file(os.path.join(root, 'train-labels-idx1-ubyte'))
)
 
test_set = (
  mnist.read_image_file(os.path.join(root,'t10k-images-idx3-ubyte')),
  mnist.read_label_file(os.path.join(root,'t10k-labels-idx1-ubyte'))
)
 
print("train set:", train_set[0].size())
print("test set:", test_set[0].size())
 
def convert_to_img(train=True):
  if(train):
    f = open(root + 'train.txt', 'w')
    data_path = root + '/train/'
    if(not os.path.exists(data_path)):
      os.makedirs(data_path)
    for i, (img, label) in enumerate(zip(train_set[0], train_set[1])):
      img_path = data_path + str(i) + '.jpg'
      io.imsave(img_path, img.numpy())
      int_label = str(label).replace('tensor(', '')
      int_label = int_label.replace(')', '')
      f.write(img_path + ' ' + str(int_label) + '\n')
    f.close()
  else:
    f = open(root + 'test.txt', 'w')
    data_path = root + '/test/'
    if (not os.path.exists(data_path)):
      os.makedirs(data_path)
    for i, (img, label) in enumerate(zip(test_set[0], test_set[1])):
      img_path = data_path + str(i) + '.jpg'
      io.imsave(img_path, img.numpy())
      int_label = str(label).replace('tensor(', '')
      int_label = int_label.replace(')', '')
      f.write(img_path + ' ' + str(int_label) + '\n')
    f.close()
 
convert_to_img(True)
convert_to_img(False)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
讲解Python的Scrapy爬虫框架使用代理进行采集的方法
Feb 18 Python
Python 正则表达式的高级用法
Dec 04 Python
Python爬虫实战之12306抢票开源
Jan 24 Python
使用python进行波形及频谱绘制的方法
Jun 17 Python
Python List列表对象内置方法实例详解
Oct 22 Python
如何基于Python实现电子邮件的发送
Dec 16 Python
python画图常规设置方式
Mar 05 Python
Python实现发票自动校核微信机器人的方法
May 22 Python
基于python 取余问题(%)详解
Jun 03 Python
Python趣味挑战之教你用pygame画进度条
May 31 Python
Python中Selenium对Cookie的操作方法
Jul 09 Python
python基础之类方法和静态方法
Oct 24 Python
Python安装lz4-0.10.1遇到的坑
May 20 #Python
Python requests发送post请求的一些疑点
May 20 #Python
python中virtualenvwrapper安装与使用
May 20 #Python
django静态文件加载的方法
May 20 #Python
django中静态文件配置static的方法
May 20 #Python
Python中跳台阶、变态跳台阶与矩形覆盖问题的解决方法
May 19 #Python
Python利用公共键如何对字典列表进行排序详解
May 19 #Python
You might like
自动生成文章摘要的代码[PHP 版本]
2007/03/20 PHP
php4与php5的区别小结(配置异同)
2011/12/20 PHP
php中3种方法统计字符串中每种字符的个数并排序
2012/08/27 PHP
php使用array_search函数实现数组查找的方法
2015/06/12 PHP
Jquery 设置标题的自动翻转
2009/10/03 Javascript
javascript中将Object转换为String函数代码 (json str)
2012/04/29 Javascript
如何让easyui gridview 宽度自适应窗口改变及fitColumns应用
2013/01/25 Javascript
qq悬浮代码(兼容各个浏览器)
2014/01/29 Javascript
jQuery制作拼图小游戏
2015/01/12 Javascript
js判断鼠标位置是否在某个div中的方法
2016/02/26 Javascript
微信小程序之ES6与事项助手的功能实现
2016/11/30 Javascript
详解React Native网络请求fetch简单封装
2017/08/10 Javascript
Vue ElementUI之Form表单验证遇到的问题
2017/08/21 Javascript
Vue 2.0学习笔记之使用$refs访问Vue中的DOM
2017/12/19 Javascript
基于Vue、Vuex、Vue-router实现的购物商城(原生切换动画)效果
2018/01/09 Javascript
在vue中获取微信支付code及code被占用问题的解决方法
2019/04/16 Javascript
浅谈 Webpack 如何处理图片(开发、打包、优化)
2019/05/15 Javascript
[51:07]VGJ.S vs Pain 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
linux平台使用Python制作BT种子并获取BT种子信息的方法
2017/01/20 Python
python构建深度神经网络(续)
2018/03/10 Python
python中int与str互转方法
2018/07/02 Python
Python之两种模式的生产者消费者模型详解
2018/10/26 Python
超简单使用Python换脸实例
2019/03/27 Python
python版DDOS攻击脚本
2019/06/12 Python
使用tqdm显示Python代码执行进度功能
2019/12/08 Python
Django实现从数据库中获取到的数据转换为dict
2020/03/27 Python
python numpy库np.percentile用法说明
2020/06/08 Python
python3实现飞机大战
2020/11/29 Python
Groupon法国官方网站:特卖和网上购物高达-70%
2019/09/02 全球购物
英国拖鞋购买网站:Bedroom Athletics
2020/02/28 全球购物
护理专业毕业生自我鉴定
2013/10/08 职场文书
专科毕业生求职简历的自我评价
2013/10/12 职场文书
《雷雨》教学反思
2014/02/20 职场文书
《恐龙》教学反思
2014/04/27 职场文书
2014年小学重阳节活动策划方案
2014/09/16 职场文书
导游词之五台山
2019/10/11 职场文书