读入图片并处理
把图片读入,变成nparray之后,经过标准化处理直接和原来的mnist数据连在一起即可
import csv
import random
import numpy as np
import tensorflow as tf
from skimage.exposure import rescale_intensity
from tensorflow.keras import backend as K
from tensorflow.keras.applications.imagenet_utils import preprocess_input
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing import image
# from skimage.exposure import rescale_intensity
import os
import cv2
from PIL import Image
import math
# import matplotlib as mpl
# import matplotlib.pyplot as plt
from PIL import Image
def preprocess_image(img_path, target_size=(28, 28)):
img2 = Image.open(img_path) # 读取图片
input_img_data = np.array(img2) # 变成nparray
return input_img_data # 返回
# datasetPath为存储路径
def generateData_png(datasetPath):
fileList = []
#图像路径存储到fileList
for file in sorted(os.listdir(datasetPath)):
if file.endswith(".png"):
fileList.append(file)
test = []
# 将图片变成 nparray 存到test里面
for i in range(len(fileList)):
path = os.path.join(datasetPath, fileList[i])
test.append(preprocess_image(path))
test = np.array(test) # 变成nparray
print(test.shape)
return test
# 模型名称
model_name = "mnist_tiny_model"
# 加载模型
model = tf.keras.models.load_model("mnist_tiny_model.h5")
# 除以255
img_shape = 28, 28, 1
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], *img_shape).astype('float32') / 255
x_test = x_test.reshape(x_test.shape[0], *img_shape).astype('float32') / 255
# 生成的图片同样操作
data1 = generateData_png(r"./datapath") # datapath表示生成图片的路径
data1 = data1.reshape(data1.shape[0], *img_shape).astype('float32') / 255
# 加入生成的图片形成最终的数据
data_= np.vstack((x_test, data1))
标签:img,keras,shape,nparry,灰度,test,import,mnist
From: https://www.cnblogs.com/christopherJames/p/16953426.html