# integrated_app.py """ 統合画像処理アプリケーション - タブ1: Twitter隠し絵ジェネレーター(透過マスク方式) - タブ2: 透過ツール(モバイル最適化版 + 複数色パレット対応) """ import gradio as gr import numpy as np from PIL import Image, ImageEnhance, ImageOps, ImageFilter import cv2 import warnings import tempfile import os warnings.filterwarnings('ignore') # ======================== # 共通ユーティリティ関数 # ======================== def hex_to_rgb(hex_color: str): """ '#rrggbb' -> np.array([r,g,b], dtype=np.uint8) """ if not isinstance(hex_color, str): return np.array([255, 255, 255], dtype=np.uint8) s = hex_color.lstrip('#') if len(s) != 6: return np.array([255, 255, 255], dtype=np.uint8) return np.array([int(s[i:i+2], 16) for i in (0, 2, 4)], dtype=np.uint8) def resize_image_for_processing(image, max_size=800): """処理用に画像をリサイズ(メモリ節約)""" width, height = image.size if max(width, height) > max_size: if width > height: new_width = max_size new_height = int(height * max_size / width) else: new_height = max_size new_width = int(width * max_size / height) return image.resize((new_width, new_height), Image.LANCZOS) return image # ======================== # Twitter隠し絵機能 # ======================== def adjust_image(image, brightness=0, contrast=0, saturation=0, gamma=1.0): """画像の色調補正""" if image is None: return None if isinstance(image, np.ndarray): image = Image.fromarray(image) image = image.convert('RGB') if brightness != 0: image = ImageEnhance.Brightness(image).enhance(1 + brightness / 100.0) if contrast != 0: image = ImageEnhance.Contrast(image).enhance(1 + contrast / 100.0) if saturation != 0: image = ImageEnhance.Color(image).enhance(1 + saturation / 100.0) if gamma != 1.0: table = [int(((i / 255.0) ** (1.0 / gamma)) * 255) for i in range(256)] image = image.point(table * 3) return image def extract_line_art(image, method="canny", canny_low=50, canny_high=150, blur_before=1, invert=True, enhance_contrast=1.2): """画像から線画を抽出する""" if image is None: return None img_array = np.array(image.convert('RGB')) gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY) if blur_before > 0: gray = cv2.GaussianBlur(gray, (blur_before*2+1, blur_before*2+1), 0) if method == "canny": edges = cv2.Canny(gray, canny_low, canny_high) elif method == "sobel": sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3) edges = np.sqrt(sobelx**2 + sobely**2) edges = np.uint8(np.clip(edges, 0, 255)) elif method == "laplacian": edges = cv2.Laplacian(gray, cv2.CV_64F) edges = np.uint8(np.absolute(edges)) else: edges = cv2.Canny(gray, canny_low, canny_high) if invert: edges = 255 - edges edges_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) result = Image.fromarray(edges_rgb) if enhance_contrast != 1.0: result = ImageEnhance.Contrast(result).enhance(enhance_contrast) return result def create_alpha_mask_from_hidden(hidden_image, threshold=128, blur_radius=1, soften=0): """隠し画像からアルファマスク生成""" if hidden_image is None: return None h_rgb = hidden_image.convert('RGB') h_arr = np.array(h_rgb) gray = cv2.cvtColor(h_arr, cv2.COLOR_RGB2GRAY) if blur_radius > 0: k = blur_radius * 2 + 1 gray = cv2.GaussianBlur(gray, (k, k), 0) if soften <= 0: alpha = np.where(gray < threshold, 0, 255).astype(np.uint8) else: low = threshold - soften high = threshold + soften alpha = np.zeros_like(gray, dtype=np.float32) alpha = np.where(gray <= low, 0.0, alpha) alpha = np.where(gray >= high, 255.0, alpha) between = (gray > low) & (gray < high) alpha[between] = ((gray[between] - low) / (high - low)) * 255.0 alpha = np.clip(alpha, 0, 255).astype(np.uint8) return alpha def save_transparent_png(image): """透過PNG画像を一時ファイルに保存してファイルパスを返す""" if image is None: return None temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png') temp_file.close() if image.mode != 'RGBA': image = image.convert('RGBA') image.save(temp_file.name, 'PNG', optimize=True) return temp_file.name def preview_normal_adjustment(image, brightness=0, contrast=0, saturation=0, gamma=1.0, enable_line_art=False, line_method="canny", canny_low=50, canny_high=150, blur_before=1): """通常画像の調整プレビュー""" if image is None: return None adjusted = adjust_image(image, brightness, contrast, saturation, gamma) if enable_line_art: adjusted = extract_line_art(adjusted, method=line_method, canny_low=canny_low, canny_high=canny_high, blur_before=blur_before) return adjusted def preview_hidden_adjustment(image, brightness=0, contrast=0, saturation=0, gamma=1.0, enable_line_art=False, line_method="canny", canny_low=50, canny_high=150, blur_before=1): """隠し画像の調整プレビュー""" if image is None: return None adjusted = adjust_image(image, brightness, contrast, saturation, gamma) if enable_line_art: adjusted = extract_line_art(adjusted, method=line_method, canny_low=canny_low, canny_high=canny_high, blur_before=blur_before) return adjusted def generate_twitter_hidden_image_advanced( normal_image, hidden_image, normal_brightness=0, normal_contrast=0, normal_saturation=0, normal_gamma=1.0, normal_line_art=False, normal_line_method="canny", normal_canny_low=50, normal_canny_high=150, normal_blur_before=1, hidden_brightness=0, hidden_contrast=0, hidden_saturation=0, hidden_gamma=1.0, hidden_line_art=False, hidden_line_method="canny", hidden_canny_low=50, hidden_canny_high=150, hidden_blur_before=1, output_size=900, mask_blur=1, mask_threshold=128, mask_soften=0 ): """透過PNG生成関数""" if normal_image is None or hidden_image is None: return None, None, None, None, None try: size = (output_size, output_size) # 通常画像の処理 adjusted_normal = adjust_image(normal_image, normal_brightness, normal_contrast, normal_saturation, normal_gamma) if normal_line_art: adjusted_normal = extract_line_art(adjusted_normal, method=normal_line_method, canny_low=normal_canny_low, canny_high=normal_canny_high, blur_before=normal_blur_before) adjusted_normal = adjusted_normal.resize(size, Image.Resampling.LANCZOS) normal_rgb = adjusted_normal.convert('RGB') # 隠し画像の処理 adjusted_hidden = adjust_image(hidden_image, hidden_brightness, hidden_contrast, hidden_saturation, hidden_gamma) if hidden_line_art: adjusted_hidden = extract_line_art(adjusted_hidden, method=hidden_line_method, canny_low=hidden_canny_low, canny_high=hidden_canny_high, blur_before=hidden_blur_before) adjusted_hidden = adjusted_hidden.resize(size, Image.Resampling.LANCZOS) # アルファマスク生成 alpha_mask = create_alpha_mask_from_hidden(adjusted_hidden, threshold=mask_threshold, blur_radius=mask_blur, soften=mask_soften) # RGBA画像作成 base_rgba = normal_rgb.convert('RGBA') alpha_pil = Image.fromarray(alpha_mask, mode='L') base_rgba.putalpha(alpha_pil) # プレビュー作成 h_preview_arr = np.dstack([np.array(adjusted_hidden.convert('RGB')), alpha_mask]) hidden_layer_preview = Image.fromarray(h_preview_arr, mode='RGBA') white_bg = Image.new('RGBA', size, (255, 255, 255, 255)) light_preview_rgba = Image.alpha_composite(white_bg, base_rgba) light_preview = light_preview_rgba.convert('RGB') dark_bg = Image.new('RGBA', size, (21, 32, 43, 255)) dark_preview_rgba = Image.alpha_composite(dark_bg, base_rgba) dark_preview = ImageEnhance.Contrast(dark_preview_rgba.convert('RGB')).enhance(1.12) result = base_rgba download_file = save_transparent_png(result) return result, light_preview, dark_preview, hidden_layer_preview, download_file except Exception as e: print("エラーが発生しました:", e) return None, None, None, None, None # ======================== # 透過ツール機能 # ======================== def rgb_to_hex(rgb): """ [r,g,b] or (r,g,b) -> '#rrggbb' """ r, g, b = int(rgb[0]), int(rgb[1]), int(rgb[2]) return f"#{r:02x}{g:02x}{b:02x}" def build_palette_html(colors): """色パレットをHTMLで表示""" if not colors: return "
パレットは空です。画像をクリックして色を追加してください。
" parts = [] for i, c in enumerate(colors): parts.append(f"
" f"
" f"
{i+1}
" f"
") return "
" + "".join(parts) + "
" def create_simple_mask(img_cv, method='simple'): """シンプルなマスク生成""" height, width = img_cv.shape[:2] mask = np.zeros((height, width), np.uint8) try: if method == 'simple': hsv = cv2.cvtColor(img_cv, cv2.COLOR_BGR2HSV) lower_blue = np.array([100, 50, 30]) upper_blue = np.array([130, 255, 150]) blue_mask = cv2.inRange(hsv, lower_blue, upper_blue) border_width = max(3, min(width, height) // 100) mask[:border_width, :] = cv2.GC_BGD mask[-border_width:, :] = cv2.GC_BGD mask[:, :border_width] = cv2.GC_BGD mask[:, -border_width:] = cv2.GC_BGD for y in range(height): for x in range(width): if blue_mask[y, x] > 0 and mask[y, x] == cv2.GC_BGD: continue elif mask[y, x] == cv2.GC_BGD: mask[y, x] = cv2.GC_PR_FGD center_margin = max(20, min(width, height) // 20) mask[center_margin:-center_margin, center_margin:-center_margin] = cv2.GC_PR_FGD elif method == 'minimal': border_width = 2 mask[:border_width, :] = cv2.GC_BGD mask[-border_width:, :] = cv2.GC_BGD mask[:, :border_width] = cv2.GC_BGD mask[:, -border_width:] = cv2.GC_BGD mask[mask == 0] = cv2.GC_PR_FGD except Exception as e: print(f"マスク生成エラー: {e}") border = max(5, min(width, height) // 50) mask[border:-border, border:-border] = cv2.GC_PR_FGD return mask def remove_background_grabcut(image, iter_count=5, blur_kernel=3, mask_method='simple'): """GrabCutを使用した背景除去""" try: original_size = image.size processed_image = resize_image_for_processing(image, max_size=600) img_array = np.array(processed_image.convert('RGB')) img_cv = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) height, width = img_cv.shape[:2] mask = create_simple_mask(img_cv, method=mask_method) bgd_model = np.zeros((1, 65), np.float64) fgd_model = np.zeros((1, 65), np.float64) iter_count = min(int(iter_count), 8) cv2.grabCut(img_cv, mask, None, bgd_model, fgd_model, iter_count, cv2.GC_INIT_WITH_MASK) mask2 = np.where((mask == cv2.GC_BGD) | (mask == cv2.GC_PR_BGD), 0, 1).astype('uint8') if blur_kernel > 1: k = min(int(blur_kernel), 7) if k % 2 == 0: k += 1 mask2_float = cv2.GaussianBlur(mask2.astype(np.float32), (k, k), 0) mask2 = np.clip(mask2_float * 255.0, 0, 255).astype(np.uint8) else: mask2 = mask2 * 255 result_rgba = np.dstack([img_array, mask2]) result_image = Image.fromarray(result_rgba, 'RGBA') if result_image.size != original_size: result_image = result_image.resize(original_size, Image.LANCZOS) return result_image except Exception as e: print(f"背景除去エラー: {e}") img_array = np.array(image.convert('RGB')) alpha = np.full((img_array.shape[0], img_array.shape[1]), 255, dtype=np.uint8) result_rgba = np.dstack([img_array, alpha]) return Image.fromarray(result_rgba, 'RGBA') def remove_background_by_multiple_colors(pil_image, colors_hex, tolerance=50, feather=5, morph_iter=0): """複数色をまとめて除去する関数""" if pil_image is None: return None if not colors_hex or len(colors_hex) == 0: rgb = np.array(pil_image.convert('RGB')).astype(np.uint8) alpha_full = np.full((rgb.shape[0], rgb.shape[1]), 255, dtype=np.uint8) return Image.fromarray(np.dstack([rgb, alpha_full]), mode="RGBA") try: original_size = pil_image.size processed_image = resize_image_for_processing(pil_image, max_size=800) img_rgb = np.array(processed_image.convert("RGB")).astype(np.float32) h, w = img_rgb.shape[:2] target_rgbs = np.array([hex_to_rgb(hx).astype(np.float32) for hx in colors_hex]) img_exp = img_rgb[:, :, np.newaxis, :] tgt_exp = target_rgbs[np.newaxis, np.newaxis, :, :] diff = img_exp - tgt_exp dist = np.sqrt(np.sum(diff ** 2, axis=3)) mask_bg_any = np.any(dist <= float(tolerance), axis=2).astype(np.uint8) if morph_iter and morph_iter > 0: kernel = np.ones((3, 3), np.uint8) mask_bg_any = cv2.morphologyEx(mask_bg_any, cv2.MORPH_CLOSE, kernel, iterations=int(min(morph_iter, 3))) mask_fg = 1 - mask_bg_any if feather and feather > 0: k = min(int(max(1, round(feather))), 15) k = k if k % 2 == 1 else k + 1 mask_float = mask_fg.astype(np.float32) mask_blurred = cv2.GaussianBlur(mask_float, (k, k), 0) else: mask_blurred = mask_fg.astype(np.float32) alpha = np.clip(mask_blurred * 255.0, 0, 255).astype(np.uint8) result_rgba = np.dstack([img_rgb.astype(np.uint8), alpha]) result_image = Image.fromarray(result_rgba, mode="RGBA") if result_image.size != original_size: result_image = result_image.resize(original_size, Image.LANCZOS) return result_image except Exception as e: print(f"複数色除去エラー: {e}") rgb = np.array(pil_image.convert('RGB')).astype(np.uint8) alpha_full = np.full((rgb.shape[0], rgb.shape[1]), 255, dtype=np.uint8) return Image.fromarray(np.dstack([rgb, alpha_full]), mode="RGBA") def get_color_from_coordinate(image, x, y): """指定座標から色を取得""" if image is None: return "#ffffff" try: img_array = np.array(image.convert('RGB')) height, width = img_array.shape[:2] x, y = int(x), int(y) if 0 <= x < width and 0 <= y < height: r, g, b = img_array[y, x] return f"#{r:02x}{g:02x}{b:02x}" else: return "#ffffff" except Exception: return "#ffffff" def process_image_transparency(image, method, iter_count, blur_kernel, mask_method, palette, tolerance, feather, morph_iter): if image is None: return None try: if method == "AI自動除去 (GrabCut)": return remove_background_grabcut(image, iter_count=int(iter_count), blur_kernel=int(blur_kernel), mask_method=mask_method) else: return remove_background_by_multiple_colors(image, palette, tolerance=tolerance, feather=feather, morph_iter=morph_iter) except Exception as e: print(f"処理エラー: {e}") return None # ======================== # メインインターフェース # ======================== def create_integrated_interface(): with gr.Blocks(title="統合画像処理アプリ", theme=gr.themes.Soft()) as app: gr.Markdown(""" # 🎨 統合画像処理アプリケーション **Twitter隠し絵作成**と**透過処理**の2つの機能を1つのアプリで! """) with gr.Tabs(): # ======================== # タブ1: Twitter隠し絵ジェネレーター # ======================== with gr.TabItem("🎭 Twitter隠し絵ジェネレーター"): gr.Markdown(""" ## Twitter隠し絵ジェネレーター(透過マスク方式) 隠し画像部分をアルファ(透明)として出力します。線画抽出機能付きで、写真からも線画を生成できます。 """) with gr.Row(): with gr.Column(): gr.Markdown("### 通常画像(背景になる画像)") normal_image = gr.Image(label="通常画像をアップロード", type="pil") normal_line_art = gr.Checkbox(label="線画抽出を有効にする", value=False) with gr.Accordion("線画抽出設定", open=False): normal_line_method = gr.Dropdown( choices=["canny", "sobel", "laplacian"], value="canny", label="抽出方法" ) normal_canny_low = gr.Slider(10, 200, 50, step=10, label="Canny低閾値") normal_canny_high = gr.Slider(50, 300, 150, step=10, label="Canny高閾値") normal_blur_before = gr.Slider(0, 5, 1, step=1, label="前処理ぼかし") with gr.Accordion("通常画像の調整", open=False): normal_brightness = gr.Slider(-100, 100, 0, step=5, label="明度") normal_contrast = gr.Slider(-100, 100, 0, step=5, label="コントラスト") normal_saturation = gr.Slider(-100, 100, 0, step=5, label="彩度") normal_gamma = gr.Slider(0.3, 3.0, 1.0, step=0.1, label="ガンマ") normal_preview = gr.Image(label="調整後の通常画像プレビュー", type="pil") with gr.Column(): gr.Markdown("### 隠し画像(線画または写真)") hidden_image = gr.Image(label="隠し画像をアップロード", type="pil") hidden_line_art = gr.Checkbox(label="線画抽出を有効にする", value=False) with gr.Accordion("線画抽出設定", open=False): hidden_line_method = gr.Dropdown( choices=["canny", "sobel", "laplacian"], value="canny", label="抽出方法" ) hidden_canny_low = gr.Slider(10, 200, 50, step=10, label="Canny低閾値") hidden_canny_high = gr.Slider(50, 300, 150, step=10, label="Canny高閾値") hidden_blur_before = gr.Slider(0, 5, 1, step=1, label="前処理ぼかし") with gr.Accordion("隠し画像の調整", open=False): hidden_brightness = gr.Slider(-100, 100, 0, step=5, label="明度") hidden_contrast = gr.Slider(-100, 100, 0, step=5, label="コントラスト") hidden_saturation = gr.Slider(-100, 100, 0, step=5, label="彩度") hidden_gamma = gr.Slider(0.3, 3.0, 1.0, step=0.1, label="ガンマ") hidden_preview = gr.Image(label="調整後の隠し画像プレビュー", type="pil") with gr.Row(): with gr.Column(): output_size = gr.Slider(128, 900, 900, step=1, label="出力サイズ(px)(Twitterは900推奨)") mask_threshold = gr.Slider(0, 255, 180, step=1, label="マスク閾値(低=黒が透明)") with gr.Column(): mask_blur = gr.Slider(0, 10, 0, step=1, label="マスクぼかし(輪郭を柔らかく)") mask_soften = gr.Slider(0, 128, 50, step=1, label="マスクソフト化幅(0=二値)") with gr.Row(): generate_btn = gr.Button("生成(透過PNG)", variant="primary", size="lg") with gr.Row(): with gr.Column(): gr.Markdown("#### ライトモードでの見え方") light_preview = gr.Image(label="ライトプレビュー") with gr.Column(): gr.Markdown("#### ダークモードでの見え方") dark_preview = gr.Image(label="ダークプレビュー") with gr.Row(): with gr.Column(): gr.Markdown("#### 隠しレイヤープレビュー") hidden_layer_preview = gr.Image(label="隠しレイヤープレビュー(アルファ付き)") with gr.Column(): gr.Markdown("#### プレビュー表示") result_image = gr.Image(label="結果プレビュー", type="pil") with gr.Row(): gr.Markdown("#### **🎯 透過PNGダウンロード**") with gr.Row(): download_file = gr.File(label="透過PNG画像をダウンロード", file_count="single") gr.Markdown("**📥 ⬅ このファイルをクリックしてダウンロード**") # Twitter隠し絵のイベントハンドラ normal_controls = [ normal_image, normal_brightness, normal_contrast, normal_saturation, normal_gamma, normal_line_art, normal_line_method, normal_canny_low, normal_canny_high, normal_blur_before ] for control in normal_controls: control.change( fn=preview_normal_adjustment, inputs=normal_controls, outputs=normal_preview ) hidden_controls = [ hidden_image, hidden_brightness, hidden_contrast, hidden_saturation, hidden_gamma, hidden_line_art, hidden_line_method, hidden_canny_low, hidden_canny_high, hidden_blur_before ] for control in hidden_controls: control.change( fn=preview_hidden_adjustment, inputs=hidden_controls, outputs=hidden_preview ) generate_btn.click( fn=generate_twitter_hidden_image_advanced, inputs=[ normal_image, hidden_image, normal_brightness, normal_contrast, normal_saturation, normal_gamma, normal_line_art, normal_line_method, normal_canny_low, normal_canny_high, normal_blur_before, hidden_brightness, hidden_contrast, hidden_saturation, hidden_gamma, hidden_line_art, hidden_line_method, hidden_canny_low, hidden_canny_high, hidden_blur_before, output_size, mask_blur, mask_threshold, mask_soften ], outputs=[result_image, light_preview, dark_preview, hidden_layer_preview, download_file] ) # ======================== # タブ2: 透過ツール # ======================== with gr.TabItem("🎨 透過ツール"): gr.Markdown(""" ## 透過ツール(モバイル最適化版) - **AI自動除去**: フレーム画像の背景を自動除去 - **複数色除去**: クリックで色を登録してまとめて除去 """) with gr.Row(): with gr.Column(scale=1): gr.Markdown("## 📤 入力設定") input_image = gr.Image(label="画像をアップロード", type="pil", format="png", interactive=True) method = gr.Radio( choices=["AI自動除去 (GrabCut)", "複数色除去"], value="AI自動除去 (GrabCut)", label="透過方法" ) with gr.Group() as ai_options: gr.Markdown("### 🤖 AI処理設定") mask_method = gr.Radio( choices=["simple", "minimal"], value="simple", label="処理方法", info="simple: 標準 / minimal: 最軽量" ) iter_count = gr.Slider(1, 8, value=5, step=1, label="処理回数") blur_kernel = gr.Slider(1, 7, value=3, step=2, label="ぼかし強度") with gr.Group(visible=False) as color_options: gr.Markdown("### 🎯 色登録") click_x = gr.Number(label="X座標", value=0, visible=False) click_y = gr.Number(label="Y座標", value=0, visible=False) current_color = gr.ColorPicker(label="選択した色", value="#ffffff") color_preview = gr.HTML(value="
") with gr.Row(): add_color_btn = gr.Button("➕ 追加", size="sm") remove_select = gr.Dropdown(label="削除する色", choices=[], value=None, interactive=True) remove_color_btn = gr.Button("🗑️ 削除", size="sm") clear_palette_btn = gr.Button("🧼 全消去", size="sm") gr.Markdown("### ⚙️ 除去設定") tolerance = gr.Slider(minimum=0, maximum=200, value=60, step=1, label="許容範囲") feather = gr.Slider(minimum=0, maximum=20, value=5, step=1, label="フェザー") morph_iter = gr.Slider(minimum=0, maximum=3, value=0, step=1, label="ノイズ除去") process_btn = gr.Button("🚀 透過処理を実行", variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown("## 📤 色パレット") palette_html = gr.HTML(value="
パレットは空です。
") gr.Markdown("## 📤 処理結果") output_image = gr.Image(label="透過結果", type="pil", format="png", show_download_button=True) # 透過ツールのState palette_state = gr.State([]) # 透過ツールのイベントハンドラ def toggle_options(selected_method): return ( gr.update(visible=(selected_method == "AI自動除去 (GrabCut)")), gr.update(visible=(selected_method == "複数色除去")) ) method.change(fn=toggle_options, inputs=[method], outputs=[ai_options, color_options]) def handle_image_click(image, evt: gr.SelectData): try: if evt is not None and getattr(evt, "index", None) is not None: ix, iy = evt.index[0], evt.index[1] color_hex = get_color_from_coordinate(image, ix, iy) preview_html = f"
{color_hex}" return ix, iy, color_hex, preview_html except Exception: pass return 0, 0, "#ffffff", "
" input_image.select(fn=handle_image_click, inputs=[input_image], outputs=[click_x, click_y, current_color, color_preview]) def add_color(current_color_hex, palette): col = current_color_hex if isinstance(current_color_hex, str) else "#ffffff" if not col.startswith('#'): col = f"#{col}" col = col.lower() palette = list(palette) if palette is not None else [] if col not in palette: palette.append(col) html = build_palette_html(palette) choices = palette.copy() return palette, html, gr.update(choices=choices, value=(choices[-1] if choices else None)) def remove_color(palette, selected_hex): palette = list(palette) if palette is not None else [] if selected_hex in palette: palette.remove(selected_hex) html = build_palette_html(palette) choices = palette.copy() return palette, html, gr.update(choices=choices, value=(choices[-1] if choices else None)) def clear_palette(): palette = [] html = build_palette_html(palette) return palette, html, gr.update(choices=[], value=None) add_color_btn.click(fn=add_color, inputs=[current_color, palette_state], outputs=[palette_state, palette_html, remove_select]) remove_color_btn.click(fn=remove_color, inputs=[palette_state, remove_select], outputs=[palette_state, palette_html, remove_select]) clear_palette_btn.click(fn=clear_palette, inputs=None, outputs=[palette_state, palette_html, remove_select]) process_btn.click( fn=process_image_transparency, inputs=[input_image, method, iter_count, blur_kernel, mask_method, palette_state, tolerance, feather, morph_iter], outputs=[output_image] ) # 共通の使い方説明 gr.Markdown(""" ## 📋 全体の使い方 ### 🎭 Twitter隠し絵ジェネレーター 1. **通常画像**: 背景として表示される画像をアップロード 2. **隠し画像**: 隠したい画像をアップロード(写真でも線画でもOK) 3. **線画抽出**: チェックボックスをONにすると写真から線画を自動抽出 4. **調整スライダー**: 各画像の明度・コントラスト等を調整 5. **生成ボタンを押して、ダウンロードファイルから透過PNGを保存** ### 🎨 透過ツール **AI自動除去の場合:** - フレーム画像の背景を自動で検出・除去 **複数色除去の場合:** 1. 画像をクリックして色を取得 2. 「➕ 追加」でパレットに登録 3. 複数色を登録後「透過処理を実行」 ## 💡 ポイント - 両方のツールとも透過PNG形式で出力されます - モバイル環境でも快適に動作するよう最適化済み - エラーが発生した場合は設定を調整してお試しください """) return app if __name__ == "__main__": app = create_integrated_interface() app.launch(server_name="0.0.0.0", server_port=7860, share=False)