我有以下代码:
from mnist import MNIST
from PIL import Image, ImageDraw
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd
from PIL import Image, ImageFilter
def imageprepare(argv):
"""
This function returns the pixel values.
The imput is a png file location.
"""
im = Image.open(argv).convert('L')
width = float(im.size[0])
height = float(im.size[1])
newImage = Image.new('L', (28, 28), (255)) # creates white canvas of 28x28 pixels
if width > height: # check which dimension is bigger
# Width is bigger. Width becomes 20 pixels.
nheight = int(round((20.0 / width * height), 0)) # resize height according to ratio width
if (nheight == 0): # rare case but minimum is 1 pixel
nheight = 1
# resize and sharpen
img = im.resize((20, nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
wtop = int(round(((28 - nheight) / 2), 0)) # calculate horizontal position
newImage.paste(img, (4, wtop)) # paste resized image on white canvas
else:
# Height is bigger. Heigth becomes 20 pixels.
nwidth = int(round((20.0 / height * width), 0)) # resize width according to ratio height
if (nwidth == 0): # rare case but minimum is 1 pixel
nwidth = 1
# resize and sharpen
img = im.resize((nwidth, 20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
wleft = int(round(((28 - nwidth) / 2), 0)) # caculate vertical pozition
newImage.paste(img, (wleft, 4)) # paste resized image on white canvas
tv = list(newImage.getdata()) # get pixel values
# normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
tva = [(255 - x) * 1.0 / 255.0 for x in tv]
print(tva)
return tva
x=imageprepare('C:\\Users\\Wasif Ahmed\\Desktop\\9.png')#file path here
#print(len(x))# mnist IMAGES are 28x28=784 pixels
# Load dataset
mndata = MNIST('C:\\Users\\Wasif Ahmed\\Desktop\\Digit Recognition\\data\\')
images, labels = mndata.load_training()
#test_images,test_labels = mndata.load_testing()
clf = KNeighborsClassifier()
# Train on the first 10000 images:
train_x = images
train_y = labels
print("Train model")
clf.fit(train_x, train_y)
test_x = x
expected = [9]
test_x = np.array(test_x)
test_x = test_x.reshape(1, -1)
print("Compute predictions")
predicted = clf.predict(test_x)
#print("Accuracy: ", accuracy_score(expected, predicted))
print("Expected: ",expected[0])
print("predicted: ", predicted[0])
预计:9
预测:1
(我使用过https://imgur.com/a/K8P1P2p的图像) 使用该功能时,imageprepare函数应该将我的图像转换为MNIST数据(我从另一篇文章中复制了它),我的预测值始终为1,好像我没有使用此函数并使用MNIST测试数据集一样,我得到了正确的预期和预测值。我怀疑我尝试将图像转换为数据的方式是错误的,因此我需要帮助才能正确执行。
test_images,test_labels = mndata.load_testing()
test_x = test_images[100]
expected = [test_labels[100]]
test_x = np.array(test_x)
test_x = test_x.reshape(1, -1)
print("Compute predictions")
predicted = clf.predict(test_x)
#print("Accuracy: ", accuracy_score(expected, predicted))
print("Expected: ",expected[0])
print("predicted: ", predicted[0])
预计:6
预计:6