python進階教程:pytorch 把MNIST數據集轉換成圖片和txt的方法

本文介紹了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作爲準備

  1. 保存爲圖片和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技術,分享一些學習的方法和需要留意的小細節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章