回答編集履歴
2
d
answer
CHANGED
File without changes
|
1
d
answer
CHANGED
@@ -16,4 +16,63 @@
|
|
16
16
|
print(f"contour {i}: ({cx}, {cy})")
|
17
17
|
```
|
18
18
|
|
19
|
-
[領域(輪郭)の特徴 — OpenCV-Python Tutorials 1 documentation](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)
|
19
|
+
[領域(輪郭)の特徴 — OpenCV-Python Tutorials 1 documentation](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)
|
20
|
+
|
21
|
+
# 輪郭抽出した画像の中身だけの画像の指定方法を教えていただけませんか?
|
22
|
+
|
23
|
+
```python
|
24
|
+
import cv2
|
25
|
+
import numpy as np
|
26
|
+
|
27
|
+
# 画像を読み込む。
|
28
|
+
img = cv2.imread(r"sample.png")
|
29
|
+
|
30
|
+
# グレースケールに変換する。
|
31
|
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
32
|
+
|
33
|
+
# 2値化する。
|
34
|
+
thresh, binary = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY_INV)
|
35
|
+
|
36
|
+
# 輪郭を抽出する。
|
37
|
+
contours, hierarchy = cv2.findContours(
|
38
|
+
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
|
39
|
+
)
|
40
|
+
|
41
|
+
# マスクを作成する
|
42
|
+
mask = np.zeros_like(binary)
|
43
|
+
|
44
|
+
# 輪郭内部(透明化しない画素)を255で塗りつぶす。
|
45
|
+
cv2.drawContours(mask, contours, -1, color=255, thickness=-1)
|
46
|
+
|
47
|
+
# RGBAに変換する
|
48
|
+
rgba = cv2.cvtColor(img, cv2.COLOR_RGB2RGBA)
|
49
|
+
|
50
|
+
# マスクをアルファチャンネルに設定する。
|
51
|
+
rgba[..., 3] = mask
|
52
|
+
|
53
|
+
### 追加したコード
|
54
|
+
|
55
|
+
# すべての輪郭を構成する点
|
56
|
+
all_points = np.concatenate(contours).reshape(-1, 2)
|
57
|
+
|
58
|
+
# x, y の最小値、最大値を探す。
|
59
|
+
xmin, ymin, xmax, ymax = (
|
60
|
+
all_points[:, 0].min(),
|
61
|
+
all_points[:, 1].min(),
|
62
|
+
all_points[:, 0].max(),
|
63
|
+
all_points[:, 1].max(),
|
64
|
+
)
|
65
|
+
# その範囲でクロップする。
|
66
|
+
cropped = rgba[ymin:ymax + 1, xmin:xmax + 1]
|
67
|
+
print(cropped.shape) # (419, 852, 4)
|
68
|
+
|
69
|
+
# 保存する。
|
70
|
+
cv2.imwrite(r"cropped.png", cropped)
|
71
|
+
|
72
|
+
# BGR値の取得
|
73
|
+
print(cropped[200, 200]) # [167 116 55 255]
|
74
|
+
|
75
|
+
# 画像の大きさ(px)
|
76
|
+
h, w = cropped.shape[:2]
|
77
|
+
print(w, h) # 624 852
|
78
|
+
```
|