對於彩色圖像,不管其圖像格式是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))