gaur3009 commited on
Commit
07180e9
·
verified ·
1 Parent(s): 53a7ff9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image, ImageDraw, ImageFont
4
+ import gradio as gr
5
+
6
+ def detect_shirt_contour(image):
7
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
8
+ blurred = cv2.GaussianBlur(gray, (5, 5), 0)
9
+ edges = cv2.Canny(blurred, 50, 150)
10
+
11
+ contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
12
+ contours = sorted(contours, key=cv2.contourArea, reverse=True)
13
+
14
+ if contours:
15
+ return cv2.boundingRect(contours[0])
16
+ return None
17
+
18
+ def warp_text(image, text, font_size, color):
19
+ pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)).convert("RGBA")
20
+ draw = ImageDraw.Draw(pil_image)
21
+
22
+ font_path = "arial.ttf" # Use a valid font
23
+ font = ImageFont.truetype(font_path, font_size)
24
+
25
+ text_width, text_height = draw.textsize(text, font=font)
26
+ text_overlay = Image.new("RGBA", (text_width, text_height), (255, 255, 255, 0))
27
+ text_draw = ImageDraw.Draw(text_overlay)
28
+ text_draw.text((0, 0), text, font=font, fill=color + (255,))
29
+
30
+ text_np = np.array(text_overlay)
31
+
32
+ shirt_bbox = detect_shirt_contour(image)
33
+ if not shirt_bbox:
34
+ return "Failed to detect shirt region."
35
+
36
+ x, y, w, h = shirt_bbox
37
+ src_points = np.float32([[0, 0], [text_width, 0], [0, text_height], [text_width, text_height]])
38
+ dst_points = np.float32([[x, y], [x + w, y], [x, y + h], [x + w, y + h]])
39
+
40
+ matrix = cv2.getPerspectiveTransform(src_points, dst_points)
41
+ warped_text = cv2.warpPerspective(text_np, matrix, (image.shape[1], image.shape[0]))
42
+
43
+ warped_text_pil = Image.fromarray(warped_text)
44
+ blended = Image.alpha_composite(pil_image, warped_text_pil).convert("RGB")
45
+
46
+ return blended
47
+
48
+ def gradio_interface(image, text, font_size, color):
49
+ color_tuple = tuple(map(int, color.lstrip('#')[1:].lower()))
50
+ img = cv2.imdecode(np.frombuffer(image.read(), np.uint8), cv2.IMREAD_COLOR)
51
+ return warp_text(img, text, font_size, color_tuple)
52
+
53
+ gr.Interface(
54
+ fn=gradio_interface,
55
+ inputs=[
56
+ gr.Image(type="file", label="Upload T-shirt Image"),
57
+ gr.Textbox(label="Enter Text"),
58
+ gr.Slider(10, 150, step=5, label="Font Size"),
59
+ gr.ColorPicker(label="Text Color")
60
+ ],
61
+ outputs=gr.Image(label="Warped T-shirt Design"),
62
+ title="Advanced T-shirt Text Warping",
63
+ description="Upload a t-shirt image and see the text realistically warp onto the fabric."
64
+ ).launch()