NAko3 commited on
Commit
96892bc
·
verified ·
1 Parent(s): 0539159

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -74
app.py CHANGED
@@ -1,12 +1,10 @@
1
  # app.py
2
  """
3
- マスク画像作成ツール(完全版・入力正規化対応)
4
- - gr.ImageEditor による落書き対応(環境によって返り値の型が変わるため正規化処理を追加)
5
- - 固定サイズキャンバス
6
- - 参照画像を中央に縮小して薄く表示
7
- - 白/黒の手描きを優先して 255/0 に固定
8
- - 自動コントラスト + ユーザ指定強化
9
- - ブラシ不透明度/サイズはサーバ側で"強度"・"フェザー"として反映(擬似的)
10
  """
11
 
12
  import io
@@ -16,73 +14,89 @@ from PIL import Image, ImageOps, ImageEnhance, ImageFilter
16
  import numpy as np
17
  import gradio as gr
18
 
19
- # ---------- 入力正規化ユーティリティ ----------
20
  def normalize_to_pil(img_input):
21
- """
22
- Gradio のコンポーネントはバージョンやコンフィグにより
23
- - PIL.Image
24
- - numpy.ndarray
25
- - file path (str)
26
- - dict (e.g. {"image": PIL.Image, "mask": ...})
27
- - tuple/list
28
- を返すことがある。
29
- ここで PIL.Image に正規化する。
30
- """
31
  if img_input is None:
32
  return None
33
-
34
- # 既に PIL Image
35
- if isinstance(img_input, Image.Image):
36
  return img_input.convert("RGB")
37
-
38
- # numpy array -> PIL
39
  if isinstance(img_input, np.ndarray):
40
- try:
41
- arr = img_input
42
- # uint8 であることを期待
43
- if arr.dtype != np.uint8:
44
- arr = (np.clip(arr, 0, 1) * 255).astype(np.uint8) if arr.max() <= 1.0 else arr.astype(np.uint8)
45
- except Exception:
46
- arr = img_input.astype(np.uint8)
47
  return Image.fromarray(arr).convert("RGB")
48
-
49
- # dict: 再帰的に中身を探す
50
  if isinstance(img_input, dict):
51
- # よくあるキー名を順に試す
52
  for k in ("image", "img", "edited_image", "image_data", "output"):
53
  if k in img_input and img_input[k] is not None:
54
  return normalize_to_pil(img_input[k])
55
- # 値を順に試す
56
  for v in img_input.values():
57
  if v is not None:
58
  pil = normalize_to_pil(v)
59
  if pil is not None:
60
  return pil
61
  return None
62
-
63
- # list/tuple: 先頭要素を試す
64
  if isinstance(img_input, (list, tuple)) and len(img_input) > 0:
65
  return normalize_to_pil(img_input[0])
66
-
67
- # 文字列 -> ファイルパスの可能性
68
  if isinstance(img_input, str):
69
- # 可能なら開く(Spaces 内の一時パスなど)
70
  try:
71
  im = Image.open(img_input)
72
  return im.convert("RGB")
73
  except Exception:
74
  return None
75
-
76
- # bytes -> try open
77
  if isinstance(img_input, (bytes, bytearray)):
78
  try:
79
  return Image.open(io.BytesIO(img_input)).convert("RGB")
80
  except:
81
  return None
82
-
83
  return None
84
 
85
- # ---------- 既存ユーティリティ ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def make_base_canvas(reference_image, size: int = 512):
87
  size = int(size)
88
  base = Image.new("RGB", (size, size), (128, 128, 128))
@@ -95,43 +109,52 @@ def make_base_canvas(reference_image, size: int = 512):
95
  new_h = max(1, int(h * scale))
96
  ref_resized = ref.resize((new_w, new_h), Image.LANCZOS)
97
  faded_base = Image.new("RGB", (new_w, new_h), (128, 128, 128))
98
- faded_ref = Image.blend(faded_base, ref_resized, alpha=0.3) # 30% の参照画像表示
99
  left = (size - new_w) // 2
100
  top = (size - new_h) // 2
101
  base.paste(faded_ref, (left, top))
102
  return base
103
 
104
- def generate_mask_from_image(edited_canvas: Image.Image,
 
105
  contrast_boost: float = 0.5,
106
  invert: bool = False,
107
  brush_strength: float = 1.0,
108
  feather: float = 0.0):
109
- if edited_canvas is None:
110
- return None, "キャンバスがありません"
 
 
 
 
 
111
 
112
- rgb = np.array(edited_canvas.convert("RGB")).astype(np.uint8)
113
 
114
- # 白と黒の閾値(手描きで明確に塗った部分を優先)
115
  white_thresh = 240
