NAko3 commited on
Commit
e7d7766
·
verified ·
1 Parent(s): 3c2d80a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -48
app.py CHANGED
@@ -1,10 +1,18 @@
1
- # app_white_only.py
2
- # white-reveal のみ作る軽量版
 
 
 
 
 
 
 
3
  import io, os, datetime
4
- from PIL import Image, ImageFilter, ImageOps
5
  import numpy as np
6
  import gradio as gr
7
 
 
8
  def normalize_to_pil(img_input, max_size=1400):
9
  if img_input is None: return None
10
  try:
@@ -19,7 +27,7 @@ def normalize_to_pil(img_input, max_size=1400):
19
  else: arr = arr.astype(np.uint8)
20
  pil = Image.fromarray(arr).convert("RGB"); pil.thumbnail((max_size,max_size), Image.LANCZOS); return pil
21
  if isinstance(img_input, dict):
22
- for k in ("image","img","output","edited_image"):
23
  if k in img_input and img_input[k] is not None:
24
  return normalize_to_pil(img_input[k], max_size=max_size)
25
  for v in img_input.values():
@@ -39,9 +47,11 @@ def normalize_to_pil(img_input, max_size=1400):
39
  except: return None
40
  return None
41
 
 
42
  def auto_mask_otsu(pil):
 
43
  gray = np.array(pil.convert("L"))
44
- hist,_ = np.histogram(gray.flatten(), bins=256, range=(0,256))
45
  total = gray.size; sum_total = np.dot(np.arange(256), hist)
46
  sumB=0.0; wB=0.0; varMax=0.0; threshold=0
47
  for t in range(256):
@@ -50,72 +60,142 @@ def auto_mask_otsu(pil):
50
  wF = total - wB
51
  if wF==0: break
52
  sumB += float(t*hist[t])
53
- mB = sumB / wB
54
- mF = (sum_total - sumB) / wF
55
  varBetween = wB * wF * (mB - mF)**2
56
  if varBetween > varMax:
57
  varMax = varBetween; threshold = t
58
  mask = (gray > threshold).astype(np.uint8) * 255
59
  m = Image.fromarray(mask, mode='L')
 
60
  m = m.filter(ImageFilter.MinFilter(3)).filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.MedianFilter(size=3))
61
  return m
62
 
63
- def make_white_reveal(orig_pil, mask_pil,
64
- max_alpha=150, gamma=0.9, blur_radius=4, invert_lum=True):
 
 
 
 
 
65
  orig = orig_pil.convert("RGB")
66
  mask = mask_pil.convert("L")
67
  w,h = orig.size
68
  mask_arr = np.array(mask).astype(np.uint8)
69
  lum = np.array(orig.convert("L")).astype(np.float32)
70
- alpha_base = 255.0 - lum if invert_lum else lum
 
 
 
 
 
71
  alpha_norm = np.clip(alpha_base/255.0, 0.0, 1.0)
72
  alpha_gamma = np.power(alpha_norm, float(gamma))
73
  alpha_scaled = (alpha_gamma * float(max_alpha)).astype(np.uint8)
74
- reveal = (mask_arr < 128)
75
- alpha_final = np.zeros_like(alpha_scaled); alpha_final[reveal] = alpha_scaled[reveal]
76
- rgba = np.zeros((h,w,4), dtype=np.uint8); rgba[...,0:3]=255; rgba[...,3]=alpha_final
77
- white = Image.fromarray(rgba, mode="RGBA")
78
- if blur_radius and float(blur_radius)>0:
79
- a = Image.fromarray(alpha_final, mode="L"); a = a.filter(ImageFilter.GaussianBlur(radius=float(blur_radius)))
80
- rgba[...,3] = np.array(a); white = Image.fromarray(rgba, mode="RGBA")
81
- return white
82
-
83
- def save_temp(img):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  if img is None: return None
85
  tmp = "/tmp" if os.path.isdir("/tmp") else "."
86
  p = os.path.join(tmp, f"white_{datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')}.png")
