Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,201 +1,727 @@
|
|
| 1 |
-
#
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
-
|
| 5 |
-
|
| 6 |
-
- マスクの白黒どちらが「見せたい部分」かを UI で切替可能。
|
| 7 |
-
- パラメータで白さの出方を制御(max_alpha, gamma, blur)。
|
| 8 |
-
- 依存: gradio, pillow, numpy
|
| 9 |
"""
|
| 10 |
-
|
| 11 |
-
from PIL import Image, ImageFilter
|
| 12 |
-
import numpy as np
|
| 13 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
return None
|
| 38 |
-
if isinstance(
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 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 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 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 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
return
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
if __name__ == "__main__":
|
| 200 |
-
|
| 201 |
-
|
|
|
|
| 1 |
+
# integrated_app.py
|
| 2 |
"""
|
| 3 |
+
統合画像処理アプリケーション
|
| 4 |
+
- タブ1: Twitter隠し絵ジェネレーター(透過マスク方式)
|
| 5 |
+
- タブ2: 透過ツール(モバイル最適化版 + 複数色パレット対応)
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
+
|
|
|
|
|
|
|
| 8 |
import gradio as gr
|
| 9 |
+
import numpy as np
|
| 10 |
+
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
|
| 11 |
+
import cv2
|
| 12 |
+
import warnings
|
| 13 |
+
import tempfile
|
| 14 |
+
import os
|
| 15 |
+
warnings.filterwarnings('ignore')
|
| 16 |
|
| 17 |
+
# ========================
|
| 18 |
+
# 共通ユーティリティ関数
|
| 19 |
+
# ========================
|
| 20 |
+
|
| 21 |
+
def hex_to_rgb(hex_color: str):
|
| 22 |
+
""" '#rrggbb' -> np.array([r,g,b], dtype=np.uint8) """
|
| 23 |
+
if not isinstance(hex_color, str):
|
| 24 |
+
return np.array([255, 255, 255], dtype=np.uint8)
|
| 25 |
+
s = hex_color.lstrip('#')
|
| 26 |
+
if len(s) != 6:
|
| 27 |
+
return np.array([255, 255, 255], dtype=np.uint8)
|
| 28 |
+
return np.array([int(s[i:i+2], 16) for i in (0, 2, 4)], dtype=np.uint8)
|
| 29 |
+
|
| 30 |
+
def resize_image_for_processing(image, max_size=800):
|
| 31 |
+
"""処理用に画像をリサイズ(メモリ節約)"""
|
| 32 |
+
width, height = image.size
|
| 33 |
+
if max(width, height) > max_size:
|
| 34 |
+
if width > height:
|
| 35 |
+
new_width = max_size
|
| 36 |
+
new_height = int(height * max_size / width)
|
| 37 |
+
else:
|
| 38 |
+
new_height = max_size
|
| 39 |
+
new_width = int(width * max_size / height)
|
| 40 |
+
return image.resize((new_width, new_height), Image.LANCZOS)
|
| 41 |
+
return image
|
| 42 |
+
|
| 43 |
+
# ========================
|
| 44 |
+
# Twitter隠し絵機能
|
| 45 |
+
# ========================
|
| 46 |
+
|
| 47 |
+
def adjust_image(image, brightness=0, contrast=0, saturation=0, gamma=1.0):
|
| 48 |
+
"""画像の色調補正"""
|
| 49 |
+
if image is None:
|
| 50 |
return None
|
| 51 |
+
if isinstance(image, np.ndarray):
|
| 52 |
+
image = Image.fromarray(image)
|
| 53 |
+
image = image.convert('RGB')
|
| 54 |
+
if brightness != 0:
|
| 55 |
+
image = ImageEnhance.Brightness(image).enhance(1 + brightness / 100.0)
|
| 56 |
+
if contrast != 0:
|
| 57 |
+
image = ImageEnhance.Contrast(image).enhance(1 + contrast / 100.0)
|
| 58 |
+
if saturation != 0:
|
| 59 |
+
image = ImageEnhance.Color(image).enhance(1 + saturation / 100.0)
|
| 60 |
+
if gamma != 1.0:
|
| 61 |
+
table = [int(((i / 255.0) ** (1.0 / gamma)) * 255) for i in range(256)]
|
| 62 |
+
image = image.point(table * 3)
|
| 63 |
+
return image
|
| 64 |
+
|
| 65 |
+
def extract_line_art(image, method="canny", canny_low=50, canny_high=150,
|
| 66 |
+
blur_before=1, invert=True, enhance_contrast=1.2):
|
| 67 |
+
"""画像から線画を抽出する"""
|
| 68 |
+
if image is None:
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
img_array = np.array(image.convert('RGB'))
|
| 72 |
+
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
|
| 73 |
+
|
| 74 |
+
if blur_before > 0:
|
| 75 |
+
gray = cv2.GaussianBlur(gray, (blur_before*2+1, blur_before*2+1), 0)
|
| 76 |
+
|
| 77 |
+
if method == "canny":
|
| 78 |
+
edges = cv2.Canny(gray, canny_low, canny_high)
|
| 79 |
+
elif method == "sobel":
|
| 80 |
+
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
|
| 81 |
+
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
|
| 82 |
+
edges = np.sqrt(sobelx**2 + sobely**2)
|
| 83 |
+
edges = np.uint8(np.clip(edges, 0, 255))
|
| 84 |
+
elif method == "laplacian":
|
| 85 |
+
edges = cv2.Laplacian(gray, cv2.CV_64F)
|
| 86 |
+
edges = np.uint8(np.absolute(edges))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
else:
|
| 88 |
+
edges = cv2.Canny(gray, canny_low, canny_high)
|
| 89 |
+
|
| 90 |
+
if invert:
|
| 91 |
+
edges = 255 - edges
|
| 92 |
+
|
| 93 |
+
edges_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
|
| 94 |
+
result = Image.fromarray(edges_rgb)
|
| 95 |
+
|
| 96 |
+
if enhance_contrast != 1.0:
|
| 97 |
+
result = ImageEnhance.Contrast(result).enhance(enhance_contrast)
|
| 98 |
+
|
| 99 |
+
return result
|
| 100 |
+
|
| 101 |
+
def create_alpha_mask_from_hidden(hidden_image, threshold=128, blur_radius=1, soften=0):
|
| 102 |
+
"""隠し画像からアルファマスク生成"""
|
| 103 |
+
if hidden_image is None:
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
h_rgb = hidden_image.convert('RGB')
|
| 107 |
+
h_arr = np.array(h_rgb)
|
| 108 |
+
gray = cv2.cvtColor(h_arr, cv2.COLOR_RGB2GRAY)
|
| 109 |
+
|
| 110 |
+
if blur_radius > 0:
|
| 111 |
+
k = blur_radius * 2 + 1
|
| 112 |
+
gray = cv2.GaussianBlur(gray, (k, k), 0)
|
| 113 |
+
|
| 114 |
+
if soften <= 0:
|
| 115 |
+
alpha = np.where(gray < threshold, 0, 255).astype(np.uint8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
else:
|
| 117 |
+
low = threshold - soften
|
| 118 |
+
high = threshold + soften
|
| 119 |
+
alpha = np.zeros_like(gray, dtype=np.float32)
|
| 120 |
+
alpha = np.where(gray <= low, 0.0, alpha)
|
| 121 |
+
alpha = np.where(gray >= high, 255.0, alpha)
|
| 122 |
+
between = (gray > low) & (gray < high)
|
| 123 |
+
alpha[between] = ((gray[between] - low) / (high - low)) * 255.0
|
| 124 |
+
alpha = np.clip(alpha, 0, 255).astype(np.uint8)
|
| 125 |
+
|
| 126 |
+
return alpha
|
| 127 |
+
|
| 128 |
+
def save_transparent_png(image):
|
| 129 |
+
"""透過PNG画像を一時ファイルに保存してファイルパスを返す"""
|
| 130 |
+
if image is None:
|
| 131 |
+
return None
|
| 132 |
+
|
| 133 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
|
| 134 |
+
temp_file.close()
|
| 135 |
+
|
| 136 |
+
if image.mode != 'RGBA':
|
| 137 |
+
image = image.convert('RGBA')
|
| 138 |
+
|
| 139 |
+
image.save(temp_file.name, 'PNG', optimize=True)
|
| 140 |
+
return temp_file.name
|
| 141 |
+
|
| 142 |
+
def preview_normal_adjustment(image, brightness=0, contrast=0, saturation=0, gamma=1.0,
|
| 143 |
+
enable_line_art=False, line_method="canny",
|
| 144 |
+
canny_low=50, canny_high=150, blur_before=1):
|
| 145 |
+
"""通常画像の調整プレビュー"""
|
| 146 |
+
if image is None:
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
adjusted = adjust_image(image, brightness, contrast, saturation, gamma)
|
| 150 |
+
|
| 151 |
+
if enable_line_art:
|
| 152 |
+
adjusted = extract_line_art(adjusted, method=line_method,
|
| 153 |
+
canny_low=canny_low, canny_high=canny_high,
|
| 154 |
+
blur_before=blur_before)
|
| 155 |
+
|
| 156 |
+
return adjusted
|
| 157 |
+
|
| 158 |
+
def preview_hidden_adjustment(image, brightness=0, contrast=0, saturation=0, gamma=1.0,
|
| 159 |
+
enable_line_art=False, line_method="canny",
|
| 160 |
+
canny_low=50, canny_high=150, blur_before=1):
|
| 161 |
+
"""隠し画像の調整プレビュー"""
|
| 162 |
+
if image is None:
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
adjusted = adjust_image(image, brightness, contrast, saturation, gamma)
|
| 166 |
+
|
| 167 |
+
if enable_line_art:
|
| 168 |
+
adjusted = extract_line_art(adjusted, method=line_method,
|
| 169 |
+
canny_low=canny_low, canny_high=canny_high,
|
| 170 |
+
blur_before=blur_before)
|
| 171 |
+
|
| 172 |
+
return adjusted
|
| 173 |
+
|
| 174 |
+
def generate_twitter_hidden_image_advanced(
|
| 175 |
+
normal_image, hidden_image,
|
| 176 |
+
normal_brightness=0, normal_contrast=0, normal_saturation=0, normal_gamma=1.0,
|
| 177 |
+
normal_line_art=False, normal_line_method="canny", normal_canny_low=50, normal_canny_high=150, normal_blur_before=1,
|
| 178 |
+
hidden_brightness=0, hidden_contrast=0, hidden_saturation=0, hidden_gamma=1.0,
|
| 179 |
+
hidden_line_art=False, hidden_line_method="canny", hidden_canny_low=50, hidden_canny_high=150, hidden_blur_before=1,
|
| 180 |
+
output_size=900, mask_blur=1, mask_threshold=128, mask_soften=0
|
| 181 |
+
):
|
| 182 |
+
"""透過PNG生成関数"""
|
| 183 |
+
if normal_image is None or hidden_image is None:
|
| 184 |
+
return None, None, None, None, None
|
| 185 |
+
|
| 186 |
+
try:
|
| 187 |
+
size = (output_size, output_size)
|
| 188 |
+
|
| 189 |
+
# 通常画像の処理
|
| 190 |
+
adjusted_normal = adjust_image(normal_image, normal_brightness, normal_contrast,
|
| 191 |
+
normal_saturation, normal_gamma)
|
| 192 |
+
if normal_line_art:
|
| 193 |
+
adjusted_normal = extract_line_art(adjusted_normal, method=normal_line_method,
|
| 194 |
+
canny_low=normal_canny_low, canny_high=normal_canny_high,
|
| 195 |
+
blur_before=normal_blur_before)
|
| 196 |
+
adjusted_normal = adjusted_normal.resize(size, Image.Resampling.LANCZOS)
|
| 197 |
+
normal_rgb = adjusted_normal.convert('RGB')
|
| 198 |
+
|
| 199 |
+
# 隠し画像の処理
|
| 200 |
+
adjusted_hidden = adjust_image(hidden_image, hidden_brightness, hidden_contrast,
|
| 201 |
+
hidden_saturation, hidden_gamma)
|
| 202 |
+
if hidden_line_art:
|
| 203 |
+
adjusted_hidden = extract_line_art(adjusted_hidden, method=hidden_line_method,
|
| 204 |
+
canny_low=hidden_canny_low, canny_high=hidden_canny_high,
|
| 205 |
+
blur_before=hidden_blur_before)
|
| 206 |
+
adjusted_hidden = adjusted_hidden.resize(size, Image.Resampling.LANCZOS)
|
| 207 |
+
|
| 208 |
+
# アルファマスク生成
|
| 209 |
+
alpha_mask = create_alpha_mask_from_hidden(adjusted_hidden, threshold=mask_threshold,
|
| 210 |
+
blur_radius=mask_blur, soften=mask_soften)
|
| 211 |
+
|
| 212 |
+
# RGBA画像作成
|
| 213 |
+
base_rgba = normal_rgb.convert('RGBA')
|
| 214 |
+
alpha_pil = Image.fromarray(alpha_mask, mode='L')
|
| 215 |
+
base_rgba.putalpha(alpha_pil)
|
| 216 |
+
|
| 217 |
+
# プレビュー作成
|
| 218 |
+
h_preview_arr = np.dstack([np.array(adjusted_hidden.convert('RGB')), alpha_mask])
|
| 219 |
+
hidden_layer_preview = Image.fromarray(h_preview_arr, mode='RGBA')
|
| 220 |
+
|
| 221 |
+
white_bg = Image.new('RGBA', size, (255, 255, 255, 255))
|
| 222 |
+
light_preview_rgba = Image.alpha_composite(white_bg, base_rgba)
|
| 223 |
+
light_preview = light_preview_rgba.convert('RGB')
|
| 224 |
+
|
| 225 |
+
dark_bg = Image.new('RGBA', size, (21, 32, 43, 255))
|
| 226 |
+
dark_preview_rgba = Image.alpha_composite(dark_bg, base_rgba)
|
| 227 |
+
dark_preview = ImageEnhance.Contrast(dark_preview_rgba.convert('RGB')).enhance(1.12)
|
| 228 |
+
|
| 229 |
+
result = base_rgba
|
| 230 |
+
download_file = save_transparent_png(result)
|
| 231 |
+
|
| 232 |
+
return result, light_preview, dark_preview, hidden_layer_preview, download_file
|
| 233 |
+
|
| 234 |
+
except Exception as e:
|
| 235 |
+
print("エラーが発生しました:", e)
|
| 236 |
+
return None, None, None, None, None
|
| 237 |
+
|
| 238 |
+
# ========================
|
| 239 |
+
# 透過ツール機能
|
| 240 |
+
# ========================
|
| 241 |
+
|
| 242 |
+
def rgb_to_hex(rgb):
|
| 243 |
+
""" [r,g,b] or (r,g,b) -> '#rrggbb' """
|
| 244 |
+
r, g, b = int(rgb[0]), int(rgb[1]), int(rgb[2])
|
| 245 |
+
return f"#{r:02x}{g:02x}{b:02x}"
|
| 246 |
+
|
| 247 |
+
def build_palette_html(colors):
|
| 248 |
+
"""色パレットをHTMLで表示"""
|
| 249 |
+
if not colors:
|
| 250 |
+
return "<div style='color:#666;padding:10px;'>パレットは空です。画像をクリックして色を追加してください。</div>"
|
| 251 |
+
parts = []
|
| 252 |
+
for i, c in enumerate(colors):
|
| 253 |
+
parts.append(f"<div style='display:inline-block;margin:2px;padding:2px;text-align:center;'>"
|
| 254 |
+
f"<div style='width:32px;height:20px;background-color:{c};border:1px solid #ccc;'></div>"
|
| 255 |
+
f"<div style='font-size:11px;margin-top:2px;'>{i+1}</div>"
|
| 256 |
+
f"</div>")
|
| 257 |
+
return "<div style='display:flex;flex-wrap:wrap;padding:5px;'>" + "".join(parts) + "</div>"
|
| 258 |
+
|
| 259 |
+
def create_simple_mask(img_cv, method='simple'):
|
| 260 |
+
"""シンプルなマスク生成"""
|
| 261 |
+
height, width = img_cv.shape[:2]
|
| 262 |
+
mask = np.zeros((height, width), np.uint8)
|
| 263 |
+
|
| 264 |
+
try:
|
| 265 |
+
if method == 'simple':
|
| 266 |
+
hsv = cv2.cvtColor(img_cv, cv2.COLOR_BGR2HSV)
|
| 267 |
+
lower_blue = np.array([100, 50, 30])
|
| 268 |
+
upper_blue = np.array([130, 255, 150])
|
| 269 |
+
blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)
|
| 270 |
+
|
| 271 |
+
border_width = max(3, min(width, height) // 100)
|
| 272 |
+
mask[:border_width, :] = cv2.GC_BGD
|
| 273 |
+
mask[-border_width:, :] = cv2.GC_BGD
|
| 274 |
+
mask[:, :border_width] = cv2.GC_BGD
|
| 275 |
+
mask[:, -border_width:] = cv2.GC_BGD
|
| 276 |
+
|
| 277 |
+
for y in range(height):
|
| 278 |
+
for x in range(width):
|
| 279 |
+
if blue_mask[y, x] > 0 and mask[y, x] == cv2.GC_BGD:
|
| 280 |
+
continue
|
| 281 |
+
elif mask[y, x] == cv2.GC_BGD:
|
| 282 |
+
mask[y, x] = cv2.GC_PR_FGD
|
| 283 |
+
|
| 284 |
+
center_margin = max(20, min(width, height) // 20)
|
| 285 |
+
mask[center_margin:-center_margin, center_margin:-center_margin] = cv2.GC_PR_FGD
|
| 286 |
+
|
| 287 |
+
elif method == 'minimal':
|
| 288 |
+
border_width = 2
|
| 289 |
+
mask[:border_width, :] = cv2.GC_BGD
|
| 290 |
+
mask[-border_width:, :] = cv2.GC_BGD
|
| 291 |
+
mask[:, :border_width] = cv2.GC_BGD
|
| 292 |
+
mask[:, -border_width:] = cv2.GC_BGD
|
| 293 |
+
mask[mask == 0] = cv2.GC_PR_FGD
|
| 294 |
+
|
| 295 |
+
except Exception as e:
|
| 296 |
+
print(f"マスク生成エラー: {e}")
|
| 297 |
+
border = max(5, min(width, height) // 50)
|
| 298 |
+
mask[border:-border, border:-border] = cv2.GC_PR_FGD
|
| 299 |
+
|
| 300 |
+
return mask
|
| 301 |
+
|
| 302 |
+
def remove_background_grabcut(image, iter_count=5, blur_kernel=3, mask_method='simple'):
|
| 303 |
+
"""GrabCutを使用した背景除去"""
|
| 304 |
+
try:
|
| 305 |
+
original_size = image.size
|
| 306 |
+
processed_image = resize_image_for_processing(image, max_size=600)
|
| 307 |
+
|
| 308 |
+
img_array = np.array(processed_image.convert('RGB'))
|
| 309 |
+
img_cv = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
|
| 310 |
+
height, width = img_cv.shape[:2]
|
| 311 |
+
|
| 312 |
+
mask = create_simple_mask(img_cv, method=mask_method)
|
| 313 |
+
|
| 314 |
+
bgd_model = np.zeros((1, 65), np.float64)
|
| 315 |
+
fgd_model = np.zeros((1, 65), np.float64)
|
| 316 |
+
|
| 317 |
+
iter_count = min(int(iter_count), 8)
|
| 318 |
+
cv2.grabCut(img_cv, mask, None, bgd_model, fgd_model, iter_count, cv2.GC_INIT_WITH_MASK)
|
| 319 |
+
|
| 320 |
+
mask2 = np.where((mask == cv2.GC_BGD) | (mask == cv2.GC_PR_BGD), 0, 1).astype('uint8')
|
| 321 |
+
|
| 322 |
+
if blur_kernel > 1:
|
| 323 |
+
k = min(int(blur_kernel), 7)
|
| 324 |
+
if k % 2 == 0:
|
| 325 |
+
k += 1
|
| 326 |
+
mask2_float = cv2.GaussianBlur(mask2.astype(np.float32), (k, k), 0)
|
| 327 |
+
mask2 = np.clip(mask2_float * 255.0, 0, 255).astype(np.uint8)
|
| 328 |
+
else:
|
| 329 |
+
mask2 = mask2 * 255
|
| 330 |
+
|
| 331 |
+
result_rgba = np.dstack([img_array, mask2])
|
| 332 |
+
result_image = Image.fromarray(result_rgba, 'RGBA')
|
| 333 |
+
|
| 334 |
+
if result_image.size != original_size:
|
| 335 |
+
result_image = result_image.resize(original_size, Image.LANCZOS)
|
| 336 |
+
|
| 337 |
+
return result_image
|
| 338 |
+
|
| 339 |
+
except Exception as e:
|
| 340 |
+
print(f"背景除去エラー: {e}")
|
| 341 |
+
img_array = np.array(image.convert('RGB'))
|
| 342 |
+
alpha = np.full((img_array.shape[0], img_array.shape[1]), 255, dtype=np.uint8)
|
| 343 |
+
result_rgba = np.dstack([img_array, alpha])
|
| 344 |
+
return Image.fromarray(result_rgba, 'RGBA')
|
| 345 |
+
|
| 346 |
+
def remove_background_by_multiple_colors(pil_image, colors_hex, tolerance=50, feather=5, morph_iter=0):
|
| 347 |
+
"""複数色をまとめて除去する関数"""
|
| 348 |
+
if pil_image is None:
|
| 349 |
+
return None
|
| 350 |
+
|
| 351 |
+
if not colors_hex or len(colors_hex) == 0:
|
| 352 |
+
rgb = np.array(pil_image.convert('RGB')).astype(np.uint8)
|
| 353 |
+
alpha_full = np.full((rgb.shape[0], rgb.shape[1]), 255, dtype=np.uint8)
|
| 354 |
+
return Image.fromarray(np.dstack([rgb, alpha_full]), mode="RGBA")
|
| 355 |
+
|
| 356 |
+
try:
|
| 357 |
+
original_size = pil_image.size
|
| 358 |
+
processed_image = resize_image_for_processing(pil_image, max_size=800)
|
| 359 |
+
|
| 360 |
+
img_rgb = np.array(processed_image.convert("RGB")).astype(np.float32)
|
| 361 |
+
h, w = img_rgb.shape[:2]
|
| 362 |
+
|
| 363 |
+
target_rgbs = np.array([hex_to_rgb(hx).astype(np.float32) for hx in colors_hex])
|
| 364 |
+
|
| 365 |
+
img_exp = img_rgb[:, :, np.newaxis, :]
|
| 366 |
+
tgt_exp = target_rgbs[np.newaxis, np.newaxis, :, :]
|
| 367 |
+
diff = img_exp - tgt_exp
|
| 368 |
+
dist = np.sqrt(np.sum(diff ** 2, axis=3))
|
| 369 |
+
mask_bg_any = np.any(dist <= float(tolerance), axis=2).astype(np.uint8)
|
| 370 |
+
|
| 371 |
+
if morph_iter and morph_iter > 0:
|
| 372 |
+
kernel = np.ones((3, 3), np.uint8)
|
| 373 |
+
mask_bg_any = cv2.morphologyEx(mask_bg_any, cv2.MORPH_CLOSE, kernel, iterations=int(min(morph_iter, 3)))
|
| 374 |
+
|
| 375 |
+
mask_fg = 1 - mask_bg_any
|
| 376 |
+
|
| 377 |
+
if feather and feather > 0:
|
| 378 |
+
k = min(int(max(1, round(feather))), 15)
|
| 379 |
+
k = k if k % 2 == 1 else k + 1
|
| 380 |
+
mask_float = mask_fg.astype(np.float32)
|
| 381 |
+
mask_blurred = cv2.GaussianBlur(mask_float, (k, k), 0)
|
| 382 |
+
else:
|
| 383 |
+
mask_blurred = mask_fg.astype(np.float32)
|
| 384 |
+
|
| 385 |
+
alpha = np.clip(mask_blurred * 255.0, 0, 255).astype(np.uint8)
|
| 386 |
+
|
| 387 |
+
result_rgba = np.dstack([img_rgb.astype(np.uint8), alpha])
|
| 388 |
+
result_image = Image.fromarray(result_rgba, mode="RGBA")
|
| 389 |
+
|
| 390 |
+
if result_image.size != original_size:
|
| 391 |
+
result_image = result_image.resize(original_size, Image.LANCZOS)
|
| 392 |
+
|
| 393 |
+
return result_image
|
| 394 |
+
|
| 395 |
+
except Exception as e:
|
| 396 |
+
print(f"複数色除去エラー: {e}")
|
| 397 |
+
rgb = np.array(pil_image.convert('RGB')).astype(np.uint8)
|
| 398 |
+
alpha_full = np.full((rgb.shape[0], rgb.shape[1]), 255, dtype=np.uint8)
|
| 399 |
+
return Image.fromarray(np.dstack([rgb, alpha_full]), mode="RGBA")
|
| 400 |
+
|
| 401 |
+
def get_color_from_coordinate(image, x, y):
|
| 402 |
+
"""指定座標から色を取得"""
|
| 403 |
+
if image is None:
|
| 404 |
+
return "#ffffff"
|
| 405 |
+
try:
|
| 406 |
+
img_array = np.array(image.convert('RGB'))
|
| 407 |
+
height, width = img_array.shape[:2]
|
| 408 |
+
x, y = int(x), int(y)
|
| 409 |
+
if 0 <= x < width and 0 <= y < height:
|
| 410 |
+
r, g, b = img_array[y, x]
|
| 411 |
+
return f"#{r:02x}{g:02x}{b:02x}"
|
| 412 |
+
else:
|
| 413 |
+
return "#ffffff"
|
| 414 |
+
except Exception:
|
| 415 |
+
return "#ffffff"
|
| 416 |
+
|
| 417 |
+
def process_image_transparency(image, method, iter_count, blur_kernel, mask_method, palette, tolerance, feather, morph_iter):
|
| 418 |
+
if image is None:
|
| 419 |
+
return None
|
| 420 |
+
|
| 421 |
+
try:
|
| 422 |
+
if method == "AI自動除去 (GrabCut)":
|
| 423 |
+
return remove_background_grabcut(image, iter_count=int(iter_count),
|
| 424 |
+
blur_kernel=int(blur_kernel), mask_method=mask_method)
|
| 425 |
+
else:
|
| 426 |
+
return remove_background_by_multiple_colors(image, palette, tolerance=tolerance,
|
| 427 |
+
feather=feather, morph_iter=morph_iter)
|
| 428 |
+
except Exception as e:
|
| 429 |
+
print(f"処理エラー: {e}")
|
| 430 |
+
return None
|
| 431 |
+
|
| 432 |
+
# ========================
|
| 433 |
+
# メインインターフェース
|
| 434 |
+
# ========================
|
| 435 |
+
|
| 436 |
+
def create_integrated_interface():
|
| 437 |
+
with gr.Blocks(title="統合画像処理アプリ", theme=gr.themes.Soft()) as app:
|
| 438 |
+
gr.Markdown("""
|
| 439 |
+
# 🎨 統合画像処理アプリケーション
|
| 440 |
+
**Twitter隠し絵作成**と**透過処理**の2つの機能を1つのアプリで!
|
| 441 |
+
""")
|
| 442 |
+
|
| 443 |
+
with gr.Tabs():
|
| 444 |
+
# ========================
|
| 445 |
+
# タブ1: Twitter隠し絵ジェネレーター
|
| 446 |
+
# ========================
|
| 447 |
+
with gr.TabItem("🎭 Twitter隠し絵ジェネレーター"):
|
| 448 |
+
gr.Markdown("""
|
| 449 |
+
## Twitter隠し絵ジェネレーター(透過マスク方式)
|
| 450 |
+
隠し画像部分をアルファ(透明)として出力します。線画抽出機能付きで、写真からも線画を生成できます。
|
| 451 |
+
""")
|
| 452 |
+
|
| 453 |
+
with gr.Row():
|
| 454 |
+
with gr.Column():
|
| 455 |
+
gr.Markdown("### 通常画像(背景になる画像)")
|
| 456 |
+
normal_image = gr.Image(label="通常画像をアップロード", type="pil")
|
| 457 |
+
|
| 458 |
+
normal_line_art = gr.Checkbox(label="線画抽出を有効にする", value=False)
|
| 459 |
+
with gr.Accordion("線画抽出設定", open=False):
|
| 460 |
+
normal_line_method = gr.Dropdown(
|
| 461 |
+
choices=["canny", "sobel", "laplacian"],
|
| 462 |
+
value="canny",
|
| 463 |
+
label="抽出方法"
|
| 464 |
+
)
|
| 465 |
+
normal_canny_low = gr.Slider(10, 200, 50, step=10, label="Canny低閾値")
|
| 466 |
+
normal_canny_high = gr.Slider(50, 300, 150, step=10, label="Canny高閾値")
|
| 467 |
+
normal_blur_before = gr.Slider(0, 5, 1, step=1, label="前処理ぼかし")
|
| 468 |
+
|
| 469 |
+
with gr.Accordion("通常画像の調整", open=False):
|
| 470 |
+
normal_brightness = gr.Slider(-100, 100, 0, step=5, label="明度")
|
| 471 |
+
normal_contrast = gr.Slider(-100, 100, 0, step=5, label="コントラスト")
|
| 472 |
+
normal_saturation = gr.Slider(-100, 100, 0, step=5, label="彩度")
|
| 473 |
+
normal_gamma = gr.Slider(0.3, 3.0, 1.0, step=0.1, label="ガンマ")
|
| 474 |
+
|
| 475 |
+
normal_preview = gr.Image(label="調整後の通常画像プレビュー", type="pil")
|
| 476 |
+
|
| 477 |
+
with gr.Column():
|
| 478 |
+
gr.Markdown("### 隠し画像(線画または写真)")
|
| 479 |
+
hidden_image = gr.Image(label="隠し画像をアップロード", type="pil")
|
| 480 |
+
|
| 481 |
+
hidden_line_art = gr.Checkbox(label="線画抽出を有効にする", value=False)
|
| 482 |
+
with gr.Accordion("線画抽出設定", open=False):
|
| 483 |
+
hidden_line_method = gr.Dropdown(
|
| 484 |
+
choices=["canny", "sobel", "laplacian"],
|
| 485 |
+
value="canny",
|
| 486 |
+
label="抽出方法"
|
| 487 |
+
)
|
| 488 |
+
hidden_canny_low = gr.Slider(10, 200, 50, step=10, label="Canny低閾値")
|
| 489 |
+
hidden_canny_high = gr.Slider(50, 300, 150, step=10, label="Canny高閾値")
|
| 490 |
+
hidden_blur_before = gr.Slider(0, 5, 1, step=1, label="前処理ぼかし")
|
| 491 |
+
|
| 492 |
+
with gr.Accordion("隠し画像の調整", open=False):
|
| 493 |
+
hidden_brightness = gr.Slider(-100, 100, 0, step=5, label="明度")
|
| 494 |
+
hidden_contrast = gr.Slider(-100, 100, 0, step=5, label="コントラスト")
|
| 495 |
+
hidden_saturation = gr.Slider(-100, 100, 0, step=5, label="彩度")
|
| 496 |
+
hidden_gamma = gr.Slider(0.3, 3.0, 1.0, step=0.1, label="ガンマ")
|
| 497 |
+
|
| 498 |
+
hidden_preview = gr.Image(label="調整後の隠し画像プレビュー", type="pil")
|
| 499 |
+
|
| 500 |
+
with gr.Row():
|
| 501 |
+
with gr.Column():
|
| 502 |
+
output_size = gr.Slider(128, 900, 900, step=1, label="出力サイズ(px)(Twitterは900推奨)")
|
| 503 |
+
mask_threshold = gr.Slider(0, 255, 180, step=1, label="マスク閾値(低=黒が透明)")
|
| 504 |
+
with gr.Column():
|
| 505 |
+
mask_blur = gr.Slider(0, 10, 0, step=1, label="マスクぼかし(輪郭を柔らかく)")
|
| 506 |
+
mask_soften = gr.Slider(0, 128, 50, step=1, label="マスクソフト化幅(0=二値)")
|
| 507 |
+
|
| 508 |
+
with gr.Row():
|
| 509 |
+
generate_btn = gr.Button("生成(透過PNG)", variant="primary", size="lg")
|
| 510 |
+
|
| 511 |
+
with gr.Row():
|
| 512 |
+
with gr.Column():
|
| 513 |
+
gr.Markdown("#### ライトモードでの見え方")
|
| 514 |
+
light_preview = gr.Image(label="ライトプレビュー")
|
| 515 |
+
with gr.Column():
|
| 516 |
+
gr.Markdown("#### ダークモードでの見え方")
|
| 517 |
+
dark_preview = gr.Image(label="ダークプレビュー")
|
| 518 |
+
|
| 519 |
+
with gr.Row():
|
| 520 |
+
with gr.Column():
|
| 521 |
+
gr.Markdown("#### 隠しレイヤープレビュー")
|
| 522 |
+
hidden_layer_preview = gr.Image(label="隠しレイヤープレビュー(アルファ付き)")
|
| 523 |
+
with gr.Column():
|
| 524 |
+
gr.Markdown("#### プレビュー表示")
|
| 525 |
+
result_image = gr.Image(label="結果プレビュー", type="pil")
|
| 526 |
+
|
| 527 |
+
with gr.Row():
|
| 528 |
+
gr.Markdown("#### **🎯 透過PNGダウンロード**")
|
| 529 |
+
with gr.Row():
|
| 530 |
+
download_file = gr.File(label="透過PNG画像をダウンロード", file_count="single")
|
| 531 |
+
gr.Markdown("**📥 ⬅ このファイルをクリックしてダウンロード**")
|
| 532 |
+
|
| 533 |
+
# Twitter隠し絵のイベントハンドラ
|
| 534 |
+
normal_controls = [
|
| 535 |
+
normal_image, normal_brightness, normal_contrast, normal_saturation, normal_gamma,
|
| 536 |
+
normal_line_art, normal_line_method, normal_canny_low, normal_canny_high, normal_blur_before
|
| 537 |
+
]
|
| 538 |
+
for control in normal_controls:
|
| 539 |
+
control.change(
|
| 540 |
+
fn=preview_normal_adjustment,
|
| 541 |
+
inputs=normal_controls,
|
| 542 |
+
outputs=normal_preview
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
hidden_controls = [
|
| 546 |
+
hidden_image, hidden_brightness, hidden_contrast, hidden_saturation, hidden_gamma,
|
| 547 |
+
hidden_line_art, hidden_line_method, hidden_canny_low, hidden_canny_high, hidden_blur_before
|
| 548 |
+
]
|
| 549 |
+
for control in hidden_controls:
|
| 550 |
+
control.change(
|
| 551 |
+
fn=preview_hidden_adjustment,
|
| 552 |
+
inputs=hidden_controls,
|
| 553 |
+
outputs=hidden_preview
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
generate_btn.click(
|
| 557 |
+
fn=generate_twitter_hidden_image_advanced,
|
| 558 |
+
inputs=[
|
| 559 |
+
normal_image, hidden_image,
|
| 560 |
+
normal_brightness, normal_contrast, normal_saturation, normal_gamma,
|
| 561 |
+
normal_line_art, normal_line_method, normal_canny_low, normal_canny_high, normal_blur_before,
|
| 562 |
+
hidden_brightness, hidden_contrast, hidden_saturation, hidden_gamma,
|
| 563 |
+
hidden_line_art, hidden_line_method, hidden_canny_low, hidden_canny_high, hidden_blur_before,
|
| 564 |
+
output_size, mask_blur, mask_threshold, mask_soften
|
| 565 |
+
],
|
| 566 |
+
outputs=[result_image, light_preview, dark_preview, hidden_layer_preview, download_file]
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# ========================
|
| 570 |
+
# タブ2: 透過ツール
|
| 571 |
+
# ========================
|
| 572 |
+
with gr.TabItem("🎨 透過ツール"):
|
| 573 |
+
gr.Markdown("""
|
| 574 |
+
## 透過ツール(モバイル最適化版)
|
| 575 |
+
- **AI自動除去**: フレーム画像の背景を自動除去
|
| 576 |
+
- **複数色除去**: クリックで色を登録してまとめて除去
|
| 577 |
+
""")
|
| 578 |
+
|
| 579 |
+
with gr.Row():
|
| 580 |
+
with gr.Column(scale=1):
|
| 581 |
+
gr.Markdown("## 📤 入力設定")
|
| 582 |
+
input_image = gr.Image(label="画像をアップロード", type="pil", format="png", interactive=True)
|
| 583 |
+
|
| 584 |
+
method = gr.Radio(
|
| 585 |
+
choices=["AI自動除去 (GrabCut)", "複数色除去"],
|
| 586 |
+
value="AI自動除去 (GrabCut)",
|
| 587 |
+
label="透過方法"
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
with gr.Group() as ai_options:
|
| 591 |
+
gr.Markdown("### 🤖 AI処理設定")
|
| 592 |
+
mask_method = gr.Radio(
|
| 593 |
+
choices=["simple", "minimal"],
|
| 594 |
+
value="simple",
|
| 595 |
+
label="処理方法",
|
| 596 |
+
info="simple: 標準 / minimal: 最軽量"
|
| 597 |
+
)
|
| 598 |
+
iter_count = gr.Slider(1, 8, value=5, step=1, label="処理回数")
|
| 599 |
+
blur_kernel = gr.Slider(1, 7, value=3, step=2, label="ぼかし強度")
|
| 600 |
+
|
| 601 |
+
with gr.Group(visible=False) as color_options:
|
| 602 |
+
gr.Markdown("### 🎯 色登録")
|
| 603 |
+
click_x = gr.Number(label="X座標", value=0, visible=False)
|
| 604 |
+
click_y = gr.Number(label="Y座標", value=0, visible=False)
|
| 605 |
+
|
| 606 |
+
current_color = gr.ColorPicker(label="選択した色", value="#ffffff")
|
| 607 |
+
color_preview = gr.HTML(value="<div style='width:40px;height:20px;background-color:#ffffff;border:1px solid #ccc;display:inline-block;'></div>")
|
| 608 |
+
|
| 609 |
+
with gr.Row():
|
| 610 |
+
add_color_btn = gr.Button("➕ 追加", size="sm")
|
| 611 |
+
remove_select = gr.Dropdown(label="削除する色", choices=[], value=None, interactive=True)
|
| 612 |
+
remove_color_btn = gr.Button("🗑️ 削除", size="sm")
|
| 613 |
+
clear_palette_btn = gr.Button("🧼 全消去", size="sm")
|
| 614 |
+
|
| 615 |
+
gr.Markdown("### ⚙️ 除去設定")
|
| 616 |
+
tolerance = gr.Slider(minimum=0, maximum=200, value=60, step=1, label="許容範囲")
|
| 617 |
+
feather = gr.Slider(minimum=0, maximum=20, value=5, step=1, label="フェザー")
|
| 618 |
+
morph_iter = gr.Slider(minimum=0, maximum=3, value=0, step=1, label="ノイズ除去")
|
| 619 |
+
|
| 620 |
+
process_btn = gr.Button("🚀 透過処理を実行", variant="primary", size="lg")
|
| 621 |
+
|
| 622 |
+
with gr.Column(scale=1):
|
| 623 |
+
gr.Markdown("## 📤 色パレット")
|
| 624 |
+
palette_html = gr.HTML(value="<div style='color:#666;padding:10px;'>パレットは空です。</div>")
|
| 625 |
+
|
| 626 |
+
gr.Markdown("## 📤 処理結果")
|
| 627 |
+
output_image = gr.Image(label="透過結果", type="pil", format="png", show_download_button=True)
|
| 628 |
+
|
| 629 |
+
# 透過ツールのState
|
| 630 |
+
palette_state = gr.State([])
|
| 631 |
+
|
| 632 |
+
# 透過ツールのイベントハンドラ
|
| 633 |
+
def toggle_options(selected_method):
|
| 634 |
+
return (
|
| 635 |
+
gr.update(visible=(selected_method == "AI自動除去 (GrabCut)")),
|
| 636 |
+
gr.update(visible=(selected_method == "複数色除去"))
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
method.change(fn=toggle_options, inputs=[method], outputs=[ai_options, color_options])
|
| 640 |
+
|
| 641 |
+
def handle_image_click(image, evt: gr.SelectData):
|
| 642 |
+
try:
|
| 643 |
+
if evt is not None and getattr(evt, "index", None) is not None:
|
| 644 |
+
ix, iy = evt.index[0], evt.index[1]
|
| 645 |
+
color_hex = get_color_from_coordinate(image, ix, iy)
|
| 646 |
+
preview_html = f"<div style='width:40px;height:20px;background-color:{color_hex};border:1px solid #ccc;display:inline-block;'></div><span style='margin-left:8px;'>{color_hex}</span>"
|
| 647 |
+
return ix, iy, color_hex, preview_html
|
| 648 |
+
except Exception:
|
| 649 |
+
pass
|
| 650 |
+
return 0, 0, "#ffffff", "<div style='width:40px;height:20px;background-color:#ffffff;border:1px solid #ccc;display:inline-block;'></div>"
|
| 651 |
+
|
| 652 |
+
input_image.select(fn=handle_image_click, inputs=[input_image], outputs=[click_x, click_y, current_color, color_preview])
|
| 653 |
+
|
| 654 |
+
def add_color(current_color_hex, palette):
|
| 655 |
+
col = current_color_hex if isinstance(current_color_hex, str) else "#ffffff"
|
| 656 |
+
if not col.startswith('#'):
|
| 657 |
+
col = f"#{col}"
|
| 658 |
+
col = col.lower()
|
| 659 |
+
|
| 660 |
+
palette = list(palette) if palette is not None else []
|
| 661 |
+
if col not in palette:
|
| 662 |
+
palette.append(col)
|
| 663 |
+
|
| 664 |
+
html = build_palette_html(palette)
|
| 665 |
+
choices = palette.copy()
|
| 666 |
+
return palette, html, gr.update(choices=choices, value=(choices[-1] if choices else None))
|
| 667 |
+
|
| 668 |
+
def remove_color(palette, selected_hex):
|
| 669 |
+
palette = list(palette) if palette is not None else []
|
| 670 |
+
if selected_hex in palette:
|
| 671 |
+
palette.remove(selected_hex)
|
| 672 |
+
html = build_palette_html(palette)
|
| 673 |
+
choices = palette.copy()
|
| 674 |
+
return palette, html, gr.update(choices=choices, value=(choices[-1] if choices else None))
|
| 675 |
+
|
| 676 |
+
def clear_palette():
|
| 677 |
+
palette = []
|
| 678 |
+
html = build_palette_html(palette)
|
| 679 |
+
return palette, html, gr.update(choices=[], value=None)
|
| 680 |
+
|
| 681 |
+
add_color_btn.click(fn=add_color, inputs=[current_color, palette_state],
|
| 682 |
+
outputs=[palette_state, palette_html, remove_select])
|
| 683 |
+
|
| 684 |
+
remove_color_btn.click(fn=remove_color, inputs=[palette_state, remove_select],
|
| 685 |
+
outputs=[palette_state, palette_html, remove_select])
|
| 686 |
+
|
| 687 |
+
clear_palette_btn.click(fn=clear_palette, inputs=None,
|
| 688 |
+
outputs=[palette_state, palette_html, remove_select])
|
| 689 |
+
|
| 690 |
+
process_btn.click(
|
| 691 |
+
fn=process_image_transparency,
|
| 692 |
+
inputs=[input_image, method, iter_count, blur_kernel, mask_method,
|
| 693 |
+
palette_state, tolerance, feather, morph_iter],
|
| 694 |
+
outputs=[output_image]
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
# 共通の使い方説明
|
| 698 |
+
gr.Markdown("""
|
| 699 |
+
## 📋 全体の使い方
|
| 700 |
+
|
| 701 |
+
### 🎭 Twitter隠し絵ジェネレーター
|
| 702 |
+
1. **通常画像**: 背景として表示される画像をアップロード
|
| 703 |
+
2. **隠し画像**: 隠したい画像をアップロード(写真でも線画でもOK)
|
| 704 |
+
3. **線画抽出**: チェックボックスをONにすると写真から線画を自動抽出
|
| 705 |
+
4. **調整スライダー**: 各画像の明度・コントラスト等を調整
|
| 706 |
+
5. **生成ボタンを押して、ダウンロードファイルから透過PNGを保存**
|
| 707 |
+
|
| 708 |
+
### 🎨 透過ツール
|
| 709 |
+
**AI自動除去の場合:**
|
| 710 |
+
- フレーム画像の背景を自動で検出・除去
|
| 711 |
+
|
| 712 |
+
**複数色除去の場合:**
|
| 713 |
+
1. 画像をクリックして色を取得
|
| 714 |
+
2. 「➕ 追加」でパレットに登録
|
| 715 |
+
3. 複数色を登録後「透過処理を実行」
|
| 716 |
+
|
| 717 |
+
## 💡 ポイント
|
| 718 |
+
- 両方のツールとも透過PNG形式で出力されます
|
| 719 |
+
- モバイル環境でも快適に動作するよう最適化済み
|
| 720 |
+
- エラーが発生した場合は設定を調整してお試しください
|
| 721 |
+
""")
|
| 722 |
+
|
| 723 |
+
return app
|
| 724 |
|
| 725 |
if __name__ == "__main__":
|
| 726 |
+
app = create_integrated_interface()
|
| 727 |
+
app.launch(server_name="0.0.0.0", server_port=7860, share=False)
|