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(""" """, 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('