回答編集履歴

3

d

2019/11/01 09:58

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -86,9 +86,7 @@
86
86
 
87
87
  # 輪郭内部 (透明化しない画素) を255で塗りつぶす。
88
88
 
89
- for cnt in contours:
90
-
91
- cv2.drawContours(mask, contours, -1, color=255, thickness=-1)
89
+ cv2.drawContours(mask, contours, -1, color=255, thickness=-1)
92
90
 
93
91
 
94
92
 

2

g

2019/11/01 09:58

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -45,6 +45,8 @@
45
45
  ```python
46
46
 
47
47
  import cv2
48
+
49
+ import numpy as np
48
50
 
49
51
 
50
52
 

1

d

2019/11/01 09:36

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -35,3 +35,79 @@
35
35
  cv2.imwrite("result.png", rgba)
36
36
 
37
37
  ```
38
+
39
+
40
+
41
+ ## 追記
42
+
43
+
44
+
45
+ ```python
46
+
47
+ import cv2
48
+
49
+
50
+
51
+ # 画像を読み込む。
52
+
53
+ img = cv2.imread("sample.png")
54
+
55
+
56
+
57
+ # グレースケールに変換する。
58
+
59
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
60
+
61
+
62
+
63
+ # 2値化する。
64
+
65
+ thresh, binary = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY_INV)
66
+
67
+
68
+
69
+ # 輪郭を抽出する。
70
+
71
+ contours, hierarchy = cv2.findContours(
72
+
73
+ binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
74
+
75
+ )
76
+
77
+
78
+
79
+ # マスクを作成する。
80
+
81
+ mask = np.zeros_like(binary)
82
+
83
+
84
+
85
+ # 輪郭内部 (透明化しない画素) を255で塗りつぶす。
86
+
87
+ for cnt in contours:
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
+ cv2.imwrite(r"result.png", rgba)
108
+
109
+ ```
110
+
111
+
112
+
113
+ ![イメージ説明](e5f9ee54893266bcd6fcffc58a017902.png)