Skip to content

Commit 7eb8da3

Browse files
committed
预测验证码
1 parent 2bf5051 commit 7eb8da3

File tree

6 files changed

+29
-3
lines changed

6 files changed

+29
-3
lines changed

ch46-机器学习-K近邻/2-使用kNN对手写数字OCR.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,10 @@
4343
accuracy = correct * 100.0 / result.size
4444
print('准确率', accuracy) # 准确率91.76%
4545

46-
''''''
46+
4747
# save the data
4848
np.savez('knn_data.npz', train=train, train_labels=train_labels,test=test,test_labels=test_labels)
49+
4950
# Now load the data
5051
with np.load('knn_data.npz') as data:
5152
print(data.files)
@@ -56,5 +57,8 @@
5657

5758

5859
#TODO 怎样预测数字?
59-
retval, results=knn.predict(test[3:5])
60+
retval, results=knn.predict(test[1003:1005])
6061
# Docstring: predict(samples[, results[, flags]]) -> retval, results
62+
print(retval, results)#(4.0, array([[ 4.],[ 4.]], dtype=float32))
63+
#对比
64+
cv2.imwrite('test[1005].jpg',test[1005].reshape((20,20)))

ch46-机器学习-K近邻/2.png

24.7 KB
Loading

ch46-机器学习-K近邻/6.png

28 KB
Loading
3.83 MB
Binary file not shown.
695 Bytes
Loading

ch46-机器学习-K近邻/预测手写数字1.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,28 @@
1919
test = data['test']
2020
test_labels = data['test_labels']
2121

22+
print('加载KNN,数据')
2223
knn = cv2.ml.KNearest_create()
2324
knn.train(train, cv2.ml.ROW_SAMPLE, train_labels)
24-
ret, result, neighbours, dist = knn.findNearest(test, k=5)
25+
ret, result, neighbours, dist = knn.findNearest(test, k=5)
26+
27+
# 加载相片
28+
print('加载相片')
29+
img2 = cv2.imread('2.png', 0)
30+
gray2 = cv2.resize(img2, (20, 20))
31+
# gray2=gray2.reshape((400,))
32+
gray21 = gray2.reshape((-1, 400)).astype(np.float32)
33+
34+
img6 = cv2.imread('6.png', 0)
35+
gray6 = cv2.resize(img6, (20, 20))
36+
# gray2=gray2.reshape((400,))
37+
gray61 = gray6.reshape((-1, 400)).astype(np.float32)
38+
39+
g2 = np.append(gray21, gray61)
40+
g3 = g2.reshape((2, 400))
41+
42+
# 预测
43+
retval, results = knn.predict(g3)
44+
print(retval, results) # 不准确
45+
# (0.0, array([[ 0.],
46+
# [ 5.]], dtype=float32))

0 commit comments

Comments
 (0)