回答編集履歴
2
d
test
CHANGED
File without changes
|
1
d
test
CHANGED
@@ -35,3 +35,121 @@
|
|
35
35
|
|
36
36
|
|
37
37
|
[領域(輪郭)の特徴 — 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)
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
# 輪郭抽出した画像の中身だけの画像の指定方法を教えていただけませんか?
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
```python
|
46
|
+
|
47
|
+
import cv2
|
48
|
+
|
49
|
+
import numpy as np
|
50
|
+
|
51
|
+
|
52
|
+
|
53
|
+
# 画像を読み込む。
|
54
|
+
|
55
|
+
img = cv2.imread(r"sample.png")
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
# グレースケールに変換する。
|
60
|
+
|
61
|
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
# 2値化する。
|
66
|
+
|
67
|
+
thresh, binary = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY_INV)
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
# 輪郭を抽出する。
|
72
|
+
|
73
|
+
contours, hierarchy = cv2.findContours(
|
74
|
+
|
75
|
+
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
|
76
|
+
|
77
|
+
)
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
# マスクを作成する
|
82
|
+
|
83
|
+
mask = np.zeros_like(binary)
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
# 輪郭内部(透明化しない画素)を255で塗りつぶす。
|
88
|
+
|
89
|
+
cv2.drawContours(mask, contours, -1, color=255, thickness=-1)
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
# RGBAに変換する
|
94
|
+
|
95
|
+
rgba = cv2.cvtColor(img, cv2.COLOR_RGB2RGBA)
|
96
|
+
|
97
|
+
|
98
|
+
|
99
|
+
# マスクをアルファチャンネルに設定する。
|
100
|
+
|
101
|
+
rgba[..., 3] = mask
|
102
|
+
|
103
|
+
|
104
|
+
|
105
|
+
### 追加したコード
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
# すべての輪郭を構成する点
|
110
|
+
|
111
|
+
all_points = np.concatenate(contours).reshape(-1, 2)
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
# x, y の最小値、最大値を探す。
|
116
|
+
|
117
|
+
xmin, ymin, xmax, ymax = (
|
118
|
+
|
119
|
+
all_points[:, 0].min(),
|
120
|
+
|
121
|
+
all_points[:, 1].min(),
|
122
|
+
|
123
|
+
all_points[:, 0].max(),
|
124
|
+
|
125
|
+
all_points[:, 1].max(),
|
126
|
+
|
127
|
+
)
|
128
|
+
|
129
|
+
# その範囲でクロップする。
|
130
|
+
|
131
|
+
cropped = rgba[ymin:ymax + 1, xmin:xmax + 1]
|
132
|
+
|
133
|
+
print(cropped.shape) # (419, 852, 4)
|
134
|
+
|
135
|
+
|
136
|
+
|
137
|
+
# 保存する。
|
138
|
+
|
139
|
+
cv2.imwrite(r"cropped.png", cropped)
|
140
|
+
|
141
|
+
|
142
|
+
|
143
|
+
# BGR値の取得
|
144
|
+
|
145
|
+
print(cropped[200, 200]) # [167 116 55 255]
|
146
|
+
|
147
|
+
|
148
|
+
|
149
|
+
# 画像の大きさ(px)
|
150
|
+
|
151
|
+
h, w = cropped.shape[:2]
|
152
|
+
|
153
|
+
print(w, h) # 624 852
|
154
|
+
|
155
|
+
```
|