在进行预测时,我正在使用python + opencv构建KNN模型以对数字0-9进行分类。 问题是,无论我输入什么图像,结果始终为9 !!!!谁能告诉我原因!干杯! 这是我的代码:
**Part 1- read all images from 10 folders(which names are 0-9):**
datas = []
for j in range(0,10):
training_paths = training_path+str(j)+'\\'
afiles = [f for f in listdir(training_paths) if isfile(join(training_paths, f))]
for f in afiles:
img = cv2.imread(training_paths+f)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
datas.append(th)
**Part2: build Knn**
def initKNN(datas):
k = np.arange(10)
shit = np.array(datas)
samples = shit.reshape(-1,28*28).astype(np.float32)
train_labels = np.repeat(k,32)[:,np.newaxis]
knn = cv2.ml.KNearest_create()
knn.train(samples, cv2.ml.ROW_SAMPLE, train_labels)
return knn
**Part3: classify number**
def find_digits(knn,img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
out = th.reshape(-1, 28*28).astype(np.float32)
ret, result, neighbours, dis = knn.findNearest(out, k=1)
return int(result)