Spaces:
Runtime error
Runtime error
Commit ·
2f6b8cf
1
Parent(s): d93c9fb
Deploy professional garment segmentation app with custom UI
Browse files- .gitattributes +7 -34
- README.md +113 -6
- SETUP_INSTRUCTIONS.md +173 -0
- app.py +304 -0
- examples/fashion1.jpg +3 -0
- examples/fashion2.jpg +3 -0
- examples/fashion3.jpg +3 -0
- requirements.txt +10 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,8 @@
|
|
| 1 |
-
*.
|
| 2 |
-
*.
|
| 3 |
-
*.
|
| 4 |
-
*.
|
| 5 |
-
*.
|
| 6 |
-
*.
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,14 +1,121 @@
|
|
| 1 |
---
|
| 2 |
title: Garment Segmentation
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Garment Segmentation
|
| 3 |
+
emoji: 👗
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.0.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
+
tags:
|
| 12 |
+
- computer-vision
|
| 13 |
+
- image-segmentation
|
| 14 |
+
- fashion
|
| 15 |
+
- virtual-try-on
|
| 16 |
+
- deepfashion2
|
| 17 |
+
- pytorch
|
| 18 |
---
|
| 19 |
|
| 20 |
+
# 👗 Garment Segmentation
|
| 21 |
+
|
| 22 |
+
An AI-powered application for **precise garment extraction** from fashion images, built with a custom U-Net model trained on the DeepFashion2 dataset.
|
| 23 |
+
|
| 24 |
+
## 🎯 What Does This Do?
|
| 25 |
+
|
| 26 |
+
This application automatically segments and extracts clothing items (especially upper-body garments) from images. It's perfect for:
|
| 27 |
+
|
| 28 |
+
- 🛍️ **E-commerce**: Isolate product images from backgrounds
|
| 29 |
+
- 👔 **Virtual Try-On**: Extract garments for AR/VR applications
|
| 30 |
+
- 🎨 **Fashion Design**: Quick garment isolation for mood boards
|
| 31 |
+
- 📊 **Dataset Preprocessing**: Prepare fashion datasets for ML tasks
|
| 32 |
+
- ✂️ **Background Removal**: Clean product photos automatically
|
| 33 |
+
|
| 34 |
+
## 🚀 Features
|
| 35 |
+
|
| 36 |
+
- **High Accuracy**: 89.64% validation IoU on DeepFashion2
|
| 37 |
+
- **Fast Inference**: Real-time segmentation with GPU support
|
| 38 |
+
- **Multiple Outputs**: Overlay, extracted garment, and binary mask
|
| 39 |
+
- **Adjustable Threshold**: Fine-tune segmentation sensitivity
|
| 40 |
+
- **Easy to Use**: Drag-and-drop interface powered by Gradio
|
| 41 |
+
|
| 42 |
+
## 🔧 How It Works
|
| 43 |
+
|
| 44 |
+
1. **Upload** a fashion image (preferably with visible upper-body clothing)
|
| 45 |
+
2. **Adjust** the confidence threshold if needed (default: 0.5)
|
| 46 |
+
3. **Get** three outputs:
|
| 47 |
+
- 🎨 **Overlay**: Original image with highlighted garment area
|
| 48 |
+
- ✂️ **Extracted**: Isolated garment on black background
|
| 49 |
+
- 🎭 **Mask**: Binary segmentation mask
|
| 50 |
+
|
| 51 |
+
## 🧠 Model Details
|
| 52 |
+
|
| 53 |
+
- **Architecture**: U-Net with ResNet50 encoder
|
| 54 |
+
- **Custom Decoder**: (256, 128, 64, 32, 16) channels
|
| 55 |
+
- **Input Size**: 768 × 768 pixels
|
| 56 |
+
- **Training Dataset**: DeepFashion2
|
| 57 |
+
- **Framework**: PyTorch Lightning + segmentation_models_pytorch
|
| 58 |
+
- **Performance**: 89.64% validation IoU @ epoch 45
|
| 59 |
+
|
| 60 |
+
### Model Repository
|
| 61 |
+
🤗 [zyuzuguldu/garment-segmentation-unet-resnet50](https://huggingface.co/zyuzuguldu/garment-segmentation-unet-resnet50)
|
| 62 |
+
|
| 63 |
+
## 📊 Performance
|
| 64 |
+
|
| 65 |
+
| Metric | Value |
|
| 66 |
+
|--------|-------|
|
| 67 |
+
| Validation IoU | **89.64%** |
|
| 68 |
+
| Inference Time (GPU) | ~50-100ms |
|
| 69 |
+
| Input Resolution | 768×768 |
|
| 70 |
+
|
| 71 |
+
## 💡 Tips for Best Results
|
| 72 |
+
|
| 73 |
+
- Use clear, well-lit photos with visible garments
|
| 74 |
+
- Works best with **upper-body clothing** (shirts, dresses, jackets, etc.)
|
| 75 |
+
- For tight/loose masks, adjust the confidence threshold:
|
| 76 |
+
- **Lower threshold** (0.3-0.4): More inclusive, captures more area
|
| 77 |
+
- **Higher threshold** (0.6-0.7): More conservative, tighter mask
|
| 78 |
+
- Front-facing or slightly angled photos work best
|
| 79 |
+
|
| 80 |
+
## 🛠️ Technical Stack
|
| 81 |
+
|
| 82 |
+
- **Framework**: [Gradio](https://gradio.app) 4.0
|
| 83 |
+
- **Deep Learning**: PyTorch 2.0+
|
| 84 |
+
- **Segmentation Library**: [segmentation_models_pytorch](https://github.com/qubvel/segmentation_models.pytorch)
|
| 85 |
+
- **Model Format**: SafeTensors for efficient loading
|
| 86 |
+
- **Deployment**: Hugging Face Spaces
|
| 87 |
+
|
| 88 |
+
## 📝 Use Cases
|
| 89 |
+
|
| 90 |
+
### 1. E-commerce Product Editing
|
| 91 |
+
Remove backgrounds from product photos automatically for cleaner catalog images.
|
| 92 |
+
|
| 93 |
+
### 2. Virtual Try-On Applications
|
| 94 |
+
Extract garment masks for AR/VR try-on experiences.
|
| 95 |
+
|
| 96 |
+
### 3. Fashion Dataset Curation
|
| 97 |
+
Preprocess and clean fashion datasets for machine learning projects.
|
| 98 |
+
|
| 99 |
+
### 4. Creative Design Tools
|
| 100 |
+
Quickly isolate clothing items for fashion mood boards and design workflows.
|
| 101 |
+
|
| 102 |
+
## 🔗 Links
|
| 103 |
+
|
| 104 |
+
- 📦 **Model Repository**: [HuggingFace Model Hub](https://huggingface.co/zyuzuguldu/garment-segmentation-unet-resnet50)
|
| 105 |
+
- 🐙 **GitHub**: [zyuzuguldu](https://github.com/zyuzuguldu)
|
| 106 |
+
- 🎓 **Training Dataset**: [DeepFashion2](https://github.com/switchablenorms/DeepFashion2)
|
| 107 |
+
|
| 108 |
+
## 📄 License
|
| 109 |
+
|
| 110 |
+
This project is licensed under the **Apache 2.0 License** - see the LICENSE file for details.
|
| 111 |
+
|
| 112 |
+
## 🙏 Acknowledgments
|
| 113 |
+
|
| 114 |
+
- DeepFashion2 dataset creators
|
| 115 |
+
- segmentation_models_pytorch library
|
| 116 |
+
- Hugging Face for hosting infrastructure
|
| 117 |
+
- Gradio for the amazing UI framework
|
| 118 |
+
|
| 119 |
+
---
|
| 120 |
+
|
| 121 |
+
**Made with ❤️ for the fashion-tech community**
|
SETUP_INSTRUCTIONS.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚀 Setup Instructions for Hugging Face Space
|
| 2 |
+
|
| 3 |
+
Follow these steps to deploy your Garment Segmentation app to Hugging Face Spaces.
|
| 4 |
+
|
| 5 |
+
## 📋 Prerequisites
|
| 6 |
+
|
| 7 |
+
1. Hugging Face account
|
| 8 |
+
2. Git installed locally
|
| 9 |
+
3. Git LFS installed (for large files)
|
| 10 |
+
4. Your model uploaded to HuggingFace Hub
|
| 11 |
+
|
| 12 |
+
## 🔧 Step-by-Step Deployment
|
| 13 |
+
|
| 14 |
+
### 1. Clone Your Space Repository
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
cd /home/sylar/PycharmProjects/Virtual-Try-On
|
| 18 |
+
git clone https://huggingface.co/spaces/zyuzuguldu/garment-segmentation
|
| 19 |
+
cd garment-segmentation
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
### 2. Copy Application Files
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
# Copy all files from gradio_app directory
|
| 26 |
+
cp ../gradio_app/app.py .
|
| 27 |
+
cp ../gradio_app/requirements.txt .
|
| 28 |
+
cp ../gradio_app/README.md .
|
| 29 |
+
cp ../gradio_app/.gitattributes .
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
### 3. Add Example Images (Optional but Recommended)
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
# Create examples directory
|
| 36 |
+
mkdir -p examples
|
| 37 |
+
|
| 38 |
+
# Copy 3-5 good example images from your dataset or test set
|
| 39 |
+
# Recommended: clear photos with visible garments, different angles/styles
|
| 40 |
+
cp /path/to/your/example1.jpg examples/fashion1.jpg
|
| 41 |
+
cp /path/to/your/example2.jpg examples/fashion2.jpg
|
| 42 |
+
cp /path/to/your/example3.jpg examples/fashion3.jpg
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
**Tips for example images:**
|
| 46 |
+
- Choose diverse garment types (shirts, dresses, jackets)
|
| 47 |
+
- Include different colors and patterns
|
| 48 |
+
- Use high-quality, well-lit photos
|
| 49 |
+
- Size: Keep under 2MB each for fast loading
|
| 50 |
+
|
| 51 |
+
### 4. Initialize Git LFS (for image files)
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
git lfs install
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
### 5. Add and Commit Files
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
# Add all files
|
| 61 |
+
git add .
|
| 62 |
+
|
| 63 |
+
# Commit with descriptive message
|
| 64 |
+
git commit -m "Initial deployment: Garment segmentation Gradio app"
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
### 6. Push to Hugging Face
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
# Push to the space
|
| 71 |
+
git push
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
### 7. Wait for Build
|
| 75 |
+
|
| 76 |
+
- Go to https://huggingface.co/spaces/zyuzuguldu/garment-segmentation
|
| 77 |
+
- The Space will automatically build and deploy (takes 2-5 minutes)
|
| 78 |
+
- Watch the build logs for any errors
|
| 79 |
+
|
| 80 |
+
## 🎨 Customization Options
|
| 81 |
+
|
| 82 |
+
### Update Model Repository
|
| 83 |
+
Edit `app.py` line 14:
|
| 84 |
+
```python
|
| 85 |
+
MODEL_REPO_ID = "your-username/your-model-name"
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
### Change Theme
|
| 89 |
+
Edit `app.py` line 192:
|
| 90 |
+
```python
|
| 91 |
+
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()): # Try: Monochrome, Glass, etc.
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
### Adjust Input Size
|
| 95 |
+
Edit `app.py` line 13:
|
| 96 |
+
```python
|
| 97 |
+
INPUT_SIZE = 768 # Change to 512, 1024, etc.
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
### Modify CSS Styling
|
| 101 |
+
Edit the `custom_css` variable in `app.py` (lines 95-130) to customize colors, fonts, and layout.
|
| 102 |
+
|
| 103 |
+
## 🐛 Troubleshooting
|
| 104 |
+
|
| 105 |
+
### Build Fails
|
| 106 |
+
- Check `requirements.txt` for correct package versions
|
| 107 |
+
- Ensure your model repository exists and is public
|
| 108 |
+
- Check Space build logs for specific errors
|
| 109 |
+
|
| 110 |
+
### Out of Memory
|
| 111 |
+
- Reduce `INPUT_SIZE` to 512 or 384
|
| 112 |
+
- Request a Space upgrade (Settings → Hardware)
|
| 113 |
+
|
| 114 |
+
### Examples Not Working
|
| 115 |
+
- Ensure example images are in `examples/` folder
|
| 116 |
+
- Update paths in `app.py` line 243 to match your image names
|
| 117 |
+
- Set `cache_examples=False` if images are large
|
| 118 |
+
|
| 119 |
+
### Slow Loading
|
| 120 |
+
- Optimize example images (compress to <500KB)
|
| 121 |
+
- Consider using GPU hardware (Settings → Hardware → T4 small)
|
| 122 |
+
|
| 123 |
+
## 📦 Alternative: Quick Deploy Script
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
#!/bin/bash
|
| 127 |
+
# quick_deploy.sh
|
| 128 |
+
|
| 129 |
+
cd /home/sylar/PycharmProjects/Virtual-Try-On
|
| 130 |
+
|
| 131 |
+
# Clone space
|
| 132 |
+
git clone https://huggingface.co/spaces/zyuzuguldu/garment-segmentation
|
| 133 |
+
cd garment-segmentation
|
| 134 |
+
|
| 135 |
+
# Copy files
|
| 136 |
+
cp ../gradio_app/{app.py,requirements.txt,README.md,.gitattributes} .
|
| 137 |
+
|
| 138 |
+
# Create examples directory
|
| 139 |
+
mkdir -p examples
|
| 140 |
+
|
| 141 |
+
# TODO: Add your example images here
|
| 142 |
+
# cp /path/to/example1.jpg examples/fashion1.jpg
|
| 143 |
+
# cp /path/to/example2.jpg examples/fashion2.jpg
|
| 144 |
+
# cp /path/to/example3.jpg examples/fashion3.jpg
|
| 145 |
+
|
| 146 |
+
# Git setup
|
| 147 |
+
git lfs install
|
| 148 |
+
git add .
|
| 149 |
+
git commit -m "Deploy garment segmentation app"
|
| 150 |
+
git push
|
| 151 |
+
|
| 152 |
+
echo "✅ Deployment complete! Check your Space in 2-5 minutes."
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
Save this as `quick_deploy.sh`, make it executable with `chmod +x quick_deploy.sh`, and run it.
|
| 156 |
+
|
| 157 |
+
## 🎉 Post-Deployment
|
| 158 |
+
|
| 159 |
+
1. **Test Your App**: Try uploading different images
|
| 160 |
+
2. **Share Your Space**: Get the public URL from the Space page
|
| 161 |
+
3. **Monitor Usage**: Check Space analytics and logs
|
| 162 |
+
4. **Iterate**: Update files and push again to redeploy
|
| 163 |
+
|
| 164 |
+
## 🔗 Useful Links
|
| 165 |
+
|
| 166 |
+
- [Gradio Docs](https://www.gradio.app/docs)
|
| 167 |
+
- [HF Spaces Docs](https://huggingface.co/docs/hub/spaces)
|
| 168 |
+
- [Your Space](https://huggingface.co/spaces/zyuzuguldu/garment-segmentation)
|
| 169 |
+
- [Your Model](https://huggingface.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6 |
+
from safetensors.torch import load_file
|
| 7 |
+
from huggingface_hub import hf_hub_download
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
|
| 11 |
+
# Configuration
|
| 12 |
+
MODEL_REPO_ID = "zyuzuguldu/garment-segmentation-unet-resnet50"
|
| 13 |
+
INPUT_SIZE = 768
|
| 14 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 15 |
+
|
| 16 |
+
# Cache the model globally
|
| 17 |
+
model = None
|
| 18 |
+
|
| 19 |
+
def load_model():
|
| 20 |
+
"""Load the segmentation model from HuggingFace Hub."""
|
| 21 |
+
global model
|
| 22 |
+
if model is None:
|
| 23 |
+
print("📥 Downloading model from HuggingFace Hub...")
|
| 24 |
+
model_path = hf_hub_download(
|
| 25 |
+
repo_id=MODEL_REPO_ID,
|
| 26 |
+
filename="model.safetensors"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
print("🔨 Building model architecture...")
|
| 30 |
+
model = smp.Unet(
|
| 31 |
+
encoder_name="resnet50",
|
| 32 |
+
classes=1,
|
| 33 |
+
activation=None,
|
| 34 |
+
decoder_channels=(256, 128, 64, 32, 16)
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
print("⚡ Loading weights...")
|
| 38 |
+
state_dict = load_file(model_path)
|
| 39 |
+
model.load_state_dict(state_dict)
|
| 40 |
+
model.to(DEVICE)
|
| 41 |
+
model.eval()
|
| 42 |
+
print("✅ Model loaded successfully!")
|
| 43 |
+
|
| 44 |
+
return model
|
| 45 |
+
|
| 46 |
+
def preprocess_image(image):
|
| 47 |
+
"""Preprocess image for model inference."""
|
| 48 |
+
# Convert PIL to numpy
|
| 49 |
+
if isinstance(image, Image.Image):
|
| 50 |
+
image = np.array(image)
|
| 51 |
+
|
| 52 |
+
# Ensure RGB
|
| 53 |
+
if len(image.shape) == 2:
|
| 54 |
+
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
|
| 55 |
+
elif image.shape[2] == 4:
|
| 56 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
|
| 57 |
+
|
| 58 |
+
# Store original size
|
| 59 |
+
original_size = image.shape[:2]
|
| 60 |
+
|
| 61 |
+
# Resize to model input size
|
| 62 |
+
image_resized = cv2.resize(image, (INPUT_SIZE, INPUT_SIZE))
|
| 63 |
+
|
| 64 |
+
# Normalize (ImageNet stats)
|
| 65 |
+
mean = np.array([0.485, 0.456, 0.406])
|
| 66 |
+
std = np.array([0.229, 0.224, 0.225])
|
| 67 |
+
image_normalized = (image_resized / 255.0 - mean) / std
|
| 68 |
+
|
| 69 |
+
# Convert to tensor: (H, W, C) -> (1, C, H, W)
|
| 70 |
+
image_tensor = torch.from_numpy(image_normalized).float().permute(2, 0, 1).unsqueeze(0)
|
| 71 |
+
|
| 72 |
+
return image_tensor, original_size, image
|
| 73 |
+
|
| 74 |
+
def postprocess_mask(mask_logits, original_size, threshold=0.5):
|
| 75 |
+
"""Postprocess model output to binary mask."""
|
| 76 |
+
# Apply sigmoid and threshold
|
| 77 |
+
mask_prob = torch.sigmoid(mask_logits).squeeze().cpu().numpy()
|
| 78 |
+
mask_binary = (mask_prob > threshold).astype(np.uint8)
|
| 79 |
+
|
| 80 |
+
# Resize back to original size
|
| 81 |
+
mask_resized = cv2.resize(mask_binary, (original_size[1], original_size[0]),
|
| 82 |
+
interpolation=cv2.INTER_NEAREST)
|
| 83 |
+
|
| 84 |
+
return mask_resized, mask_prob
|
| 85 |
+
|
| 86 |
+
def create_overlay(image, mask, alpha=0.6):
|
| 87 |
+
"""Create an overlay visualization of mask on image."""
|
| 88 |
+
# Create colored mask (cyan/turquoise color)
|
| 89 |
+
colored_mask = np.zeros_like(image)
|
| 90 |
+
colored_mask[:, :, 0] = mask * 0 # Red channel
|
| 91 |
+
colored_mask[:, :, 1] = mask * 255 # Green channel
|
| 92 |
+
colored_mask[:, :, 2] = mask * 255 # Blue channel
|
| 93 |
+
|
| 94 |
+
# Blend with original image
|
| 95 |
+
overlay = cv2.addWeighted(image, 1, colored_mask, alpha, 0)
|
| 96 |
+
|
| 97 |
+
return overlay
|
| 98 |
+
|
| 99 |
+
def extract_garment(image, mask):
|
| 100 |
+
"""Extract garment using the mask (black background)."""
|
| 101 |
+
# Ensure mask is 3-channel
|
| 102 |
+
mask_3ch = np.stack([mask] * 3, axis=-1)
|
| 103 |
+
|
| 104 |
+
# Apply mask to image
|
| 105 |
+
extracted = image * mask_3ch
|
| 106 |
+
|
| 107 |
+
return extracted
|
| 108 |
+
|
| 109 |
+
def segment_garment(image, threshold=0.5, show_overlay=True):
|
| 110 |
+
"""Main segmentation function."""
|
| 111 |
+
# Load model
|
| 112 |
+
model = load_model()
|
| 113 |
+
|
| 114 |
+
# Preprocess
|
| 115 |
+
image_tensor, original_size, original_image = preprocess_image(image)
|
| 116 |
+
image_tensor = image_tensor.to(DEVICE)
|
| 117 |
+
|
| 118 |
+
# Inference
|
| 119 |
+
with torch.no_grad():
|
| 120 |
+
mask_logits = model(image_tensor)
|
| 121 |
+
|
| 122 |
+
# Postprocess
|
| 123 |
+
mask_binary, mask_prob = postprocess_mask(mask_logits, original_size, threshold)
|
| 124 |
+
|
| 125 |
+
# Resize probability map for visualization
|
| 126 |
+
mask_prob_resized = cv2.resize(mask_prob, (original_size[1], original_size[0]))
|
| 127 |
+
|
| 128 |
+
# Create visualizations
|
| 129 |
+
if show_overlay:
|
| 130 |
+
overlay = create_overlay(original_image, mask_binary)
|
| 131 |
+
extracted = extract_garment(original_image, mask_binary)
|
| 132 |
+
return overlay, extracted, (mask_binary * 255).astype(np.uint8)
|
| 133 |
+
else:
|
| 134 |
+
extracted = extract_garment(original_image, mask_binary)
|
| 135 |
+
return (mask_binary * 255).astype(np.uint8), extracted, overlay
|
| 136 |
+
|
| 137 |
+
# Custom CSS for better styling
|
| 138 |
+
custom_css = """
|
| 139 |
+
#title {
|
| 140 |
+
text-align: center;
|
| 141 |
+
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
|
| 142 |
+
-webkit-background-clip: text;
|
| 143 |
+
-webkit-text-fill-color: transparent;
|
| 144 |
+
font-size: 3em;
|
| 145 |
+
font-weight: bold;
|
| 146 |
+
margin-bottom: 0.5em;
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
#description {
|
| 150 |
+
text-align: center;
|
| 151 |
+
font-size: 1.2em;
|
| 152 |
+
color: #666;
|
| 153 |
+
margin-bottom: 2em;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
#model-info {
|
| 157 |
+
background: #f8f9fa;
|
| 158 |
+
padding: 1.5em;
|
| 159 |
+
border-radius: 10px;
|
| 160 |
+
margin: 1em 0;
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
.performance-badge {
|
| 164 |
+
background: #28a745;
|
| 165 |
+
color: white;
|
| 166 |
+
padding: 0.3em 0.8em;
|
| 167 |
+
border-radius: 15px;
|
| 168 |
+
font-weight: bold;
|
| 169 |
+
display: inline-block;
|
| 170 |
+
margin: 0.2em;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
footer {
|
| 174 |
+
text-align: center;
|
| 175 |
+
margin-top: 2em;
|
| 176 |
+
padding: 1em;
|
| 177 |
+
color: #888;
|
| 178 |
+
}
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
# Create Gradio Interface
|
| 182 |
+
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
| 183 |
+
|
| 184 |
+
# Header
|
| 185 |
+
gr.Markdown("<h1 id='title'>👗 Garment Segmentation</h1>")
|
| 186 |
+
gr.Markdown(
|
| 187 |
+
"<p id='description'>AI-powered garment extraction for fashion and virtual try-on applications</p>"
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
# Model Information
|
| 191 |
+
with gr.Accordion("📊 Model Information", open=False):
|
| 192 |
+
gr.Markdown("""
|
| 193 |
+
<div id='model-info'>
|
| 194 |
+
|
| 195 |
+
### Architecture
|
| 196 |
+
- **Model**: U-Net with ResNet50 encoder
|
| 197 |
+
- **Input Size**: 768 × 768 pixels
|
| 198 |
+
- **Training Dataset**: DeepFashion2
|
| 199 |
+
- **Performance**: <span class='performance-badge'>Val IoU: 89.64%</span>
|
| 200 |
+
|
| 201 |
+
### Key Features
|
| 202 |
+
- 🎯 High-precision garment segmentation
|
| 203 |
+
- ⚡ Fast inference (GPU-accelerated)
|
| 204 |
+
- 🎨 Multiple visualization options
|
| 205 |
+
- 🔧 Adjustable confidence threshold
|
| 206 |
+
|
| 207 |
+
### Use Cases
|
| 208 |
+
- Virtual try-on applications
|
| 209 |
+
- Fashion e-commerce product editing
|
| 210 |
+
- Garment dataset preprocessing
|
| 211 |
+
- Clothing item extraction and isolation
|
| 212 |
+
|
| 213 |
+
</div>
|
| 214 |
+
""")
|
| 215 |
+
|
| 216 |
+
# Main Interface
|
| 217 |
+
with gr.Row():
|
| 218 |
+
with gr.Column(scale=1):
|
| 219 |
+
input_image = gr.Image(
|
| 220 |
+
label="📤 Upload Image",
|
| 221 |
+
type="pil",
|
| 222 |
+
height=400
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
threshold = gr.Slider(
|
| 226 |
+
minimum=0.1,
|
| 227 |
+
maximum=0.9,
|
| 228 |
+
value=0.5,
|
| 229 |
+
step=0.05,
|
| 230 |
+
label="🎚️ Confidence Threshold",
|
| 231 |
+
info="Adjust to refine the segmentation mask"
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
submit_btn = gr.Button("🚀 Segment Garment", variant="primary", size="lg")
|
| 235 |
+
|
| 236 |
+
gr.Markdown("### 💡 Tips:")
|
| 237 |
+
gr.Markdown("""
|
| 238 |
+
- Upload clear photos with visible garments
|
| 239 |
+
- Works best with upper-body clothing
|
| 240 |
+
- Adjust threshold if mask is too loose/tight
|
| 241 |
+
- Try different angles for best results
|
| 242 |
+
""")
|
| 243 |
+
|
| 244 |
+
with gr.Column(scale=2):
|
| 245 |
+
gr.Markdown("### 📊 Results")
|
| 246 |
+
|
| 247 |
+
with gr.Row():
|
| 248 |
+
output_overlay = gr.Image(
|
| 249 |
+
label="🎨 Overlay (Mask + Original)",
|
| 250 |
+
height=300
|
| 251 |
+
)
|
| 252 |
+
output_extracted = gr.Image(
|
| 253 |
+
label="✂️ Extracted Garment",
|
| 254 |
+
height=300
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
output_mask = gr.Image(
|
| 258 |
+
label="🎭 Binary Mask",
|
| 259 |
+
height=300
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# Examples
|
| 263 |
+
gr.Markdown("### 🖼️ Try These Examples")
|
| 264 |
+
gr.Examples(
|
| 265 |
+
examples=[
|
| 266 |
+
["examples/fashion1.jpg", 0.5],
|
| 267 |
+
["examples/fashion2.jpg", 0.5],
|
| 268 |
+
["examples/fashion3.jpg", 0.5],
|
| 269 |
+
],
|
| 270 |
+
inputs=[input_image, threshold],
|
| 271 |
+
outputs=[output_overlay, output_extracted, output_mask],
|
| 272 |
+
fn=segment_garment,
|
| 273 |
+
cache_examples=False,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# Event handlers
|
| 277 |
+
submit_btn.click(
|
| 278 |
+
fn=segment_garment,
|
| 279 |
+
inputs=[input_image, threshold],
|
| 280 |
+
outputs=[output_overlay, output_extracted, output_mask]
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# Auto-run on image upload
|
| 284 |
+
input_image.change(
|
| 285 |
+
fn=segment_garment,
|
| 286 |
+
inputs=[input_image, threshold],
|
| 287 |
+
outputs=[output_overlay, output_extracted, output_mask]
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
# Footer
|
| 291 |
+
gr.Markdown("""
|
| 292 |
+
<footer>
|
| 293 |
+
<hr>
|
| 294 |
+
<p>
|
| 295 |
+
Built with ❤️ using <a href="https://gradio.app">Gradio</a> |
|
| 296 |
+
Model: <a href="https://huggingface.co/zyuzuguldu/garment-segmentation-unet-resnet50">garment-segmentation-unet-resnet50</a> |
|
| 297 |
+
<a href="https://github.com/zyuzuguldu">GitHub</a>
|
| 298 |
+
</p>
|
| 299 |
+
</footer>
|
| 300 |
+
""")
|
| 301 |
+
|
| 302 |
+
# Launch the app
|
| 303 |
+
if __name__ == "__main__":
|
| 304 |
+
demo.launch()
|
examples/fashion1.jpg
ADDED
|
Git LFS Details
|
examples/fashion2.jpg
ADDED
|
Git LFS Details
|
examples/fashion3.jpg
ADDED
|
Git LFS Details
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
torch>=2.0.0
|
| 3 |
+
torchvision>=0.15.0
|
| 4 |
+
segmentation-models-pytorch
|
| 5 |
+
opencv-python-headless
|
| 6 |
+
numpy
|
| 7 |
+
pillow
|
| 8 |
+
safetensors
|
| 9 |
+
huggingface-hub
|
| 10 |
+
matplotlib
|