116
  black_thresh = 15
117
  white_mask = np.all(rgb >= white_thresh, axis=2)
118
  black_mask = np.all(rgb <= black_thresh, axis=2)
119
 
120
- # 輝度(luminance)
121
- lum = (0.299 * rgb[...,0] + 0.587 * rgb[...,1] + 0.114 * rgb[...,2]).astype(np.float32)
122
- result = lum.copy()
123
-
124
- # 手描き部分を優先
125
- result[white_mask] = 255.0
126
- result[black_mask] = 0.0
127
-
128
- # ブラシ強度(手描きの“主張”を強める処理)
 
 
 
 
 
129
  try:
130
  s = float(brush_strength)
131
  except:
132
  s = 1.0
133
- if s <= 0:
134
- s = 0.0
135
  center = 127.5
136
  result = (result - center) * (1.0 + (s - 1.0)) + center
137
  result = np.clip(result, 0, 255)
@@ -141,7 +164,7 @@ def generate_mask_from_image(edited_canvas: Image.Image,
141
  # 自動コントラスト
142
  img = ImageOps.autocontrast(img, cutoff=0)
143
 
144
- # ユーザ指定のコントラスト強化
145
  try:
146
  factor = 1.0 + float(contrast_boost)
147
  except:
@@ -149,7 +172,7 @@ def generate_mask_from_image(edited_canvas: Image.Image,
149
  if factor != 1.0:
150
  img = ImageEnhance.Contrast(img).enhance(factor)
151
 
152
- # フェザー(ぼかし)
153
  try:
154
  f = float(feather)
155
  except:
@@ -157,13 +180,14 @@ def generate_mask_from_image(edited_canvas: Image.Image,
157
  if f > 0:
158
  img = img.filter(ImageFilter.GaussianBlur(radius=f))
159
 
160
- # 反転オプション
161
  if invert:
162
  img = ImageOps.invert(img)
163
 
164
- status = f"マスク生成完了 | contrast_factor={factor:.2f} | brush_strength={s:.2f} | feather={f:.1f} | invert={invert}"
165
  return img, status
166
 
 
167
  def save_mask_temp_png(mask_img: Image.Image):
168
  if mask_img is None:
169
  return None
@@ -181,8 +205,8 @@ def create_ui():
181
  .gr-row { flex-direction: column; }
182
  }
183
  """
184
- with gr.Blocks(title="マスク作成ツール(完全版)", css=css) as demo:
185
- gr.Markdown("# マスク作成ツール(完全版)\n参照画像をアップロードして、右の編集キャンバスで直接描画してください(白=見せる, 黒=隠す)。スマホでのタッチ操作にも対応します。")
186
 
187
  with gr.Row():
188
  with gr.Column(scale=1):
@@ -193,7 +217,7 @@ def create_ui():
193
 
194
  gr.Markdown("### 出力設定")
195
  contrast = gr.Slider(0.0, 2.0, value=0.5, step=0.1, label="コントラスト強化 (0.0=無効)")
196
- brush_strength = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="ブラシ強度(擬似不透明度)")
197
  feather = gr.Slider(0.0, 20.0, value=0.0, step=0.5, label="フェザー(ぼかし、px)")
198
  invert = gr.Checkbox(label="結果を反転", value=False)
199
 
@@ -201,8 +225,8 @@ def create_ui():
201
  download_btn = gr.Button("ダウンロード (PNG)")
202
 
203
  with gr.Column(scale=1):
204
- # ImageEditor を使ってクライアント側で直接編集(落書き・消しゴムなど)
205
- canvas = gr.ImageEditor(label="編集キャンバス(タッチで描画)", type="pil")
206
  final_mask = gr.Image(label="生成マスク (グレースケール)", type="pil")
207
  status = gr.Textbox(label="状況", lines=3, interactive=False)
208
 
@@ -220,11 +244,7 @@ def create_ui():
220
 
221
  def generate_mask(canvas_img, cont, inv, b_strength, f_pix):
222
  try:
223
- # normalize -> PIL.Image にする
224
- pil_canvas = normalize_to_pil(canvas_img)
225
- if pil_canvas is None:
226
- return None, "無効なキャンバス入力(画像が取得できません)"
227
- mask, st = generate_mask_from_image(pil_canvas, cont, inv, b_strength, f_pix)
228
  return mask, st
229
  except Exception as e:
230
  return None, f"生成エラー: {e}"
 
1
  # app.py
2
  """
3
+ 軽量マスク作成ツール(Otsu自動抽出・Pillow/NumPyのみ)
4
+ - 依存は gradio, pillow, numpy のみ(軽量)
5
+ - ImageEditor を使って任意で落書き(手描き)が可能
6
+ - 手描きが無ければ Otsu 閾値 + 簡易モルフォロジーで自動抽出
7
+ - その後自動コントラスト・ユーザコントラスト強化・フェザー処理
 
 
8
  """
9
 
10
  import io
 
14
  import numpy as np
15
  import gradio as gr
16
 
17
+ # ---------- 入力正規化 ----------
18
  def normalize_to_pil(img_input):
 
 
 
 
 
 
 
 
 
 
19
  if img_input is None:
20
  return None
21
+ from PIL import Image as PilImage
22
+ # PIL Image
23
+ if isinstance(img_input, PilImage.Image):
24
  return img_input.convert("RGB")
25
+ # numpy
 
26
  if isinstance(img_input, np.ndarray):
27
+ arr = img_input
28
+ if arr.dtype != np.uint8:
29
+ if arr.max() <= 1.0:
30
+ arr = (np.clip(arr, 0, 1) * 255).astype(np.uint8)
31
+ else:
32
+ arr = arr.astype(np.uint8)
 
33
  return Image.fromarray(arr).convert("RGB")
34
+ # dict (Gradio の場合に返ることがある)
 
35
  if isinstance(img_input, dict):
 
36
  for k in ("image", "img", "edited_image", "image_data", "output"):
37
  if k in img_input and img_input[k] is not None:
38
  return normalize_to_pil(img_input[k])
 
39
  for v in img_input.values():
40
  if v is not None:
41
  pil = normalize_to_pil(v)
42
  if pil is not None:
43
  return pil
44
  return None
45
+ # list/tuple
 
46
  if isinstance(img_input, (list, tuple)) and len(img_input) > 0:
47
  return normalize_to_pil(img_input[0])
48
+ # filepath
 
49
  if isinstance(img_input, str):
 
50
  try:
51
  im = Image.open(img_input)
52
  return im.convert("RGB")
53
  except Exception:
54
  return None
55
+ # bytes
 
56
  if isinstance(img_input, (bytes, bytearray)):
57
  try:
58
  return Image.open(io.BytesIO(img_input)).convert("RGB")
59
  except:
60
  return None
 
61
  return None
62
 
63
+ # ---------- 自動抽出(軽量:Otsu + モルフォ) ----------
64
+ def auto_mask_extract_otsu(pil_img):
65
+ """PIL Image -> returns PIL 'L' mask (0/255) using Otsu + small morphological clean"""
66
+ if pil_img is None:
67
+ return None
68
+ gray = np.array(pil_img.convert("L"))
69
+ # Otsu threshold
70
+ hist, _ = np.histogram(gray.flatten(), bins=256, range=(0,256))
71
+ total = gray.size
72
+ sum_total = np.dot(np.arange(256), hist)
73
+ sumB = 0.0
74
+ wB = 0.0
75
+ varMax = 0.0
76
+ threshold = 0
77
+ for t in range(256):
78
+ wB += hist[t]
79
+ if wB == 0:
80
+ continue
81
+ wF = total - wB
82
+ if wF == 0:
83
+ break
84
+ sumB += float(t * hist[t])
85
+ mB = sumB / wB
86
+ mF = (sum_total - sumB) / wF
87
+ varBetween = wB * wF * (mB - mF) ** 2
88
+ if varBetween > varMax:
89
+ varMax = varBetween
90
+ threshold = t
91
+ bin_mask = (gray > threshold).astype(np.uint8) * 255
92
+ pil_mask = Image.fromarray(bin_mask, mode='L')
93
+ # morphological clean: small erosion then dilation (remove small specks)
94
+ pil_mask = pil_mask.filter(ImageFilter.MinFilter(3)).filter(ImageFilter.MaxFilter(3))
95
+ # optionally fill holes: simple median to smooth
96
+ pil_mask = pil_mask.filter(ImageFilter.MedianFilter(size=3))
97
+ return pil_mask
98
+
99
+ # ---------- ベースキャンバス作成 ----------
100
  def make_base_canvas(reference_image, size: int = 512):
101
  size = int(size)
102
  base = Image.new("RGB", (size, size), (128, 128, 128))
 
109
  new_h = max(1, int(h * scale))
110
  ref_resized = ref.resize((new_w, new_h), Image.LANCZOS)
111
  faded_base = Image.new("RGB", (new_w, new_h), (128, 128, 128))
112
+ faded_ref = Image.blend(faded_base, ref_resized, alpha=0.3) # 30% 表示
113
  left = (size - new_w) // 2
114
  top = (size - new_h) // 2
115
  base.paste(faded_ref, (left, top))
116
  return base
117
 
118
+ # ---------- マスク生成ロジック ----------
119
+ def generate_mask_from_image(edited_canvas_input,
120
  contrast_boost: float = 0.5,
121
  invert: bool = False,
122
  brush_strength: float = 1.0,
123
  feather: float = 0.0):
124
+ """
125
+ edited_canvas_input: Gradio の返り値を受ける(dict/ndarray/PIL/path の可能性)
126
+ 自動 or 手描きを判定して安定的にマスクを作る(PIL.Image(L) を返す)
127
+ """
128
+ pil_canvas = normalize_to_pil(edited_canvas_input)
129
+ if pil_canvas is None:
130
+ return None, "キャンバスが取得できません"
131
 
132
+ rgb = np.array(pil_canvas.convert("RGB")).astype(np.uint8)
133
 
134
+ # 手描き用の白/黒閾値
135
  white_thresh = 240
136
  black_thresh = 15
137
  white_mask = np.all(rgb >= white_thresh, axis=2)
138
  black_mask = np.all(rgb <= black_thresh, axis=2)
139
 
140
+ # 自動判定:手描きが無ければ自動抽出(Otsu)
141
+ if (not white_mask.any()) and (not black_mask.any()):
142
+ auto_mask = auto_mask_extract_otsu(pil_canvas)
143
+ if auto_mask is None:
144
+ return None, "自動抽出に失敗しました"
145
+ result = np.array(auto_mask).astype(np.float32)
146
+ else:
147
+ # 輝度ベース(手描きが混在する場合)
148
+ lum = (0.299 * rgb[...,0] + 0.587 * rgb[...,1] + 0.114 * rgb[...,2]).astype(np.float32)
149
+ result = lum.copy()
150
+ result[white_mask] = 255.0
151
+ result[black_mask] = 0.0
152
+
153
+ # ブラシ強度(擬似的な強調)
154
  try:
155
  s = float(brush_strength)
156
  except:
157
  s = 1.0
 
 
158
  center = 127.5
159
  result = (result - center) * (1.0 + (s - 1.0)) + center
160
  result = np.clip(result, 0, 255)
 
164
  # 自動コントラスト
165
  img = ImageOps.autocontrast(img, cutoff=0)
166
 
167
+ # ユーザコントラスト強化
168
  try:
169
  factor = 1.0 + float(contrast_boost)
170
  except:
 
172
  if factor != 1.0:
173
  img = ImageEnhance.Contrast(img).enhance(factor)
174
 
175
+ # フェザー(ガウスぼかし)
176
  try:
177
  f = float(feather)
178
  except:
 
180
  if f > 0:
181
  img = img.filter(ImageFilter.GaussianBlur(radius=f))
182
 
183
+ # 反転
184
  if invert:
185
  img = ImageOps.invert(img)
186
 
187
+ status = f"生成完了 | contrast_factor={factor:.2f} | brush_strength={s:.2f} | feather={f:.1f} | invert={invert}"
188
  return img, status
189
 
190
+ # ---------- ダウンロード補助 ----------
191
  def save_mask_temp_png(mask_img: Image.Image):
192
  if mask_img is None:
193
  return None
 
205
  .gr-row { flex-direction: column; }
206
  }
207
  """
208
+ with gr.Blocks(title="軽量マスク作成ツール (Otsu)") as demo:
209
+ gr.Markdown("## 軽量マスク作成ツール\n落書きがなければ自動で被写体を抽出��ます(Otsu閾値)。モバイルでのタッチ編集対応。")
210
 
211
  with gr.Row():
212
  with gr.Column(scale=1):
 
217
 
218
  gr.Markdown("### 出力設定")
219
  contrast = gr.Slider(0.0, 2.0, value=0.5, step=0.1, label="コントラスト強化 (0.0=無効)")
220
+ brush_strength = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="ブラシ強度(擬似)")
221
  feather = gr.Slider(0.0, 20.0, value=0.0, step=0.5, label="フェザー(ぼかし、px)")
222
  invert = gr.Checkbox(label="結果を反転", value=False)
223
 
 
225
  download_btn = gr.Button("ダウンロード (PNG)")
226
 
227
  with gr.Column(scale=1):
228
+ # ImageEditor(落書き可)
229
+ canvas = gr.ImageEditor(label="編集キャンバス(任意で落書き)", type="pil")
230
  final_mask = gr.Image(label="生成マスク (グレースケール)", type="pil")
231
  status = gr.Textbox(label="状況", lines=3, interactive=False)
232
 
 
244
 
245
  def generate_mask(canvas_img, cont, inv, b_strength, f_pix):
246
  try:
247
+ mask, st = generate_mask_from_image(canvas_img, cont, inv, b_strength, f_pix)
 
 
 
 
248
  return mask, st
249
  except Exception as e:
250
  return None, f"生成エラー: {e}"