質問編集履歴

1

あああ

2018/07/10 02:59

投稿

jun_endo
jun_endo

スコア56

test CHANGED
@@ -1 +1 @@
1
- cv2のKNearestが使えない
1
+ cv2のKNearestが使えないああ
test CHANGED
@@ -6,11 +6,93 @@
6
6
 
7
7
 
8
8
 
9
+ ###サンプル
10
+
11
+ ```lang-python
12
+
13
+ import cv2
14
+
15
+ import numpy as np
16
+
17
+
18
+
19
+ ####### training part ###############
20
+
21
+ samples = np.loadtxt('generalsamples.data',np.float32)
22
+
23
+ responses = np.loadtxt('generalresponses.data',np.float32)
24
+
25
+ responses = responses.reshape((responses.size,1))
26
+
27
+
28
+
29
+ model = cv2.ml.KNearest_create()
30
+
31
+ model.train(samples,responses)
32
+
33
+
34
+
35
+ ############################# testing part #########################
36
+
37
+
38
+
39
+ im = cv2.imread('pi.png')
40
+
41
+ out = np.zeros(im.shape,np.uint8)
42
+
43
+ gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
44
+
45
+ thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
46
+
47
+
48
+
49
+ contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
50
+
51
+
52
+
53
+ for cnt in contours:
54
+
55
+ if cv2.contourArea(cnt)>50:
56
+
57
+ [x,y,w,h] = cv2.boundingRect(cnt)
58
+
59
+ if h>28:
60
+
61
+ cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
62
+
63
+ roi = thresh[y:y+h,x:x+w]
64
+
65
+ roismall = cv2.resize(roi,(10,10))
66
+
67
+ roismall = roismall.reshape((1,100))
68
+
69
+ roismall = np.float32(roismall)
70
+
71
+ retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
72
+
73
+ string = str(int((results[0][0])))
74
+
75
+ cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
76
+
77
+
78
+
79
+ cv2.imshow('im',im)
80
+
81
+ cv2.imshow('out',out)
82
+
83
+ cv2.waitKey(0)
84
+
85
+
86
+
87
+ ```
88
+
9
89
  ###わからないこと
10
90
 
11
91
  pythonのopencvで数字認識をしようと、
12
92
 
13
93
  スタックオーバフローにあったサンプルを動かそうとしたところ、
94
+
95
+
14
96
 
15
97
  ```lang-python
16
98
 
@@ -29,3 +111,23 @@
29
111
 
30
112
 
31
113
  どなたか教えてください。
114
+
115
+
116
+
117
+ cv2.ml~に変えて実行してみたところ
118
+
119
+ ```
120
+
121
+ Traceback (most recent call last):
122
+
123
+ File "suji_test.py", line 10, in <module>
124
+
125
+ model.train(samples,responses)
126
+
127
+ TypeError: only size-1 arrays can be converted to Python scalars
128
+
129
+ ```
130
+
131
+ このようになりました
132
+
133
+ これはどういういみですか?