app开发者平台在数字化时代的重要性与发展趋势解析
602
2022-10-11
pytorch 把MNIST数据集转换成图片和txt
1.-Mnist 数据集
import os# third-party libraryimport torchimport torch.nn as nnfrom torch.autograd import Variableimport torch.utils.data as Dataimport torchvisionimport matplotlib.pyplot as plt# torch.manual_seed(1) # reproducibleDOWNLOAD_MNIST = False# Mnist digits datasetif not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'): # not mnist dir or mnist is empyt dir DOWNLOAD_MNIST = Truetrain_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 osfrom skimage import ioimport torchvision.datasets.mnist as mnistimport numpyroot = "./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()) f.write(img_path + ' ' + str(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()) f.write(img_path + ' ' + str(label) + '\n') f.close()convert_to_img(True)convert_to_img(False)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~