VDNT11 commited on
Commit
990270d
·
verified ·
1 Parent(s): 0a4022e

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +54 -12
  2. angle_detection_app.py +240 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,12 +1,54 @@
1
- ---
2
- title: Angle Measure
3
- emoji: 🚀
4
- colorFrom: purple
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.23.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Angle Detection App
2
+
3
+ A Gradio web application for detecting bends and measuring angles in images.
4
+
5
+ ## Local Deployment
6
+
7
+ 1. Install dependencies:
8
+ ```bash
9
+ pip install -r requirements.txt
10
+ ```
11
+
12
+ 2. Run the app:
13
+ ```bash
14
+ python angle_detection_app.py
15
+ ```
16
+
17
+ 3. Open your browser and navigate to the URL shown in the terminal (typically http://127.0.0.1:7860)
18
+
19
+ ## Hugging Face Spaces Deployment
20
+
21
+ 1. Create a new Space on Hugging Face:
22
+ - Go to https://huggingface.co/spaces
23
+ - Click "New Space"
24
+ - Choose "Gradio" as the SDK
25
+ - Give your space a name
26
+
27
+ 2. Push your code to the Space:
28
+ ```bash
29
+ git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
30
+ cd YOUR_SPACE_NAME
31
+ # Copy your files here
32
+ git add .
33
+ git commit -m "Initial commit"
34
+ git push
35
+ ```
36
+
37
+ ## Docker Deployment
38
+
39
+ 1. Build the Docker image:
40
+ ```bash
41
+ docker build -t angle-detection-app .
42
+ ```
43
+
44
+ 2. Run the container:
45
+ ```bash
46
+ docker run -p 7860:7860 angle-detection-app
47
+ ```
48
+
49
+ 3. Access the app at http://localhost:7860
50
+
51
+ ## Requirements
52
+
53
+ - Python 3.8+
54
+ - See requirements.txt for Python package dependencies
angle_detection_app.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from typing import Tuple, List
6
+ import tempfile
7
+ import os
8
+
9
+ def detect_bends_and_angles(
10
+ image,
11
+ blur_kernel_size: int = 7,
12
+ canny_threshold1: int = 30,
13
+ canny_threshold2: int = 150,
14
+ dilation_kernel_size: int = 2,
15
+ hough_threshold: int = 50,
16
+ min_line_length: int = 10,
17
+ max_line_gap: int = 60,
18
+ bend_threshold: int = 15,
19
+ debug: bool = True
20
+ ) -> Tuple[List[Tuple[int, int]], List[Tuple[Tuple[int, int], float]]]:
21
+ """
22
+ Detect bends and calculate angles relative to horizontal with configurable parameters.
23
+ """
24
+ # Convert image to grayscale
25
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
26
+
27
+ # Step 2: Apply Gaussian blur
28
+ # Ensure blur_kernel_size is odd and greater than 0
29
+ if blur_kernel_size is None:
30
+ blur_kernel_size = 3 # Default to 3 if not provided
31
+ blur_kernel_size = max(3, blur_kernel_size | 1) # Ensure it's an odd number
32
+ blurred = cv2.GaussianBlur(gray, (blur_kernel_size, blur_kernel_size), 0)
33
+
34
+ # Step 3: Perform edge detection
35
+ edges = cv2.Canny(blurred, canny_threshold1, canny_threshold2)
36
+
37
+ # Step 4: Dilate edges
38
+ kernel = np.ones((dilation_kernel_size, dilation_kernel_size), np.uint8)
39
+ dilated = cv2.dilate(edges, kernel, iterations=1)
40
+
41
+ # Step 5: Detect parallel lines and identify bends
42
+ height, width = dilated.shape
43
+ lines = cv2.HoughLinesP(
44
+ dilated,
45
+ rho=1,
46
+ theta=np.pi/180,
47
+ threshold=hough_threshold,
48
+ minLineLength=min_line_length,
49
+ maxLineGap=max_line_gap
50
+ )
51
+
52
+ bend_points = []
53
+ if lines is not None:
54
+ segments = []
55
+ for line in lines:
56
+ x1, y1, x2, y2 = line[0]
57
+ if x1 > x2:
58
+ x1, x2 = x2, x1
59
+ y1, y2 = y2, y1
60
+ segments.append((x1, y1, x2, y2))
61
+
62
+ segments.sort(key=lambda seg: seg[0], reverse=True)
63
+
64
+ for i in range(len(segments) - 1):
65
+ x1, y1, x2, y2 = segments[i]
66
+ x1_next, y1_next, x2_next, y2_next = segments[i + 1]
67
+
68
+ if abs(x1 - x1_next) < bend_threshold and abs(y1 - y1_next) < bend_threshold:
69
+ bend_points.append((x1, y1))
70
+
71
+ # Step 6: Calculate angles between bends
72
+ angles = []
73
+ for i in range(len(bend_points) - 1):
74
+ x1, y1 = bend_points[i]
75
+ x2, y2 = bend_points[i + 1]
76
+ dx, dy = x2 - x1, y2 - y1
77
+ angle = np.arctan2(dy, dx) * 180 / np.pi
78
+ angle = angle if angle >= 0 else angle + 180
79
+ angles.append((bend_points[i], angle))
80
+
81
+ return bend_points, angles
82
+
83
+ def process_image(
84
+ image,
85
+ blur_kernel_size: int,
86
+ canny_threshold1: int,
87
+ canny_threshold2: int,
88
+ dilation_kernel_size: int,
89
+ hough_threshold: int,
90
+ min_line_length: int,
91
+ max_line_gap: int,
92
+ bend_threshold: int
93
+ ) -> Tuple[np.ndarray, str]:
94
+ """
95
+ Process the image and return the visualization and angle measurements.
96
+ """
97
+ # Convert Gradio image to numpy array if needed
98
+ if isinstance(image, dict):
99
+ image = image['image']
100
+ if isinstance(image, str):
101
+ image = cv2.imread(image)
102
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
103
+
104
+ bend_points, angles = detect_bends_and_angles(
105
+ image,
106
+ blur_kernel_size,
107
+ canny_threshold1,
108
+ canny_threshold2,
109
+ dilation_kernel_size,
110
+ hough_threshold,
111
+ min_line_length,
112
+ max_line_gap,
113
+ bend_threshold
114
+ )
115
+
116
+ # Create visualization
117
+ result_img = image.copy()
118
+ for i, (x, y) in enumerate(bend_points):
119
+ cv2.circle(result_img, (x, y), 5, (0, 0, 255), -1)
120
+ cv2.putText(
121
+ result_img, f"Bend {chr(65 + i)}", (x, y - 10),
122
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1
123
+ )
124
+ for (x, y), angle in angles:
125
+ cv2.putText(
126
+ result_img, f"{angle:.1f}°", (x, y + 20),
127
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1
128
+ )
129
+
130
+ # Create angle measurements text
131
+ measurements = "Angle Measurements:\n"
132
+ for i, ((x, y), angle) in enumerate(angles):
133
+ measurements += f"Bend {chr(65 + i)} at ({x}, {y}): {angle:.1f}°\n"
134
+
135
+ return result_img, measurements
136
+
137
+ def create_gradio_interface():
138
+ with gr.Blocks(title="Angle Detection App", theme=gr.themes.Soft()) as interface:
139
+ gr.Markdown("# Angle Detection App")
140
+ gr.Markdown("Upload an image to detect bends and measure angles.")
141
+
142
+ with gr.Row():
143
+ with gr.Column():
144
+ input_image = gr.Image(label="Input Image", type="numpy")
145
+
146
+ with gr.Accordion("Algorithm Parameters", open=False):
147
+ blur_kernel_size = gr.Slider(
148
+ minimum=3, maximum=15, step=2,
149
+ value=7, label="Blur Kernel Size"
150
+ )
151
+ canny_threshold1 = gr.Slider(
152
+ minimum=0, maximum=100, step=10,
153
+ value=30, label="Canny Threshold 1"
154
+ )
155
+ canny_threshold2 = gr.Slider(
156
+ minimum=100, maximum=300, step=10,
157
+ value=150, label="Canny Threshold 2"
158
+ )
159
+ dilation_kernel_size = gr.Slider(
160
+ minimum=1, maximum=5, step=1,
161
+ value=2, label="Dilation Kernel Size"
162
+ )
163
+ hough_threshold = gr.Slider(
164
+ minimum=10, maximum=100, step=10,
165
+ value=50, label="Hough Threshold"
166
+ )
167
+ min_line_length = gr.Slider(
168
+ minimum=5, maximum=50, step=5,
169
+ value=10, label="Minimum Line Length"
170
+ )
171
+ max_line_gap = gr.Slider(
172
+ minimum=10, maximum=100, step=10,
173
+ value=60, label="Maximum Line Gap"
174
+ )
175
+ bend_threshold = gr.Slider(
176
+ minimum=5, maximum=30, step=5,
177
+ value=15, label="Bend Threshold"
178
+ )
179
+
180
+ process_btn = gr.Button("Process Image", variant="primary")
181
+
182
+ with gr.Column():
183
+ output_image = gr.Image(label="Result")
184
+ output_text = gr.Textbox(label="Measurements", lines=10)
185
+
186
+ process_btn.click(
187
+ fn=process_image,
188
+ inputs=[
189
+ input_image,
190
+ blur_kernel_size,
191
+ canny_threshold1,
192
+ canny_threshold2,
193
+ dilation_kernel_size,
194
+ hough_threshold,
195
+ min_line_length,
196
+ max_line_gap,
197
+ bend_threshold
198
+ ],
199
+ outputs=[output_image, output_text]
200
+ )
201
+
202
+ # Add example images
203
+ gr.Examples(
204
+ examples=[
205
+ ["Initial_images/22432269-0abf-4af8-b4b3-207bb48867cf.jpeg"],
206
+ ["Initial_images/processed_JPG/1b_crop.png"],
207
+ ["Initial_images/processed_JPG/7feb_00.png"],
208
+ ],
209
+ inputs=input_image,
210
+ outputs=[output_image, output_text],
211
+ fn=process_image,
212
+ cache_examples=True,
213
+ )
214
+
215
+ return interface
216
+
217
+ if __name__ == "__main__":
218
+ interface = create_gradio_interface()
219
+ # Get port from environment variable or use a different default port
220
+ port = int(os.environ.get("GRADIO_SERVER_PORT", 7861))
221
+ # Get host from environment variable or use default
222
+ host = os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0")
223
+ # Launch the interface with error handling
224
+ try:
225
+ interface.launch(
226
+ server_name=host,
227
+ server_port=port,
228
+ share=True # Set to True to create a public URL
229
+ )
230
+ except OSError as e:
231
+ print(f"Port {port} is in use. Trying next port...")
232
+ try:
233
+ interface.launch(
234
+ server_name=host,
235
+ server_port=port + 1,
236
+ share=True
237
+ )
238
+ except Exception as e:
239
+ print(f"Error launching the interface: {e}")
240
+ print("Please try a different port by setting the GRADIO_SERVER_PORT environment variable")
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ opencv-python>=4.8.0
3
+ numpy>=1.24.0
4
+ matplotlib>=3.7.0
5
+ Pillow>=10.0.0
6
+ pillow-heif>=0.15.0