|
import gradio as gr |
|
import torch |
|
import cv2 |
|
import numpy as np |
|
from torchvision import transforms |
|
from PIL import Image |
|
from transformers import DPTForDepthEstimation, DPTFeatureExtractor |
|
import torchvision.transforms.functional as F |
|
|
|
|
|
model_name = "Intel/dpt-large" |
|
feature_extractor = DPTFeatureExtractor.from_pretrained(model_name) |
|
depth_model = DPTForDepthEstimation.from_pretrained(model_name) |
|
depth_model.eval() |
|
|
|
def estimate_depth(image): |
|
"""Estimate depth map from image.""" |
|
image = image.convert("RGB").resize((384, 384)) |
|
inputs = feature_extractor(images=image, return_tensors="pt") |
|
with torch.no_grad(): |
|
outputs = depth_model(**inputs) |
|
depth = outputs.predicted_depth.squeeze().cpu().numpy() |
|
depth = cv2.resize(depth, (image.width, image.height)) |
|
depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255 |
|
return depth.astype(np.uint8) |
|
|
|
def warp_design(cloth_img, design_img): |
|
"""Warp the design onto the clothing while preserving folds.""" |
|
cloth_img = cloth_img.convert("RGB") |
|
design_img = design_img.convert("RGB") |
|
cloth_np = np.array(cloth_img) |
|
design_np = np.array(design_img) |
|
h, w, _ = cloth_np.shape |
|
|
|
|
|
depth_map = estimate_depth(cloth_img) |
|
depth_map = cv2.resize(depth_map, (w, h)) |
|
|
|
|
|
flow = cv2.calcOpticalFlowFarneback(depth_map, depth_map, None, 0.5, 3, 15, 3, 5, 1.2, 0) |
|
flow_map = np.column_stack((flow[..., 0] + np.arange(w), flow[..., 1] + np.arange(h)[:, None])) |
|
warped_design = cv2.remap(design_np, flow_map, None, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT) |
|
|
|
|
|
blended = cv2.addWeighted(cloth_np, 0.7, warped_design, 0.3, 0) |
|
|
|
return Image.fromarray(blended) |
|
|
|
def main(cloth, design): |
|
return warp_design(cloth, design) |
|
|
|
iface = gr.Interface( |
|
fn=main, |
|
inputs=[gr.Image(type="pil"), gr.Image(type="pil")], |
|
outputs=gr.Image(type="pil"), |
|
title="AI Cloth Design Warping", |
|
description="Upload a clothing image and a design to blend it naturally, ensuring it stays centered and follows fabric folds." |
|
) |
|
|
|
if __name__ == "__main__": |
|
iface.launch(share=True) |