leonelhs commited on
Commit
f2c4bda
·
verified ·
1 Parent(s): 4324279

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #######################################################################################
2
+ #
3
+ # MIT License
4
+ #
5
+ # Copyright (c) [2025] [[email protected]]
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+ #
25
+ #######################################################################################
26
+ #
27
+ #
28
+ # Source code is based on or inspired by several projects.
29
+ # For more details and proper attribution, please refer to the following resources:
30
+ #
31
+ # - [stackoverflow] - [https://stackoverflow.com/questions/22656698/perspective-correction-in-opencv-using-python]
32
+ # - [rembg] [https://huggingface.co/spaces/leonelhs/rembg]
33
+ # - [rembg] [https://github.com/danielgatis/rembg]
34
+ # - [Chatgpt] [https://chatgpt.com/]
35
+ #
36
+ # The image is first processed by an AI service.
37
+ # This step provides a cleaner, bounded version of the image,
38
+ # because OpenCV’s edge detection is not always reliable on raw inputs.
39
+ # With the improved intermediate image, OpenCV can detect borders more consistently
40
+ # and the perspective unwrap produces better results.
41
+
42
+
43
+ import cv2
44
+ import numpy as np
45
+ import gradio as gr
46
+ from gradio_client import Client, handle_file
47
+
48
+ client = Client("leonelhs/rembg")
49
+
50
+ def unwrap(image, mask):
51
+ img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
52
+ gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
53
+
54
+ _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
55
+ contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
56
+ contours = sorted(contours, key=cv2.contourArea, reverse=True)
57
+
58
+ if len(contours) > 0:
59
+ cnt = contours[0]
60
+ peri = cv2.arcLength(cnt, True)
61
+ approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
62
+
63
+ if len(approx) == 4:
64
+ corners = approx.reshape(4, 2).astype(np.float32)
65
+
66
+ # Order points: top-left, top-right, bottom-right, bottom-left
67
+ rect = np.zeros((4, 2), dtype="float32")
68
+ s = corners.sum(axis=1)
69
+ rect[0] = corners[np.argmin(s)]
70
+ rect[2] = corners[np.argmax(s)]
71
+
72
+ diff = np.diff(corners, axis=1)
73
+ rect[1] = corners[np.argmin(diff)]
74
+ rect[3] = corners[np.argmax(diff)]
75
+
76
+ (tl, tr, br, bl) = rect
77
+
78
+ # Compute width & height
79
+ widthA = np.linalg.norm(br - bl)
80
+ widthB = np.linalg.norm(tr - tl)
81
+ maxWidth = int(max(widthA, widthB))
82
+
83
+ heightA = np.linalg.norm(tr - br)
84
+ heightB = np.linalg.norm(tl - bl)
85
+ maxHeight = int(max(heightA, heightB))
86
+
87
+ dst = np.array([
88
+ [0, 0],
89
+ [maxWidth - 1, 0],
90
+ [maxWidth - 1, maxHeight - 1],
91
+ [0, maxHeight - 1]
92
+ ], dtype="float32")
93
+
94
+ # Perspective transform
95
+ M = cv2.getPerspectiveTransform(rect, dst)
96
+ warped = cv2.warpPerspective(img, M, (maxWidth, maxHeight))
97
+
98
+ return cv2.cvtColor(warped, cv2.COLOR_BGR2RGB), mask, corners
99
+
100
+ # fallback: return original if no rectangle
101
+ return image, mask, contours
102
+
103
+ def predict(img):
104
+ """
105
+ Unwrap an image using AI-assisted preprocessing and OpenCV.
106
+
107
+ The algorithm first leverages an AI service to generate a cleaner,
108
+ well-bounded intermediate image. This helps OpenCV detect borders
109
+ more reliably before performing the perspective unwrap.
110
+
111
+ Parameters:
112
+ img (string): File path to the input image to be unwrapped.
113
+
114
+ Returns:
115
+ path (string): File path to the generated, unwrapped image.
116
+ """
117
+
118
+ # Step 1: Use an AI service to preprocess the image.
119
+ # - OpenCV can detect edges, but results are inconsistent depending on noise/lighting.
120
+ # - The AI model generates a cleaner, well-bounded intermediate image.
121
+ crop, mask = client.predict(image=handle_file(img), session="U2NET", smoot=True, api_name="/predict")
122
+
123
+ # Step 2: Apply OpenCV on this intermediate image for more accurate border detection
124
+ # before performing the perspective unwrap.
125
+ crop = cv2.imread(crop)
126
+ mask = cv2.imread(mask)
127
+ return unwrap(crop, mask)
128
+
129
+
130
+ with gr.Blocks() as app:
131
+ gr.Markdown("## 🖼️ Rectangle Detection & Perspective Unwrap")
132
+ with gr.Row():
133
+ with gr.Column(scale=1):
134
+ inp = gr.Image(type="filepath", label="Upload Image")
135
+ btn_unwrap = gr.Button("📐 Perspective Unwrap")
136
+ with gr.Column(scale=2):
137
+ with gr.Row():
138
+ with gr.Column(scale=1):
139
+ out_unwrap = gr.Image(type="numpy", label="Unwrapped Rectangle")
140
+ with gr.Accordion("See intermediates", open=False):
141
+ out_mask = gr.Image(type="numpy", label="Detected Corners")
142
+ out_corners = gr.JSON(label="Corners (x,y)")
143
+
144
+ btn_unwrap.click(predict, inputs=inp, outputs=[out_unwrap, out_mask, out_corners])
145
+
146
+ app.launch(share=False, debug=True, show_error=True, mcp_server=True)
147
+ app.queue()
148
+