回答編集履歴
1
d
answer
CHANGED
@@ -22,4 +22,39 @@
|
|
22
22
|
M = cv2.moments(max_cnt)
|
23
23
|
cx = int(M["m10"] / M["m00"])
|
24
24
|
cy = int(M["m01"] / M["m00"])
|
25
|
-
```
|
25
|
+
```
|
26
|
+
|
27
|
+
## 追記
|
28
|
+
|
29
|
+
```python
|
30
|
+
import cv2
|
31
|
+
import matplotlib.pyplot as plt
|
32
|
+
from matplotlib.patches import Polygon
|
33
|
+
|
34
|
+
img = cv2.imread('test.jpeg')
|
35
|
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
36
|
+
|
37
|
+
# 輪郭抽出する。
|
38
|
+
_, contours, hierarchy = cv2.findContours(
|
39
|
+
gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
40
|
+
|
41
|
+
# 面積が一定以上の輪郭だけ抽出
|
42
|
+
contours = list(filter(lambda x: cv2.contourArea(x) > 500, contours))
|
43
|
+
|
44
|
+
# 重心と外接矩形を計算する。
|
45
|
+
def get_centroid(cnt):
|
46
|
+
M = cv2.moments(cnt)
|
47
|
+
return int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])
|
48
|
+
|
49
|
+
rects = [cv2.boundingRect(x) for x in contours]
|
50
|
+
centers = [get_centroid(x) for x in contours]
|
51
|
+
|
52
|
+
# 重心と外接矩形を描画する。
|
53
|
+
for [x, y, w, h], [cx, cy] in zip(rects, centers):
|
54
|
+
cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=2)
|
55
|
+
cv2.circle(img, (cx, cy), radius=2, color=(0, 255, 0), thickness=-1)
|
56
|
+
|
57
|
+
cv2.imwrite('output.png', img)
|
58
|
+
```
|
59
|
+
|
60
|
+

|