图片转mnist格式数据

对于彩色图像,不管其图像格式是PNG,还是BMP,或者JPG,在PIL中,使用Image模块的open()函数打开后,返回的图像对象的模式都是“RGB”。而对于灰度图像,不管其图像格式是PNG,还是BMP,或者JPG,打开后,其模式为“L”。
img = Image.open('1.bmp').convert('L')
如果convert中 模式“1”为二值图像,非黑即白。但是它每个像素用8个bit表示,0表示黑,255表示白。这个跟mnist很像,但是也有不同的
mnist 里的颜色是0代表白色(背景),1.0代表黑色

再转成28x28的大小
# resize的过程
if img.size[0] != 28 or img.size[1] != 28:
    img = img.resize((28, 28))

# 暂存像素值的一维数组
arr = []

for i in range(28):
    for j in range(28):
        # mnist 里的颜色是0代表白色(背景),1.0代表黑色, 这里把灰度图转换成mnist的数据
        pixel = 1.0 - float(img.getpixel((j, i)))/255.0
        # pixel = 255.0 - float(img.getpixel((j, i))) # 如果是0-255的颜色值
        arr.append(pixel)

#reshape转成四维的
arr1 = np.array(arr).reshape((1, 28, 28, 1))
print (model.predict(arr1))

发布了201 篇原创文章 · 获赞 20 · 访问量 41万+

猜你喜欢

转载自blog.csdn.net/zmlovelx/article/details/103244697