Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import cv2
|
5 |
+
from PIL import Image
|
6 |
+
from torchvision import transforms
|
7 |
+
from cloth_segmentation.networks.u2net import U2NET
|
8 |
+
|
9 |
+
# ---------------------- MODEL LOAD ---------------------- #
|
10 |
+
@st.cache_resource
|
11 |
+
def load_model():
|
12 |
+
model_path = "cloth_segmentation/networks/u2net.pth"
|
13 |
+
model = U2NET(3, 1)
|
14 |
+
state_dict = torch.load(model_path, map_location=torch.device('cpu'))
|
15 |
+
state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()}
|
16 |
+
model.load_state_dict(state_dict)
|
17 |
+
model.eval()
|
18 |
+
return model
|
19 |
+
|
20 |
+
model = load_model()
|
21 |
+
|
22 |
+
# ---------------------- UTILITY FUNCTIONS ---------------------- #
|
23 |
+
def refine_mask(mask):
|
24 |
+
close_kernel = np.ones((5, 5), np.uint8)
|
25 |
+
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel)
|
26 |
+
erode_kernel = np.ones((3, 3), np.uint8)
|
27 |
+
mask = cv2.erode(mask, erode_kernel, iterations=1)
|
28 |
+
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel)
|
29 |
+
mask = cv2.GaussianBlur(mask, (5, 5), 1.5)
|
30 |
+
return mask
|
31 |
+
|
32 |
+
def segment_dress(image_np):
|
33 |
+
transform_pipeline = transforms.Compose([
|
34 |
+
transforms.ToTensor(),
|
35 |
+
transforms.Resize((320, 320))
|
36 |
+
])
|
37 |
+
image = Image.fromarray(image_np).convert("RGB")
|
38 |
+
input_tensor = transform_pipeline(image).unsqueeze(0)
|
39 |
+
with torch.no_grad():
|
40 |
+
output = model(input_tensor)[0][0].squeeze().cpu().numpy()
|
41 |
+
output = (output - output.min()) / (output.max() - output.min() + 1e-8)
|
42 |
+
adaptive_thresh = np.mean(output) + 0.2
|
43 |
+
dress_mask = (output > adaptive_thresh).astype(np.uint8) * 255
|
44 |
+
dress_mask = cv2.resize(dress_mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST)
|
45 |
+
return refine_mask(dress_mask)
|
46 |
+
|
47 |
+
def apply_grabcut(image_np, dress_mask):
|
48 |
+
bgd_model = np.zeros((1, 65), np.float64)
|
49 |
+
fgd_model = np.zeros((1, 65), np.float64)
|
50 |
+
mask = np.where(dress_mask > 0, cv2.GC_PR_FGD, cv2.GC_BGD).astype('uint8')
|
51 |
+
coords = cv2.findNonZero(dress_mask)
|
52 |
+
if coords is not None:
|
53 |
+
x, y, w, h = cv2.boundingRect(coords)
|
54 |
+
rect = (x, y, w, h)
|
55 |
+
cv2.grabCut(image_np, mask, rect, bgd_model, fgd_model, 3, cv2.GC_INIT_WITH_MASK)
|
56 |
+
refined_mask = np.where((mask == cv2.GC_FGD) | (mask == cv2.GC_PR_FGD), 255, 0).astype("uint8")
|
57 |
+
return refine_mask(refined_mask)
|
58 |
+
|
59 |
+
def recolor_dress(image_np, dress_mask, target_color):
|
60 |
+
target_color_lab = cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2LAB)[0][0]
|
61 |
+
img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
|
62 |
+
dress_pixels = img_lab[dress_mask > 0]
|
63 |
+
if len(dress_pixels) == 0:
|
64 |
+
return image_np
|
65 |
+
mean_L, mean_A, mean_B = np.mean(dress_pixels, axis=0)
|
66 |
+
a_shift = target_color_lab[1] - mean_A
|
67 |
+
b_shift = target_color_lab[2] - mean_B
|
68 |
+
img_lab[..., 1] = np.clip(img_lab[..., 1] + (dress_mask / 255.0) * a_shift, 0, 255)
|
69 |
+
img_lab[..., 2] = np.clip(img_lab[..., 2] + (dress_mask / 255.0) * b_shift, 0, 255)
|
70 |
+
img_recolored = cv2.cvtColor(img_lab.astype(np.uint8), cv2.COLOR_LAB2RGB)
|
71 |
+
feathered_mask = cv2.GaussianBlur(dress_mask, (21, 21), 7)
|
72 |
+
lightness_mask = (img_lab[..., 0] / 255.0) ** 0.7
|
73 |
+
adaptive_feather = (feathered_mask * lightness_mask).astype(np.uint8)
|
74 |
+
return (image_np * (1 - adaptive_feather[..., None] / 255) + img_recolored * (adaptive_feather[..., None] / 255)).astype(np.uint8)
|
75 |
+
|
76 |
+
def change_dress_color(img, color):
|
77 |
+
color_map = {
|
78 |
+
"Red": (0, 0, 255), "Blue": (255, 0, 0), "Green": (0, 255, 0),
|
79 |
+
"Yellow": (0, 255, 255), "Purple": (128, 0, 128), "Orange": (0, 165, 255),
|
80 |
+
"Cyan": (255, 255, 0), "Magenta": (255, 0, 255), "White": (255, 255, 255),
|
81 |
+
"Black": (0, 0, 0)
|
82 |
+
}
|
83 |
+
new_color_bgr = color_map.get(color, (0, 0, 255))
|
84 |
+
img_np = np.array(img)
|
85 |
+
try:
|
86 |
+
dress_mask = segment_dress(img_np)
|
87 |
+
if np.sum(dress_mask) < 1000:
|
88 |
+
return img
|
89 |
+
dress_mask = apply_grabcut(img_np, dress_mask)
|
90 |
+
img_recolored = recolor_dress(img_np, dress_mask, new_color_bgr)
|
91 |
+
return Image.fromarray(img_recolored)
|
92 |
+
except Exception as e:
|
93 |
+
st.error(f"Error processing image: {str(e)}")
|
94 |
+
return img
|
95 |
+
|
96 |
+
# ---------------------- STREAMLIT UI ---------------------- #
|
97 |
+
st.title("👗 AI Dress Color Changer")
|
98 |
+
st.markdown("Upload a dress image and select a new color for realistic recoloring")
|
99 |
+
|
100 |
+
uploaded_img = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
|
101 |
+
color_option = st.selectbox("Choose a Color", [
|
102 |
+
"Red", "Blue", "Green", "Yellow", "Purple",
|
103 |
+
"Orange", "Cyan", "Magenta", "White", "Black"
|
104 |
+
])
|
105 |
+
|
106 |
+
if uploaded_img:
|
107 |
+
image = Image.open(uploaded_img).convert("RGB")
|
108 |
+
st.image(image, caption="Original Image", use_column_width=True)
|
109 |
+
|
110 |
+
if st.button("Recolor Dress"):
|
111 |
+
with st.spinner("Processing..."):
|
112 |
+
result = change_dress_color(image, color_option)
|
113 |
+
st.image(result, caption="Recolored Dress", use_column_width=True)
|