回答編集履歴

1

d

2019/02/22 05:00

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -47,3 +47,73 @@
47
47
  cy = int(M["m01"] / M["m00"])
48
48
 
49
49
  ```
50
+
51
+
52
+
53
+ ## 追記
54
+
55
+
56
+
57
+ ```python
58
+
59
+ import cv2
60
+
61
+ import matplotlib.pyplot as plt
62
+
63
+ from matplotlib.patches import Polygon
64
+
65
+
66
+
67
+ img = cv2.imread('test.jpeg')
68
+
69
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
70
+
71
+
72
+
73
+ # 輪郭抽出する。
74
+
75
+ _, contours, hierarchy = cv2.findContours(
76
+
77
+ gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
78
+
79
+
80
+
81
+ # 面積が一定以上の輪郭だけ抽出
82
+
83
+ contours = list(filter(lambda x: cv2.contourArea(x) > 500, contours))
84
+
85
+
86
+
87
+ # 重心と外接矩形を計算する。
88
+
89
+ def get_centroid(cnt):
90
+
91
+ M = cv2.moments(cnt)
92
+
93
+ return int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])
94
+
95
+
96
+
97
+ rects = [cv2.boundingRect(x) for x in contours]
98
+
99
+ centers = [get_centroid(x) for x in contours]
100
+
101
+
102
+
103
+ # 重心と外接矩形を描画する。
104
+
105
+ for [x, y, w, h], [cx, cy] in zip(rects, centers):
106
+
107
+ cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=2)
108
+
109
+ cv2.circle(img, (cx, cy), radius=2, color=(0, 255, 0), thickness=-1)
110
+
111
+
112
+
113
+ cv2.imwrite('output.png', img)
114
+
115
+ ```
116
+
117
+
118
+
119
+ ![イメージ説明](a86fc8df02db4ed2e25e47c5761f9979.png)