ClothSeg / app.py
ahmedsharaf's picture
Deploy ClothSeg Streamlit App
b157024
Raw History Blame Contribute Delete
11.5 kB
import os
from pathlib import Path
import cv2
import numpy as np
import torch
from PIL import Image
import streamlit as st
import albumentations as A
from albumentations.pytorch import ToTensorV2
from src.config import load_config
from src.model import build_model
from src.operations import (
to_binary_clothes,
morphological_operations,
create_overlay,
)
from src.visualize import colorize_mask, CLASS_NAMES, CLASS_COLORS
# Set page configuration
st.set_page_config(
page_title="ClothSeg - Clothing Semantic Segmentation",
page_icon="🧥",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom Styling
st.markdown("""
<style>
.main-title {
font-size: 2.2rem;
font-weight: 700;
color: #1E293B;
margin-bottom: 0.2rem;
}
.sub-title {
font-size: 1.05rem;
color: #64748B;
margin-bottom: 1.5rem;
}
.class-badge {
display: inline-block;
padding: 4px 10px;
border-radius: 6px;
font-size: 0.85rem;
font-weight: 600;
margin-right: 6px;
margin-bottom: 6px;
color: white;
}
.metric-card {
background-color: #F8FAFC;
border-radius: 8px;
padding: 12px;
border: 1px solid #E2E8F0;
text-align: center;
}
</style>
""", unsafe_allow_html=True)
@st.cache_resource(show_spinner=False)
def get_model_and_config(device_name: str = "cpu"):
"""Load configuration and initialize model with cached weights on the chosen device."""
config = load_config()
device = torch.device(device_name)
model = build_model(config)
model = model.to(device)
checkpoint_path = config["paths"]["best_model"]
if not os.path.exists(checkpoint_path):
# Fallback to local root search
alt_path = Path("checkpoints") / "best_model.pth"
if alt_path.exists():
checkpoint_path = str(alt_path)
else:
raise FileNotFoundError(
f"Model checkpoint not found at '{checkpoint_path}'. "
"Please make sure 'checkpoints/best_model.pth' is present."
)
checkpoint = torch.load(checkpoint_path, map_location=device)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
return model, config, device, checkpoint.get("epoch", "N/A"), checkpoint.get("best_miou", "N/A")
def preprocess_image(image_np, image_size=512):
"""Letterbox resize with constant padding and ImageNet normalization."""
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
geometric_transform = A.Compose([
A.LongestMaxSize(max_size=image_size, interpolation=cv2.INTER_LINEAR),
A.PadIfNeeded(
min_height=image_size,
min_width=image_size,
border_mode=cv2.BORDER_CONSTANT,
fill=0
)
])
processed = geometric_transform(image=image_np)
display_image = processed["image"]
normalized = A.Normalize(mean=mean, std=std)(image=display_image)["image"]
tensor = ToTensorV2()(image=normalized)["image"]
return tensor.unsqueeze(0), display_image
def run_prediction(model, input_tensor, device):
"""Run model inference and produce raw multi-class prediction mask."""
input_tensor = input_tensor.to(device)
with torch.no_grad():
if device.type == "cuda":
with torch.autocast(device_type="cuda"):
outputs = model(input_tensor)
else:
outputs = model(input_tensor)
prediction = torch.argmax(outputs, dim=1)
return prediction.squeeze(0).cpu().numpy().astype(np.uint8)
def custom_overlay(image, mask, color_hex="#00FF00", alpha=0.5):
"""Create customizable color overlay on clothing mask."""
overlay = image.copy()
clothes = mask == 1
# Convert hex color to RGB tuple
color_hex = color_hex.lstrip('#')
rgb_color = np.array([int(color_hex[i:i+2], 16) for i in (0, 2, 4)], dtype=np.uint8)
overlay[clothes] = (overlay[clothes] * (1 - alpha) + rgb_color * alpha).astype(np.uint8)
return overlay
def main():
# Sidebar
st.sidebar.title("⚙️ Model Settings")
# Device Selection
cuda_available = torch.cuda.is_available()
device_options = ["cuda", "cpu"] if cuda_available else ["cpu"]
device_labels = {
"cuda": f"CUDA (GPU: {torch.cuda.get_device_name(0)})" if cuda_available else "CUDA",
"cpu": "CPU (Standard)"
}
selected_device_key = st.sidebar.selectbox(
"🖥️ Select Compute Device",
options=device_options,
format_func=lambda x: device_labels.get(x, x),
index=0 if cuda_available else 0,
help="Choose 'cuda' for high-speed GPU acceleration, or 'cpu' for standard CPU inference."
)
try:
model, config, device, epoch, best_miou = get_model_and_config(selected_device_key)
st.sidebar.success(f"Running on **{device.type.upper()}**")
st.sidebar.caption(f"Architecture: **U-Net (ResNet-34)** | Checkpoint: **Epoch {epoch}** (Val mIoU: {best_miou:.4f})")
except Exception as e:
st.sidebar.error(f"Error loading model: {e}")
st.error(f"Failed to load model checkpoint: {e}")
return
st.sidebar.markdown("---")
st.sidebar.subheader("🎨 Post-Processing Controls")
alpha = st.sidebar.slider("Overlay Transparency (Alpha)", min_value=0.1, max_value=1.0, value=0.5, step=0.05)
overlay_color = st.sidebar.color_picker("Overlay Highlight Color", value="#00FF00")
with st.sidebar.expander("Advanced Morphology"):
opening_k = st.slider("Opening Kernel (Noise Removal)", min_value=1, max_value=9, value=3, step=2)
closing_k = st.slider("Closing Kernel (Hole Filling)", min_value=1, max_value=25, value=11, step=2)
# Sample images selector
st.sidebar.markdown("---")
st.sidebar.subheader("🖼️ Or Select a Sample")
sample_dir = Path("assets")
sample_files = [f for f in ["1.jpg", "2.jpg", "4.jpg", "7.jpg", "8.jpg", "9.jpg"] if (sample_dir / f).exists()]
selected_sample = st.sidebar.selectbox("Choose sample image:", ["None"] + sample_files)
# Header
st.markdown('<div class="main-title">🧥 ClothSeg: Clothing Semantic Segmentation</div>', unsafe_allow_html=True)
st.markdown('<div class="sub-title">Segment and isolate garments from personal imagery in real-time using Deep U-Net with ResNet-34.</div>', unsafe_allow_html=True)
# Upload section
uploaded_file = st.file_uploader(
"Upload a person photo (JPG, PNG, WEBP):",
type=["jpg", "jpeg", "png", "webp"],
help="Upload a full-body or half-body portrait."
)
image_to_process = None
if uploaded_file is not None:
pil_image = Image.open(uploaded_file).convert("RGB")
image_to_process = np.array(pil_image)
elif selected_sample != "None":
sample_path = sample_dir / selected_sample
pil_image = Image.open(sample_path).convert("RGB")
image_to_process = np.array(pil_image)
st.info(f"Loaded sample image: **{selected_sample}**")
if image_to_process is not None:
with st.spinner("Processing image and predicting clothing segmentation..."):
# 1. Preprocess
tensor, display_image = preprocess_image(image_to_process, image_size=config["data"]["image_size"])
# 2. Predict
raw_prediction = run_prediction(model, tensor, device)
# 3. Postprocess
binary_mask = to_binary_clothes(raw_prediction)
final_mask = morphological_operations(
binary_mask,
opening_kernel=opening_k,
closing_kernel=closing_k,
opening_iterations=1,
closing_iterations=1
)
# 4. Colorize raw prediction
colored_raw = colorize_mask(raw_prediction)
# 5. Create overlay
overlay = custom_overlay(display_image, final_mask, color_hex=overlay_color, alpha=alpha)
# Class Legend Badges
st.markdown("### 🏷️ Multi-Class Legend")
badge_html = ""
for name, color in zip(CLASS_NAMES, CLASS_COLORS):
text_color = "#FFFFFF" if color != "#FFFF00" else "#000000"
badge_html += f'<span class="class-badge" style="background-color: {color}; color: {text_color}; border: 1px solid #CBD5E1;">{name}</span>'
st.markdown(badge_html, unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Four Columns Display
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown("#### 1. Input Image")
st.image(display_image, use_container_width=True, caption=f"Padded ({display_image.shape[1]}x{display_image.shape[0]})")
with col2:
st.markdown("#### 2. Raw Prediction")
st.image(colored_raw, use_container_width=True, caption="Multi-Class Semantic Mask")
with col3:
st.markdown("#### 3. Final Mask")
st.image(final_mask * 255, use_container_width=True, caption="Cleaned Binary Mask")
with col4:
st.markdown("#### 4. Overlay")
st.image(overlay, use_container_width=True, caption=f"Highlight ({overlay_color}, α={alpha})")
# Garment detection analysis
st.markdown("---")
st.subheader("📊 Detected Garment Coverage")
total_pixels = raw_prediction.size
coverage_cols = st.columns(len(CLASS_NAMES) - 1)
for i, (name, color) in enumerate(zip(CLASS_NAMES[1:], CLASS_COLORS[1:])):
class_id = i + 1
class_pixels = np.sum(raw_prediction == class_id)
percentage = (class_pixels / total_pixels) * 100
with coverage_cols[i]:
detected = percentage > 0.1
status_emoji = "✅" if detected else "⚪"
st.metric(
label=f"{status_emoji} {name}",
value=f"{percentage:.2f}%",
delta="Present" if detected else "Not detected"
)
# Download options
st.markdown("---")
st.subheader("💾 Download Results")
dcol1, dcol2, dcol3 = st.columns(3)
with dcol1:
raw_pil = Image.fromarray(colored_raw)
raw_bytes = cv2.imencode('.png', cv2.cvtColor(colored_raw, cv2.COLOR_RGB2BGR))[1].tobytes()
st.download_button(
label="📥 Download Raw Prediction (PNG)",
data=raw_bytes,
file_name="clothseg_raw_prediction.png",
mime="image/png"
)
with dcol2:
binary_bytes = cv2.imencode('.png', (final_mask * 255).astype(np.uint8))[1].tobytes()
st.download_button(
label="📥 Download Final Mask (PNG)",
data=binary_bytes,
file_name="clothseg_final_mask.png",
mime="image/png"
)
with dcol3:
overlay_bytes = cv2.imencode('.png', cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))[1].tobytes()
st.download_button(
label="📥 Download Overlay (PNG)",
data=overlay_bytes,
file_name="clothseg_overlay.png",
mime="image/png"
)
else:
st.info("👆 Please upload an image or select a sample from the sidebar to test clothing segmentation.")
if __name__ == "__main__":
main()