值错误: 找到带有暗淡 4 的数组。预期 SVC <= 2



我正在尝试训练一个预测手写数字的模型,如果相机捕捉到数字的图像,并且模型预测,但是,我一直得到上面标题的值错误。这是我的密码。

图像被描述为*img_resize=cv2.resize(im_binary,(28,28((*行,但我认为这是错误的,你能帮我找出正确的方法吗,因为相机拍摄的图像无法接收。

from sklearn import svm
from sklearn import datasets
svc=svm.SVC(gamma=0.001, C=100.)
digits=datasets.load_digits()
x=digits['data']
y=digits['target']

svc.fit(x,y)

import numpy as np
import cv2
from skimage import img_as_ubyte    
from skimage.color import rgb2gray
width = 640
height = 480
cameraNo = 0

cap = cv2.VideoCapture(cameraNo)
cap.set(3,width)
cap.set(4,height)


while True:
success, img_orig = cap.read()
img_gray = rgb2gray(img_orig)
img_gray_u8 = img_as_ubyte(img_gray)
(thresh, im_binary) = cv2.threshold(img_gray_u8, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
img_resized = cv2.resize(im_binary,(28,28))
im_gray_invert = 255 - img_resized
cv2.imshow("invert image", im_gray_invert)
im_final = im_gray_invert.reshape(1,28,28,1)
ans = svc.predict(im_final)
ans = np.argmax(ans,axis=1)[0]
print(ans)
cv2.putText(img_orig,'Predicted Digit : '+str(ans),
(50,50),cv2.FONT_HERSHEY_COMPLEX,
1,(0,0,255),1)
cv2.imshow("Original Image",img_orig)

if cv2.waitKey(1) and 0xFF == ord('q'):
break

cap.release()
cv2.destroyAllWindows()

您在训练中使用了形状为8*8的图像。例如;

x[0].shape

是64,它是扁平的8乘8阵列。

然而,在你的测试集中,你有形状为28*28的图像,这会导致问题;

im_gray_invert.shape

如果你的测试集中有8*8个图像,通过修改下面的行,你的代码就可以工作了;

im_final = im_gray_invert.flatten()

希望这能有所帮助。祝你好运:(

最新更新