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

yipeiwu_com5年前Python基础

本文介绍了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的Flask框架中Flask-Admin库的简单入门指引

Python的Flask框架中Flask-Admin库的简单入门指引

 Flask-Admin是一个功能齐全、简单易用的Flask扩展,让你可以为Flask应用程序增加管理界面。它受django-admin包的影响,但用这样一种方式实现,开发者拥...

python Web开发你要理解的WSGI & uwsgi详解

python Web开发你要理解的WSGI & uwsgi详解

WSGI协议 首先弄清下面几个概念: WSGI:全称是Web Server Gateway Interface,WSGI不是服务器,python模块,框架,API或者任何软件,只是一种...

python中map、any、all函数用法分析

本文实例讲述了python中map、any、all函数用法。分享给大家供大家参考。具体分析如下: 最近想学python,就一直比较关注python,昨天在python吧看到有个帖子提问怎...

python广度优先搜索得到两点间最短路径

python广度优先搜索得到两点间最短路径

前言 之前一直写不出来,这周周日花了一下午终于弄懂了, 顺便放博客里,方便以后忘记了再看看。 要实现的是输入一张 图,起点,终点,输出起点和终点之间的最短路径。 广度优先搜索 适用...

python实现的AES双向对称加密解密与用法分析

本文实例讲述了python实现的AES双向对称加密解密与用法。分享给大家供大家参考,具体如下: 高级加密标准(Advanced Encryption Standard,AES),在密码学...