回答編集履歴
1
せっかくなので…
answer
CHANGED
@@ -9,4 +9,61 @@
|
|
9
9
|
既に二値化できるところまで来ているようですので、矩形の検出は既定の関数ですぐにできます。四角の描画も線を一本一本引かなくてもまとめて引けます。だいぶ楽になるのではないでしょうか?こちらも[別のOpenCVのチュートリアル](http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html)が参考になります。
|
10
10
|
|
11
11
|
---
|
12
|
+
漂う力技感。
|
13
|
+

|
14
|
+

|
15
|
+
```Python3
|
16
|
+
import cv2
|
17
|
+
|
18
|
+
def detect_contour(img):
|
19
|
+
int_ocv = int(cv2.__version__[0])
|
20
|
+
if int_ocv == 4:
|
21
|
+
contours, hierachy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
22
|
+
else:
|
23
|
+
_, contours, hierachy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
|
24
|
+
return contours
|
25
|
+
|
26
|
+
|
27
|
+
img_raw = cv2.imread("test.png")
|
28
|
+
img_drawn = img_raw.copy()
|
29
|
+
img_hsv = cv2.cvtColor(img_raw,cv2.COLOR_BGR2HSV)
|
30
|
+
|
31
|
+
img_bin = cv2.inRange(img_hsv, (0,20,0), (10,255,255))
|
32
|
+
|
33
|
+
# cv2.imshow("img_bin",img_bin)
|
34
|
+
|
35
|
+
###
|
36
|
+
|
37
|
+
contours = detect_contour(img_bin)
|
38
|
+
for cnt in contours:
|
39
|
+
area = cv2.contourArea(cnt)
|
40
|
+
if area > 2000:
|
41
|
+
img_bin = cv2.drawContours(img_bin,[cnt],-1,(128), -1)
|
42
|
+
img_bin[img_bin==255] = 0
|
43
|
+
img_drawn[img_bin==128] = (0,0,255)
|
44
|
+
|
45
|
+
###
|
46
|
+
contours = detect_contour(img_bin)
|
47
|
+
for cnt in contours:
|
48
|
+
# area = cv2.contourArea(cnt)
|
49
|
+
x, y, w, h = cv2.boundingRect(cnt)
|
50
|
+
img_drawn = cv2.rectangle(img_drawn,(x,y),(x+w,y+h),(0,255,0),2)
|
51
|
+
|
52
|
+
# cv2.imshow("img_raw",img_raw)
|
53
|
+
# cv2.imshow("img_bin[fixed]",img_bin)
|
54
|
+
cv2.imshow("img_drawn",img_drawn)
|
55
|
+
cv2.waitKey(0)
|
56
|
+
cv2.imwrite("img_drawn.png",img_drawn)
|
57
|
+
|
58
|
+
|
59
|
+
|
60
|
+
|
61
|
+
|
62
|
+
|
63
|
+
cv2.waitKey(0)
|
64
|
+
|
65
|
+
```
|
66
|
+
|
67
|
+
|
68
|
+
---
|
12
69
|
さらに精度が必要であれば[機械学習](https://www.pro-s.co.jp/blog/system/opencv/6231)や[深層学習](https://qiita.com/harmegiddo/items/c3db5fd567fa4c6cc9fb)を検討ください。
|