사진을 mnist 형식의 데이터로 변환하는 방법

"""
그림을 읽고, 그레이 스케일로 변환하고, 크기를 28로 조정
하고 예측을 위해 mnist 모델에 전달합니다.

"""

from __future__ import division, print_function, absolute_import

import tflearn
import numpy as np
from PIL import Image

# 读取训练好的模型


from mnist_model import *
model = MnistModel('models/mnist2/mnist2.tfl')
# 读取图片转成灰度格式
img = Image.open('1.bmp').convert('L')

# 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代表黑色
        pixel = 1.0 - float(img.getpixel((j, i)))/255.0
        # pixel = 255.0 - float(img.getpixel((j, i))) # 如果是0-255的颜色值
        arr.append(pixel)

arr1 = np.array(arr).reshape((1, 28, 28, 1))
print (model.predict(arr1))
"""

수정된 형식의 경우 이러한 방식으로 그림을 그려 진행 상황을 확인할 수도 있습니다. mnist를 예로 들어 보겠습니다.




from PIL import Image

import tflearn.datasets.mnist as mnist
X, Y, testX, testY = mnist.load_data(one_hot=True)
X = X.reshape([-1, 28, 28, 1])
testX = testX.reshape([-1, 28, 28, 1])
# 取出测试集中第一张图片的像素,reshape成28*28
test_x_0 = testX[0].reshape([28, 28])

# 新建一张图片,把test_x_0的像素写入
img = Image.new('L', (28, 28), 255)
for i in range(28):
    for j in range(28):
        img.putpixel((j, i), 255 - int(test_x_0[i][j] * 255.0))

# 保存图片以查看,也可以直接img.show()
img.save('test_save.png')

Guess you like

Origin blog.csdn.net/stay_foolish12/article/details/131705508