1 获取数据
import numpy as np
import tensorflow as tf
from tensorflow.keras import datasets def save(mnist_path):print("TensorFlow: {0}".format(tf.__version__))(train_data, train_label), (test_data, test_label) = datasets.mnist.load_data()np.savez(mnist_path,train_data=train_data,train_label=train_label,test_data=test_data,test_label=test_label,)mnist_path = 'C:\\Users\\Hyacinth\\Desktop\\mnist.npz'
save(mnist_path)
2 显示图片
import numpy as np
from tensorflow.keras import datasets def image_show(mnist_path):data = np.load(mnist_path)image = data['train_data'][0:100]label = data['train_label'].reshape(-1, )plt.figure(figsize = (10, 10))for i in range(100):print('%f, %f' % (i, label[i]))plt.subplot(10, 10, i + 1)plt.imshow(image[i])plt.show()mnist_path = 'C:\\Users\\Hyacinth\\Desktop\\mnist.npz'
image_show(mnist_path )
3 转换图片
import os
import cv2
import numpy as npdef convert_to_image(mnist_path, image_path):data = np.load(mnist_path)train_image = data["train_data"]train_label = data["train_label"]train_label = train_label.astype(np.int32)train_label = train_label.reshape(-1, 1)index = 0for arr in train_image:img_name = str(index) + ".png"img_path = image_path + str(train_label[index][0]) + "\\"if not os.path.exists(img_path):os.mkdir(img_path)cv2.imwrite(img_path + img_name, arr)index = index + 1image_path = "C:\\Users\\Hyacinth\\Desktop\\mnist\\"
mnist_path = 'C:\\Users\\Hyacinth\\Desktop\\mnist.npz'
convert_to_image(mnist_path, image_path)
4 全部代码
import os
import cv2
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras import datasets def image_show(mnist_path):data = np.load(mnist_path)image = data['train_data'][0:100]label = data['train_label'].reshape(-1, )plt.figure(figsize = (10, 10))for i in range(100):print('%f, %f' % (i, label[i]))plt.subplot(10, 10, i + 1)plt.imshow(image[i])plt.show()def save(mnist_path):print("TensorFlow: {0}".format(tf.__version__))(train_data, train_label), (test_data, test_label) = datasets.mnist.load_data()np.savez(mnist_path,train_data=train_data,train_label=train_label,test_data=test_data,test_label=test_label,)def convert_to_image(mnist_path, image_path):data = np.load(mnist_path)train_image = data["train_data"]train_label = data["train_label"]train_label = train_label.astype(np.int32)train_label = train_label.reshape(-1, 1)index = 0for arr in train_image:img_name = str(index) + ".png"img_path = image_path + str(train_label[index][0]) + "\\"if not os.path.exists(img_path):os.mkdir(img_path)cv2.imwrite(img_path + img_name, arr)index = index + 1image_path = "C:\\Users\\Hyacinth\\Desktop\\mnist\\"
mnist_path = 'C:\\Users\\Hyacinth\\Desktop\\mnist.npz'
save(mnist_path)
convert_to_image(mnist_path, image_path)