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 itchat实现微信好友头像拼接图的示例代码

python itchat实现微信好友头像拼接图的示例代码

偶然在网上发现itchat这个框架,itchat是一个开源的微信个人号接口,它使python调用微信变得非常简单。看到网上有人发自己微信好友的头像拼接图,自己也做了一个,感觉还蛮好玩的。...

一文秒懂python读写csv xml json文件各种骚操作

Python优越的灵活性和易用性使其成为最受欢迎的编程语言之一,尤其是对数据科学家而言。 这在很大程度上是因为使用Python处理大型数据集是很简单的一件事情。 如今,每家科技公司都在制...

浅谈django url请求与数据库连接池的共享问题

浅谈django url请求与数据库连接池的共享问题

但凡介绍数据库连接池的文章,都会说“数据库连接是一种关键的有限的昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出。对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响...

python实现顺序表的简单代码

python实现顺序表的简单代码

 顺序表即线性表的顺序存储结构。它是通过一组地址连续的存储单元对线性表中的数据进行存储的,相邻的两个元素在物理位置上也是相邻的。比如,第1个元素是存储在线性表的起始位置LOC(...

Python面向对象封装操作案例详解

Python面向对象封装操作案例详解

本文实例讲述了Python面向对象封装操作。分享给大家供大家参考,具体如下: 目标 封装 小明爱跑步 存放家具 01. 封装 封装 是面向对象编程的一大特点 面向对象编程的 第一步 ——...