File size: 16,062 Bytes
59e856b 6f047dd 7b32868 557c26f 9ba7b72 557c26f 9ba7b72 9592232 6f047dd 9ba7b72 59e856b 9ba7b72 e7ca482 9ba7b72 59e856b 9ba7b72 6f047dd 9ba7b72 6f047dd 9ba7b72 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 9592232 6f047dd 56e6f9a 6f047dd 56e6f9a 9592232 6f047dd 9592232 56e6f9a e7ca482 6f047dd e7ca482 d31171b b89e628 6f047dd 9ba7b72 6f047dd 45b6f92 6f047dd 9ba7b72 6f047dd 7b32868 6f047dd 7b32868 9ba7b72 6f047dd 59e856b 6f047dd e7ca482 6f047dd 59e856b 7b32868 6f047dd 7b32868 3092e25 7b32868 6f047dd 3092e25 7b32868 6f047dd 7b32868 6f047dd 7b32868 6f047dd e7ca482 6f047dd d8919cd 6f047dd d8919cd e7ca482 6f047dd 59e856b 6f047dd 59e856b 6f047dd 59e856b 6f047dd 7b32868 6f047dd 45b6f92 6f047dd e751ee6 7b32868 e751ee6 6f047dd e751ee6 6f047dd e751ee6 9ba7b72 e751ee6 9ba7b72 9592232 6f047dd 9ba7b72 6f047dd 9ba7b72 7b32868 6f047dd 7b32868 6f047dd 83db1cc 6f047dd 83db1cc 6f047dd 9ba7b72 6f047dd 6eb591a 6f047dd 9ba7b72 e751ee6 9ba7b72 6f047dd e751ee6 9ba7b72 6f047dd e751ee6 6f047dd 9592232 6f047dd 9ba7b72 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | import io
import cv2
import numpy as np
import streamlit as st
from PIL import Image
from scipy.ndimage import binary_fill_holes, distance_transform_edt, label
# ---------------------------------------------------------------------------
# App Configuration & Session State
# ---------------------------------------------------------------------------
st.set_page_config(
layout="wide",
page_title="TexAI Extractor Pro",
page_icon="✨",
initial_sidebar_state="expanded"
)
if "fringe_val" not in st.session_state:
st.session_state.fringe_val = 0
def step_fringe(delta: int):
st.session_state.fringe_val = max(0, min(5, st.session_state.fringe_val + delta))
# ---------------------------------------------------------------------------
# Modern App CSS Styling (Clean Light Theme)
# ---------------------------------------------------------------------------
st.markdown(
"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
html, body, [class*="css"] {
font-family: 'Inter', sans-serif;
}
/* Base App Theme - Clean Light */
.stApp {
background-color: #f8fafc;
}
/* Layout Spacing */
.block-container {
padding-top: 2rem !important;
max-width: 1400px;
}
header { visibility: hidden; }
footer { visibility: hidden; }
/* Header Typography */
.app-header {
margin-bottom: 2.5rem;
padding-bottom: 1.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
.app-title {
font-weight: 800;
font-size: 2.8rem;
letter-spacing: -0.03em;
margin-bottom: 0.25rem;
color: #0f172a;
}
.app-subtitle {
font-size: 1.05rem;
color: #64748b;
font-weight: 400;
}
/* Sidebar Styling */
[data-testid="stSidebar"] {
background-color: #ffffff;
border-right: 1px solid rgba(0, 0, 0, 0.05);
}
[data-testid="stSidebar"] * {
color: #334155 !important;
}
.sidebar-header {
font-weight: 700;
font-size: 0.85rem;
color: #94a3b8 !important;
text-transform: uppercase;
letter-spacing: 0.05em;
margin: 1.5rem 0 0.75rem 0;
}
/* Primary Buttons (Sleek Dark) */
.stButton > button {
background-color: #0f172a !important;
color: white !important;
border-radius: 8px !important;
border: none !important;
font-weight: 500 !important;
padding: 0.6rem 1.2rem !important;
transition: all 0.2s ease !important;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05) !important;
}
.stButton > button:hover {
background-color: #334155 !important;
transform: translateY(-1px);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1) !important;
}
/* Download Buttons (Vibrant Action) */
.stDownloadButton > button {
background-color: #2563eb !important;
color: white !important;
border-radius: 8px !important;
border: none !important;
font-weight: 600 !important;
padding: 0.8rem 1.2rem !important;
margin-top: 1rem;
transition: all 0.2s ease !important;
box-shadow: 0 4px 6px rgba(37, 99, 235, 0.2) !important;
}
.stDownloadButton > button:hover {
background-color: #1d4ed8 !important;
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(37, 99, 235, 0.3) !important;
}
/* Image Cards & Text */
.image-card-title {
font-weight: 600;
font-size: 0.85rem;
color: #64748b;
margin-bottom: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
p, span, label, div[data-baseweb="radio"] {
color: #334155;
}
/* Upload Dropzone */
[data-testid="stFileUploaderDropzone"] {
border-radius: 12px;
border: 2px dashed #cbd5e1;
background-color: #ffffff;
transition: all 0.3s ease;
}
[data-testid="stFileUploaderDropzone"]:hover {
border-color: #2563eb;
background-color: #f8fafc;
}
/* White/Light Gray Transparency Grid */
[data-testid="stImage"] {
background-color: #ffffff !important;
background-image:
linear-gradient(45deg, #f1f5f9 25%, transparent 25%),
linear-gradient(135deg, #f1f5f9 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #f1f5f9 75%),
linear-gradient(135deg, transparent 75%, #f1f5f9 75%) !important;
background-size: 16px 16px !important;
background-position: 0 0, 8px 0, 8px -8px, 0px 8px !important;
border-radius: 12px;
border: 1px solid #e2e8f0;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
overflow: hidden;
}
</style>
""", unsafe_allow_html=True
)
# ---------------------------------------------------------------------------
# Engine 1: Segformer (Strict Clothing Extraction)
# ---------------------------------------------------------------------------
@st.cache_resource(show_spinner=False, max_entries=1)
def load_segformer():
from transformers import AutoModelForSemanticSegmentation, SegformerImageProcessor
processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")
model = AutoModelForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes")
return processor, model
@st.cache_data(show_spinner=False, max_entries=2)
def segformer_cutout(image_bytes: bytes, grow_px: int) -> bytes:
import torch
import torch.nn as nn
processor, model = load_segformer()
source_img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
inputs = processor(images=source_img, return_tensors="pt")
with torch.no_grad(): outputs = model(**inputs)
logits = outputs.logits.cpu()
upsampled_logits = nn.functional.interpolate(logits, size=source_img.size[::-1], mode="bilinear", align_corners=False)
pred_seg = upsampled_logits.argmax(dim=1)[0].numpy()
clothing_labels = [4, 5, 6, 7]
garment_mask_arr = np.isin(pred_seg, clothing_labels).astype(np.uint8) * 255
if grow_px > 0:
kernel = np.ones((3, 3), np.uint8)
garment_mask_arr = cv2.erode(garment_mask_arr, kernel, iterations=grow_px)
garment_mask = Image.fromarray(garment_mask_arr, mode="L")
cutout = source_img.convert("RGBA")
cutout.putalpha(garment_mask)
buf = io.BytesIO()
cutout.save(buf, format="PNG")
return buf.getvalue()
# ---------------------------------------------------------------------------
# Engine 2: U2Net Cloth (Local Occusion Repair)
# ---------------------------------------------------------------------------
MAX_MASK_EDGE = 1024
@st.cache_resource(show_spinner=False)
def load_ai_session():
import onnxruntime as ort
from rembg.sessions import sessions_class
opts = ort.SessionOptions()
opts.enable_cpu_mem_arena = False
opts.intra_op_num_threads = 1
session_dict = {cls.name(): cls for cls in sessions_class}
return session_dict["u2net_cloth_seg"]("u2net_cloth_seg", opts)
def _mirror_fill(rgb: np.ndarray, garment: np.ndarray, occluded: np.ndarray):
out = rgb.copy()
remaining = occluded.copy()
pieces, count = label(garment | occluded)
for index in range(1, count + 1):
piece = pieces == index
target = piece & occluded
fabric = piece & garment & ~occluded
if target.sum() == 0 or fabric.sum() < 500: continue
xs = np.nonzero(fabric)[1]
axis = int(round((xs.min() + xs.max()) / 2))
ys, xs_t = np.nonzero(target)
mirrored = 2 * axis - xs_t
inside = (mirrored >= 0) & (mirrored < rgb.shape[1])
ys, xs_t, mirrored = ys[inside], xs_t[inside], mirrored[inside]
usable = fabric[ys, mirrored]
out[ys[usable], xs_t[usable]] = rgb[ys[usable], mirrored[usable]]
remaining[ys[usable], xs_t[usable]] = False
return out, remaining
@st.cache_data(show_spinner=False, max_entries=2)
def u2net_cloth_cutout(image_bytes: bytes, repair: bool, grow_px: int) -> bytes:
source = Image.open(io.BytesIO(image_bytes)).convert("RGB")
width, height = source.size
small = source.copy()
small.thumbnail((MAX_MASK_EDGE, MAX_MASK_EDGE), Image.LANCZOS)
parts = load_ai_session().predict(small)
upper, lower = (np.array(p.convert("L").resize((width, height), Image.LANCZOS)) > 127 for p in parts[:2])
garment = upper | lower
rgb = np.array(source)
if repair:
occluded = binary_fill_holes(garment) & ~garment
if occluded.any():
rgb, remaining = _mirror_fill(rgb, garment, occluded)
if remaining.any():
rgb = cv2.inpaint(rgb, cv2.dilate(remaining.astype(np.uint8) * 255, np.ones((3, 3), np.uint8), 1), 3, cv2.INPAINT_TELEA)
garment = garment | occluded
garment_mask = (garment * 255).astype(np.uint8)
if grow_px > 0:
garment_mask = cv2.erode(garment_mask, np.ones((3, 3), np.uint8), iterations=grow_px)
result = Image.fromarray(rgb).convert("RGBA")
result.putalpha(Image.fromarray(garment_mask))
buf = io.BytesIO()
result.save(buf, format="PNG")
return buf.getvalue()
# ---------------------------------------------------------------------------
# Engine 3: Chroma Key
# ---------------------------------------------------------------------------
def detect_background_hex(img_array: np.ndarray, border: int = 10) -> str:
h, w, _ = img_array.shape
border = min(border, h // 2, w // 2) or 1
samples = np.concatenate([
img_array[:border, :, :].reshape(-1, 3), img_array[-border:, :, :].reshape(-1, 3),
img_array[:, :border, :].reshape(-1, 3), img_array[:, -border:, :].reshape(-1, 3),
])
return "#{:02X}{:02X}{:02X}".format(*samples.mean(axis=0).astype(np.uint8))
def chroma_cutout(img_array: np.ndarray, key_hex: str, tola: int, tolb: int, grow_px: int) -> Image.Image:
hex_str = key_hex.lstrip('#')
target = np.array([int(hex_str[i:i+2], 16) for i in (0, 2, 4)], dtype=np.float32)
distances = np.linalg.norm(img_array.astype(np.float32) - target, axis=-1)
alpha_f = np.clip((distances - tola) / max(tolb - tola, 1), 0.0, 1.0)
final_rgb = img_array.copy()
if grow_px > 0:
core = cv2.erode((alpha_f > 0.5).astype(np.uint8), np.ones((3, 3), np.uint8), iterations=grow_px)
if core.any():
_, indices = distance_transform_edt(1 - core, return_indices=True)
final_rgb = np.where(core[..., None].astype(bool), final_rgb, final_rgb[indices[0], indices[1]])
return Image.fromarray(np.dstack([final_rgb, np.uint8(alpha_f * 255)]), "RGBA")
# ---------------------------------------------------------------------------
# App Interface
# ---------------------------------------------------------------------------
st.markdown('<div class="app-header"><div class="app-title">TexAI Extractor</div><div class="app-subtitle">High-Fidelity Garment Isolation Engine. Designed to instantly generate clean catalog assets.</div></div>', unsafe_allow_html=True)
uploaded_file = st.file_uploader("Upload product photo to begin", type=["png", "jpg", "jpeg"], label_visibility="collapsed")
if uploaded_file is None:
st.info("Upload a garment photo above to launch the extraction studio.")
st.stop()
image_bytes = uploaded_file.getvalue()
original_image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
img_array = np.array(original_image)
with st.sidebar:
st.markdown('<div class="sidebar-header">Extraction Engine</div>', unsafe_allow_html=True)
st.error("⚠️ **Garments Only.** This tool explicitly deletes human skin, hair, and body parts.")
method = st.radio("Processing Engine", ["Segformer (Pro Garment AI)", "U2Net (Local Occlusion Repair)", "Chroma Key (Studio Green)", "Hybrid (AI + Chroma Key)"], label_visibility="collapsed")
st.markdown("---")
if method == "U2Net (Local Occlusion Repair)":
st.info("Maps generic clothing shapes and attempts to mathematically rebuild fabric hidden behind arms.")
repair_occlusion = st.checkbox("Rebuild fabric behind arms", value=True)
elif method == "Chroma Key (Studio Green)":
st.warning("Math-based background subtraction for solid colors.")
detected_hex = detect_background_hex(img_array)
key_color_hex = st.color_picker("Key Color", detected_hex)
tola = st.slider("Shadow Tolerance", 1, 50, 10)
tolb = st.slider("Highlight Tolerance", tola + 1, 120, 60)
elif method == "Hybrid (AI + Chroma Key)":
st.info("⚡ **Combines AI with precise Chroma math.** Punches out enclosed background gaps and refines edges.")
repair_occlusion = st.checkbox("Rebuild fabric behind arms", value=False)
detected_hex = detect_background_hex(img_array)
key_color_hex = st.color_picker("Key Color", detected_hex)
tola = st.slider("Shadow Tolerance", 1, 50, 10)
tolb = st.slider("Highlight Tolerance", tola + 1, 120, 60)
with st.expander("Edge Cleanup", expanded=True):
col_min, col_slide, col_plus = st.columns([1, 4, 1])
with col_min: st.button("−", on_click=step_fringe, args=(-1,), width="stretch")
with col_slide: grow_px = st.slider("Fringe", 0, 5, key="fringe_val", label_visibility="collapsed")
with col_plus: st.button("+", on_click=step_fringe, args=(1,), width="stretch")
# ---------------------------------------------------------------------------
# Processing
# ---------------------------------------------------------------------------
col1, col2 = st.columns(2, gap="large")
with col1:
st.markdown('<div class="image-card-title">Source Image</div>', unsafe_allow_html=True)
st.image(original_image, width="stretch")
with col2:
st.markdown('<div class="image-card-title">Extraction Result</div>', unsafe_allow_html=True)
try:
with st.spinner("Extracting garments..."):
if method == "Segformer (Pro Garment AI)":
out_bytes = segformer_cutout(image_bytes, grow_px)
extracted_image = Image.open(io.BytesIO(out_bytes))
elif method == "U2Net (Local Occlusion Repair)":
out_bytes = u2net_cloth_cutout(image_bytes, repair_occlusion, grow_px)
extracted_image = Image.open(io.BytesIO(out_bytes))
elif method == "Chroma Key (Studio Green)":
extracted_image = chroma_cutout(img_array, key_color_hex, tola, tolb, grow_px)
elif method == "Hybrid (AI + Chroma Key)":
ai_bytes = u2net_cloth_cutout(image_bytes, repair_occlusion, grow_px)
ai_alpha = np.array(Image.open(io.BytesIO(ai_bytes)).split()[-1])
chroma_img = chroma_cutout(img_array, key_color_hex, tola, tolb, grow_px)
chroma_alpha = np.array(chroma_img.split()[-1])
combined_alpha = np.minimum(ai_alpha, chroma_alpha)
if grow_px > 0:
combined_alpha = cv2.erode(combined_alpha, np.ones((3, 3), np.uint8), iterations=grow_px)
extracted_image = chroma_img.copy()
extracted_image.putalpha(Image.fromarray(combined_alpha))
st.image(extracted_image, width="stretch")
buf = io.BytesIO()
extracted_image.save(buf, format="PNG")
st.download_button("↓ Export Transparent Garment", data=buf.getvalue(), file_name="garment_asset.png", mime="image/png", width="stretch")
except Exception as exc:
st.error(f"Processing Error: {exc}")
|