87
- img.save(p, format="PNG"); return p
 
88
 
89
- def generate(img_in, mask_in, in_max, out_size, max_alpha, gamma, blur, invert):
90
- orig = normalize_to_pil(img_in, max_size=int(in_max or 1400))
91
- if orig is None: return None, "元画像が読み込めません"
 
 
 
92
  if mask_in is not None:
93
  m = normalize_to_pil(mask_in, max_size=int(in_max or 1400))
94
  mask = m.convert("L") if m is not None else auto_mask_otsu(orig)
95
  else:
96
  mask = auto_mask_otsu(orig)
97
- white = make_white_reveal(orig, mask, max_alpha=int(max_alpha), gamma=float(gamma), blur_radius=float(blur), invert_lum=bool(invert))
98
- # resize to square
99
- w = int(out_size); white.thumbnail((w,w), Image.LANCZOS)
100
- canvas = Image.new("RGBA",(w,w),(0,0,0,0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  left = (w - white.width)//2; top = (w - white.height)//2
102
- canvas.paste(white,(left,top),white)
103
- return canvas, "white-reveal 生成完了"
104
-
105
- with gr.Blocks() as demo:
106
- gr.Markdown("white-reveal のみ生成(ダークで白が浮く)")
107
- img = gr.Image(type="pil", label="元画像")
108
- mask = gr.Image(type="pil", label="任意マスク(省略可)")
109
- in_max = gr.Slider(512,2400,value=1400,label="内部最大サイズ")
110
- out_size = gr.Slider(256,1200,value=900,label="出力サイズ(px)")
111
- max_alpha = gr.Slider(0,255,value=150,label="max_alpha")
112
- gamma = gr.Slider(0.5,1.5,value=0.9,label="gamma")
113
- blur = gr.Slider(0.0,10.0,value=4.0,label="blur")
114
- invert = gr.Checkbox(True, label="輝度を反転してalphaにする")
115
- gen = gr.Button("生成")
116
- out = gr.Image(label="White-reveal (RGBA)", type="pil")
117
- status = gr.Textbox()
118
- gen.click(fn=generate, inputs=[img,mask,in_max,out_size,max_alpha,gamma,blur,invert], outputs=[out,status])
119
- dl = gr.Button("ダウンロード")
120
- dl.click(fn=lambda im: save_temp(im), inputs=[out], outputs=[gr.File(label="DL PNG")])
121
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ """
3
+ White-reveal 作成ツール(マスク極性対応版)
4
+ - アップロード画像から自動マスク(Otsu)または任意マスクを使い、
5
+ 「ダークモードで白が浮く」white-reveal PNG を生成します。
6
+ - マスクの白黒どちらが「見せたい部分」かを UI で切替可能。
7
+ - パラメータで白さの出方を制御(max_alpha, gamma, blur)。
8
+ - 依存: gradio, pillow, numpy
9
+ """
10
  import io, os, datetime
11
+ from PIL import Image, ImageFilter
12
  import numpy as np
13
  import gradio as gr
14
 
15
+ # ---------- normalizers ----------
16
  def normalize_to_pil(img_input, max_size=1400):
17
  if img_input is None: return None
18
  try:
 
27
  else: arr = arr.astype(np.uint8)
28
  pil = Image.fromarray(arr).convert("RGB"); pil.thumbnail((max_size,max_size), Image.LANCZOS); return pil
29
  if isinstance(img_input, dict):
30
+ for k in ("image","img","image_data","output","edited_image"):
31
  if k in img_input and img_input[k] is not None:
32
  return normalize_to_pil(img_input[k], max_size=max_size)
33
  for v in img_input.values():
 
47
  except: return None
48
  return None
49
 
50
+ # ---------- simple Otsu ----------
51
  def auto_mask_otsu(pil):
52
+ if pil is None: return None
53
  gray = np.array(pil.convert("L"))
54
+ hist, _ = np.histogram(gray.flatten(), bins=256, range=(0,256))
55
  total = gray.size; sum_total = np.dot(np.arange(256), hist)
56
  sumB=0.0; wB=0.0; varMax=0.0; threshold=0
57
  for t in range(256):
 
60
  wF = total - wB
61
  if wF==0: break
62
  sumB += float(t*hist[t])
63
+ mB = sumB/wB
64
+ mF = (sum_total - sumB)/wF
65
  varBetween = wB * wF * (mB - mF)**2
66
  if varBetween > varMax:
67
  varMax = varBetween; threshold = t
68
  mask = (gray > threshold).astype(np.uint8) * 255
69
  m = Image.fromarray(mask, mode='L')
70
+ # small clean
71
  m = m.filter(ImageFilter.MinFilter(3)).filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.MedianFilter(size=3))
72
  return m
73
 
74
+ # ---------- white reveal maker (mask polarity aware) ----------
75
+ def make_white_reveal(orig_pil, mask_pil, max_alpha=150, gamma=0.9, blur_radius=4, invert_lum=True, mask_white_is_reveal=True):
76
+ """
77
+ orig_pil: RGB PIL
78
+ mask_pil: L-mode PIL (255/0)
79
+ mask_white_is_reveal: Trueなら mask==255 が「見せたい領域」
80
+ """
81
  orig = orig_pil.convert("RGB")
82
  mask = mask_pil.convert("L")
83
  w,h = orig.size
84
  mask_arr = np.array(mask).astype(np.uint8)
85
  lum = np.array(orig.convert("L")).astype(np.float32)
86
+
87
+ # base alpha from luminance (optionally inverted)
88
+ if invert_lum:
89
+ alpha_base = 255.0 - lum
90
+ else:
91
+ alpha_base = lum.copy()
92
  alpha_norm = np.clip(alpha_base/255.0, 0.0, 1.0)
93
  alpha_gamma = np.power(alpha_norm, float(gamma))
94
  alpha_scaled = (alpha_gamma * float(max_alpha)).astype(np.uint8)
95
+
96
+ # determine reveal region from mask polarity
97
+ if mask_white_is_reveal:
98
+ reveal_region = (mask_arr >= 128)
99
+ else:
100
+ reveal_region = (mask_arr < 128)
101
+
102
+ alpha_final = np.zeros_like(alpha_scaled)
103
+ alpha_final[reveal_region] = alpha_scaled[reveal_region]
104
+
105
+ rgba = np.zeros((h,w,4), dtype=np.uint8)
106
+ rgba[...,0:3] = 255
107
+ rgba[...,3] = alpha_final
108
+
109
+ white_img = Image.fromarray(rgba, mode="RGBA")
110
+
111
+ # blur alpha for softer edges
112
+ if blur_radius and float(blur_radius) > 0:
113
+ a = Image.fromarray(alpha_final, mode="L")
114
+ a = a.filter(ImageFilter.GaussianBlur(radius=float(blur_radius)))
115
+ rgba[...,3] = np.array(a)
116
+ white_img = Image.fromarray(rgba, mode="RGBA")
117
+
118
+ return white_img
119
+
120
+ # ---------- helper: auto-detect polarity ----------
121
+ def detect_mask_polarity(mask_pil):
122
+ """簡易自動判定:白(255) の割合が小さければ白を '見せたい' と仮定(小さいオブジェク���を表示する想定)"""
123
+ arr = np.array(mask_pil.convert("L"))
124
+ white_ratio = float((arr >= 128).sum()) / arr.size
125
+ # 白が少ない=白が対象(例:ハートなど小さいモチーフ) -> True
126
+ # 白が大きい=白が背景的 => False
127
+ return white_ratio < 0.5
128
+
129
+ # ---------- save tmp ----------
130
+ def save_tmp_png(img):
131
  if img is None: return None
132
  tmp = "/tmp" if os.path.isdir("/tmp") else "."
133
  p = os.path.join(tmp, f"white_{datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')}.png")
134
+ img.save(p, format="PNG")
135
+ return p
136
 
137
+ # ---------- UI callbacks ----------
138
+ def generate_white_only(orig_in, mask_in, in_max, out_size, max_alpha, gamma, blur, invert_lum, mask_polarity_checkbox):
139
+ orig = normalize_to_pil(orig_in, max_size=int(in_max or 1400))
140
+ if orig is None:
141
+ return None, "元画像が読み込めません"
142
+ # mask: use provided or auto
143
  if mask_in is not None:
144
  m = normalize_to_pil(mask_in, max_size=int(in_max or 1400))
145
  mask = m.convert("L") if m is not None else auto_mask_otsu(orig)
146
  else:
147
  mask = auto_mask_otsu(orig)
148
+ if mask is None:
149
+ return None, "マスク生成に失敗しました"
150
+
151
+ # auto-detect polarity suggestion
152
+ auto_polarity = detect_mask_polarity(mask)
153
+ # If user explicitly checked the checkbox, use that (checkbox meaning: "白が見せたい" True)
154
+ # If user left it unchecked (None/False) we'll still allow auto-detect to set default behavior in UI.
155
+ mask_white_is_reveal = bool(mask_polarity_checkbox) if mask_polarity_checkbox is not None else auto_polarity
156
+
157
+ white = make_white_reveal(orig, mask,
158
+ max_alpha=int(max_alpha),
159
+ gamma=float(gamma),
160
+ blur_radius=float(blur),
161
+ invert_lum=bool(invert_lum),
162
+ mask_white_is_reveal=mask_white_is_reveal)
163
+ # center on square canvas at out_size
164
+ w = int(out_size or 900)
165
+ white.thumbnail((w,w), Image.LANCZOS)
166
+ canvas = Image.new("RGBA", (w,w), (0,0,0,0))
167
  left = (w - white.width)//2; top = (w - white.height)//2
168
+ canvas.paste(white, (left, top), white)
169
+ status = f"生成完了 | mask_white_is_reveal={mask_white_is_reveal} (auto_suggest={auto_polarity})"
170
+ return canvas, status
171
+
172
+ # ---------- UI ----------
173
+ def create_ui():
174
+ with gr.Blocks(title="White-reveal(極性対応)") as demo:
175
+ gr.Markdown("White-reveal を作ります。**マスクの白(255)が見せたい部分か**をUIで指定できます(自動推定あり)。")
176
+
177
+ with gr.Row():
178
+ with gr.Column(scale=1):
179
+ img_in = gr.Image(type="pil", label="元画像をアップロード")
180
+ mask_in = gr.Image(type="pil", label="任意マスク(省略可)")
181
+ in_max = gr.Slider(512, 2400, value=1400, step=64, label="内部処理最大サイズ(px)")
182
+ out_size = gr.Slider(256, 1200, value=900, step=64, label="出力サイズ(px)")
183
+ max_alpha = gr.Slider(0,255,value=150,label="max_alpha (白の強さ上限)")
184
+ gamma = gr.Slider(0.5,1.5,value=0.9,label="gamma (中間調コントロール)")
185
+ blur = gr.Slider(0.0,10.0,value=4.0,label="blur (alpha のぼかし px)")
186
+ invert_lum = gr.Checkbox(label="輝度を反転してアルファに���う (推奨)", value=True)
187
+ mask_polarity_checkbox = gr.Checkbox(label="マスクの白(255)が『見せたい部分』である (チェックでYes) — 自動判定あり", value=None)
188
+ gen_btn = gr.Button("white-reveal 生成")
189
+ with gr.Column(scale=1):
190
+ out = gr.Image(type="pil", label="生成された white-reveal (RGBA)")
191
+ status = gr.Textbox(lines=2, label="状況")
192
+
193
+ gen_btn.click(fn=generate_white_only,
194
+ inputs=[img_in, mask_in, in_max, out_size, max_alpha, gamma, blur, invert_lum, mask_polarity_checkbox],
195
+ outputs=[out, status])
196
+
197
+ return demo
198
+
199
+ if __name__ == "__main__":
200
+ demo = create_ui()
201
+ demo.launch()