質問するログイン新規登録

回答編集履歴

3

d

2019/11/01 09:58

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -42,8 +42,7 @@
42
42
  mask = np.zeros_like(binary)
43
43
 
44
44
  # 輪郭内部 (透明化しない画素) を255で塗りつぶす。
45
- for cnt in contours:
46
- cv2.drawContours(mask, contours, -1, color=255, thickness=-1)
45
+ cv2.drawContours(mask, contours, -1, color=255, thickness=-1)
47
46
 
48
47
  # RGBA に変換する。
49
48
  rgba = cv2.cvtColor(img, cv2.COLOR_RGB2RGBA)

2

g

2019/11/01 09:58

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -22,6 +22,7 @@
22
22
 
23
23
  ```python
24
24
  import cv2
25
+ import numpy as np
25
26
 
26
27
  # 画像を読み込む。
27
28
  img = cv2.imread("sample.png")

1

d

2019/11/01 09:36

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -16,4 +16,42 @@
16
16
 
17
17
  # 保存する。
18
18
  cv2.imwrite("result.png", rgba)
19
- ```
19
+ ```
20
+
21
+ ## 追記
22
+
23
+ ```python
24
+ import cv2
25
+
26
+ # 画像を読み込む。
27
+ img = cv2.imread("sample.png")
28
+
29
+ # グレースケールに変換する。
30
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
31
+
32
+ # 2値化する。
33
+ thresh, binary = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY_INV)
34
+
35
+ # 輪郭を抽出する。
36
+ contours, hierarchy = cv2.findContours(
37
+ binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
38
+ )
39
+
40
+ # マスクを作成する。
41
+ mask = np.zeros_like(binary)
42
+
43
+ # 輪郭内部 (透明化しない画素) を255で塗りつぶす。
44
+ for cnt in contours:
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
+ cv2.imwrite(r"result.png", rgba)
55
+ ```
56
+
57
+ ![イメージ説明](e5f9ee54893266bcd6fcffc58a017902.png)