这是我发现here的修改后的代码。
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('digits.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Now we split the image to 5000 cells, each 20x20 size
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]
# Make it into a Numpy array. It size will be (50,100,20,20)
x = np.array(cells)
# Now we prepare train_data.
train = x[:,:50].reshape(-1,400).astype(np.float32) # Size = (2500,400)
img = cv2.imread('1.png')
img1 = cv2.imread('2.png')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img1 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (20,20)).astype(np.float32)
img1 = cv2.resize(img1, (20,20)).astype(np.float32)
img = img.flatten()
img1 = img1.flatten()
arr = [img,img1]
arr = np.asarray(arr)
# Create labels for train and test data
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
# Initiate kNN, train the data, then test it with test data for k=1
knn = cv2.ml.KNearest_create()
knn.train(train, 0,train_labels)
ret, result, neighbours, dist = knn.findNearest(arr, k=5)
for i in result:
print i
# save the data
np.savez('knn_data.npz',train=train, train_labels=train_labels)
# Now load the data
with np.load('knn_data.npz') as data:
print data.files
train = data['train']
train_labels = data['train_labels']
完美无缺。但我无法弄清楚如何使用这个knn_data.npz文件。 这是我的尝试:
import numpy as np
import cv2
from matplotlib import pyplot as plt
with np.load('knn_data.npz') as data:
print data.files
train = data['train']
train_labels = data['train_labels']
img = cv2.imread('1.png')
img1 = cv2.imread('2.png')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img1 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (20,20)).astype(np.float32)
img1 = cv2.resize(img1, (20,20)).astype(np.float32)
img = img.flatten()
img1 = img1.flatten()
arr = [img,img1]
arr = np.asarray(arr)
knn = cv2.ml.KNearest_create()
ret, result, neighbours, dist = knn.findNearest(arr, k=5)
for i in result:
print i
我收到的错误消息,我无法修复:
OpenCV错误:在findNearest,文件/io/opencv/modules/ml/src/knearest.cpp中,断言失败(test_samples.type()== 5&& test_samples.cols == samples.cols) 325
追踪(最近一次通话): 文件" knn1.py",第20行,in ret,result,neighbors,dist = knn.findNearest(img,k = 5) cv2.error:/io/opencv/modules/ml/src/knearest.cpp:325:错误:(-215)test_samples.type()== 5&&函数findNearest
中的test_samples.cols == samples.cols
我在opencv 3.2.0
的{{1}}上使用python 2.7.15
。文件 1.png 和 2.png 是RGB图像文件。
答案 0 :(得分:1)
在您的示例中,您创建变量train
和train_labels
但从不使用它们。
在致电knn.findNearest(arr, k=5)
之前在任何地方添加以下内容:
train = data['train']
train_labels = data['train_labels']
knn = cv2.ml.KNearest_create()
knn.train(train, 0,train_labels)