umairahmad1789 commited on
Commit
2c880eb
1 Parent(s): d39fb79

Upload 11 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/Test20.jpg filter=lfs diff=lfs merge=lfs -text
37
+ examples/Test21.jpg filter=lfs diff=lfs merge=lfs -text
38
+ examples/Test22.jpg filter=lfs diff=lfs merge=lfs -text
39
+ examples/Test23.jpg filter=lfs diff=lfs merge=lfs -text
Reference_ScalingBox.jpg ADDED
app.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from typing import List, Union
4
+ from PIL import Image
5
+ import numpy as np
6
+ import torch
7
+ from torchvision import transforms
8
+ from ultralytics import YOLOWorld, YOLO
9
+ from ultralytics.engine.results import Results
10
+ from ultralytics.utils.plotting import save_one_box
11
+ from transformers import AutoModelForImageSegmentation
12
+ import cv2
13
+ import ezdxf
14
+ import gradio as gr
15
+ import gc
16
+ from scalingtestupdated import calculate_scaling_factor
17
+
18
+
19
+
20
+ def yolo_detect(
21
+ image: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor],
22
+ classes: List[str],
23
+ ) -> np.ndarray:
24
+ drawer_detector = YOLOWorld("yolov8x-worldv2.pt")
25
+ drawer_detector.set_classes(classes)
26
+ results: List[Results] = drawer_detector.predict(image)
27
+ boxes = []
28
+ for result in results:
29
+ boxes.append(
30
+ save_one_box(result.cpu().boxes.xyxy, im=result.orig_img, save=False)
31
+ )
32
+
33
+ del drawer_detector
34
+
35
+ return boxes[0]
36
+
37
+
38
+ def remove_bg(image: np.ndarray) -> np.ndarray:
39
+ birefnet = AutoModelForImageSegmentation.from_pretrained(
40
+ "zhengpeng7/BiRefNet", trust_remote_code=True
41
+ )
42
+
43
+ device = "cpu"
44
+ torch.set_float32_matmul_precision(["high", "highest"][0])
45
+
46
+ birefnet.to(device)
47
+ birefnet.eval()
48
+ transform_image = transforms.Compose(
49
+ [
50
+ transforms.Resize((1024, 1024)),
51
+ transforms.ToTensor(),
52
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
53
+ ]
54
+ )
55
+
56
+ image = Image.fromarray(image)
57
+ input_images = transform_image(image).unsqueeze(0).to("cpu")
58
+
59
+ # Prediction
60
+ with torch.no_grad():
61
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
62
+ pred = preds[0].squeeze()
63
+
64
+ # Show Results
65
+ pred_pil = transforms.ToPILImage()(pred)
66
+ # Scale proportionally with max length to 1024 for faster showing
67
+ scale_ratio = 1024 / max(image.size)
68
+ scaled_size = (int(image.size[0] * scale_ratio), int(image.size[1] * scale_ratio))
69
+
70
+ del birefnet
71
+
72
+ return np.array(pred_pil.resize(scaled_size))
73
+
74
+ def exclude_scaling_box(image: np.ndarray, bbox: np.ndarray, orig_size: tuple, processed_size: tuple, expansion_factor: float = 1.5) -> np.ndarray:
75
+ # Unpack the bounding box
76
+ x_min, y_min, x_max, y_max = map(int, bbox)
77
+
78
+ # Calculate scaling factors
79
+ scale_x = processed_size[1] / orig_size[1] # Width scale
80
+ scale_y = processed_size[0] / orig_size[0] # Height scale
81
+
82
+ # Adjust bounding box coordinates
83
+ x_min = int(x_min * scale_x)
84
+ x_max = int(x_max * scale_x)
85
+ y_min = int(y_min * scale_y)
86
+ y_max = int(y_max * scale_y)
87
+
88
+ # Calculate expanded box coordinates
89
+ box_width = x_max - x_min
90
+ box_height = y_max - y_min
91
+ expanded_x_min = max(0, int(x_min - (expansion_factor - 1) * box_width / 2))
92
+ expanded_x_max = min(image.shape[1], int(x_max + (expansion_factor - 1) * box_width / 2))
93
+ expanded_y_min = max(0, int(y_min - (expansion_factor - 1) * box_height / 2))
94
+ expanded_y_max = min(image.shape[0], int(y_max + (expansion_factor - 1) * box_height / 2))
95
+
96
+ # Black out the expanded region
97
+ image[expanded_y_min:expanded_y_max, expanded_x_min:expanded_x_max] = 0
98
+
99
+ return image
100
+
101
+
102
+ def extract_outlines(binary_image: np.ndarray) -> np.ndarray:
103
+ """
104
+ Extracts and draws the outlines of masks from a binary image.
105
+ Args:
106
+ binary_image: Grayscale binary image where white represents masks and black is the background.
107
+ Returns:
108
+ Image with outlines drawn.
109
+ """
110
+ # Detect contours from the binary image
111
+ contours, _ = cv2.findContours(
112
+ binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
113
+ )
114
+
115
+ # Create a blank image to draw contours
116
+ outline_image = np.zeros_like(binary_image)
117
+ # Smooth the contours
118
+ smoothed_contours = []
119
+ for contour in contours:
120
+ # Calculate epsilon for approxPolyDP
121
+ epsilon = 0.002 * cv2.arcLength(contour, True)
122
+ # Approximate the contour with fewer points
123
+ smoothed_contour = cv2.approxPolyDP(contour, epsilon, True)
124
+ smoothed_contours.append(smoothed_contour)
125
+
126
+ # Draw the contours on the blank image
127
+ cv2.drawContours(
128
+ outline_image, smoothed_contours, -1, (255), thickness=1
129
+ ) # White color for outlines
130
+
131
+ return cv2.bitwise_not(outline_image), smoothed_contours
132
+
133
+
134
+ def shrink_bbox(image: np.ndarray, shrink_factor: float):
135
+ """
136
+ Crops the central 80% of the image, maintaining proportions for non-square images.
137
+ Args:
138
+ image: Input image as a NumPy array.
139
+ Returns:
140
+ Cropped image as a NumPy array.
141
+ """
142
+ height, width = image.shape[:2]
143
+ center_x, center_y = width // 2, height // 2
144
+
145
+ # Calculate 80% dimensions
146
+ new_width = int(width * shrink_factor)
147
+ new_height = int(height * shrink_factor)
148
+
149
+ # Determine the top-left and bottom-right points for cropping
150
+ x1 = max(center_x - new_width // 2, 0)
151
+ y1 = max(center_y - new_height // 2, 0)
152
+ x2 = min(center_x + new_width // 2, width)
153
+ y2 = min(center_y + new_height // 2, height)
154
+
155
+ # Crop the image
156
+ cropped_image = image[y1:y2, x1:x2]
157
+ return cropped_image
158
+
159
+
160
+ # def to_dxf(outlines):
161
+ # upper_range_tuple = (200)
162
+ # lower_range_tuple = (0)
163
+
164
+ # doc = ezdxf.new('R2010')
165
+ # msp = doc.modelspace()
166
+ # masked_jpg = cv2.inRange(outlines,lower_range_tuple, upper_range_tuple)
167
+
168
+ # for i in range(0,masked_jpg.shape[0]):
169
+ # for j in range(0,masked_jpg.shape[1]):
170
+ # if masked_jpg[i][j] == 255:
171
+ # msp.add_line((j,masked_jpg.shape[0] - i), (j,masked_jpg.shape[0] - i))
172
+
173
+ # doc.saveas("./outputs/out.dxf")
174
+ # return "./outputs/out.dxf"
175
+
176
+ def to_dxf(contours):
177
+ doc = ezdxf.new()
178
+ msp = doc.modelspace()
179
+
180
+ for contour in contours:
181
+ points = [(point[0][0], point[0][1]) for point in contour]
182
+ msp.add_lwpolyline(points, close=True) # Add a polyline for each contour
183
+
184
+ doc.saveas("./outputs/out.dxf")
185
+ return "./outputs/out.dxf"
186
+
187
+ def smooth_contours(contour):
188
+ epsilon = 0.01 * cv2.arcLength(contour, True) # Adjust factor (e.g., 0.01)
189
+ return cv2.approxPolyDP(contour, epsilon, True)
190
+
191
+
192
+ def scale_image(image: np.ndarray, scale_factor: float) -> np.ndarray:
193
+ """
194
+ Resize image by scaling both width and height by the same factor.
195
+
196
+ Args:
197
+ image: Input numpy image
198
+ scale_factor: Factor to scale the image (e.g., 0.5 for half size, 2 for double size)
199
+
200
+ Returns:
201
+ np.ndarray: Resized image
202
+ """
203
+ if scale_factor <= 0:
204
+ raise ValueError("Scale factor must be positive")
205
+
206
+ current_height, current_width = image.shape[:2]
207
+
208
+ # Calculate new dimensions
209
+ new_width = int(current_width * scale_factor)
210
+ new_height = int(current_height * scale_factor)
211
+
212
+ # Choose interpolation method based on whether we're scaling up or down
213
+ interpolation = cv2.INTER_AREA if scale_factor < 1 else cv2.INTER_CUBIC
214
+
215
+ # Resize image
216
+ resized_image = cv2.resize(
217
+ image, (new_width, new_height), interpolation=interpolation
218
+ )
219
+
220
+ return resized_image
221
+
222
+
223
+ def detect_reference_square(img) -> np.ndarray:
224
+ box_detector = YOLO("./last.pt")
225
+ res = box_detector.predict(img)
226
+ del box_detector
227
+ return save_one_box(res[0].cpu().boxes.xyxy, res[0].orig_img, save=False), res[0].cpu().boxes.xyxy[0
228
+ ]
229
+
230
+ def predict(image):
231
+ drawer_img = yolo_detect(image, ["box"])
232
+ shrunked_img = shrink_bbox(drawer_img, 0.8)
233
+ # Detect the scaling reference square
234
+ reference_obj_img, scaling_box_coords = detect_reference_square(shrunked_img)
235
+ reference_obj_img_scaled = shrink_bbox(reference_obj_img, 1.2)
236
+ try:
237
+ scaling_factor = calculate_scaling_factor(
238
+ reference_image_path="./Reference_ScalingBox.jpg",
239
+ target_image=reference_obj_img_scaled,
240
+ feature_detector="SIFT",
241
+ )
242
+ except:
243
+ scaling_factor = 1.0
244
+ # Save original size before `remove_bg` processing
245
+ orig_size = shrunked_img.shape[:2]
246
+ # Generate foreground mask and save its size
247
+ objects_mask = remove_bg(shrunked_img)
248
+ processed_size = objects_mask.shape[:2]
249
+ # Exclude scaling box region from objects mask
250
+ objects_mask = exclude_scaling_box(
251
+ objects_mask, scaling_box_coords, orig_size, processed_size, expansion_factor=3.0
252
+ )
253
+ # Scale the object mask according to scaling factor
254
+ # objects_mask_scaled = scale_image(objects_mask, scaling_factor)
255
+ Image.fromarray(objects_mask).save("./outputs/scaled_mask_new.jpg")
256
+ outlines, contours = extract_outlines(objects_mask)
257
+ dxf = to_dxf(contours)
258
+
259
+ return outlines, dxf, objects_mask, scaling_factor, reference_obj_img_scaled
260
+
261
+
262
+
263
+ if __name__ == "__main__":
264
+ os.makedirs("./outputs", exist_ok=True)
265
+
266
+ ifer = gr.Interface(
267
+ fn=predict,
268
+ inputs=[gr.Image(label="Input Image")],
269
+ outputs=[
270
+ gr.Image(label="Ouput Image"),
271
+ gr.File(label="DXF file"),
272
+ gr.Image(label="Mask"),
273
+ gr.Textbox(label="Scaling Factor(mm)", placeholder="Every pixel is equal to mentioned number in mm(milimeter)"),
274
+ gr.Image(label="Image used for calculating scaling factor")
275
+ ],
276
+ examples=["./examples/Test20.jpg", "./examples/Test21.jpg", "./examples/Test22.jpg", "./examples/Test23.jpg"]
277
+ )
278
+ ifer.launch(share=True)
279
+
examples/Test20.jpg ADDED

Git LFS Details

  • SHA256: bb3cd0135de88af3c869b71544fef57fc588dfd590caf57844fdc8324587aa03
  • Pointer size: 132 Bytes
  • Size of remote file: 2.45 MB
examples/Test21.jpg ADDED

Git LFS Details

  • SHA256: 9e79912e7563650e7b0a3e93aebc6918a9de5397a23278ce979bf5a512a920e0
  • Pointer size: 132 Bytes
  • Size of remote file: 2.65 MB
examples/Test22.jpg ADDED

Git LFS Details

  • SHA256: 199cff40a0951b56557ad31d167029f42dcc144bac7f0678600b486e609bdded
  • Pointer size: 132 Bytes
  • Size of remote file: 2.67 MB
examples/Test23.jpg ADDED

Git LFS Details

  • SHA256: 6d77515b752861465a1ce3fb24083f600874a03cf586a2c07535abb6e826f242
  • Pointer size: 132 Bytes
  • Size of remote file: 2.49 MB
last.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ecf93886616e47bcbd997c9149521eab864aea3c4fa9ff48a95ab23d8ecf51e
3
+ size 6254691
outputs/out.dxf ADDED
outputs/scaled_mask_new.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ transformers
2
+ ultralytics
3
+ ezdxf
4
+ gradio
5
+ kornia
6
+ timm
scalingtestupdated.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import os
4
+ import argparse
5
+ from typing import Union
6
+ from matplotlib import pyplot as plt
7
+
8
+
9
+ class ScalingSquareDetector:
10
+ def __init__(self, feature_detector="ORB", debug=False):
11
+ """
12
+ Initialize the detector with the desired feature matching algorithm.
13
+ :param feature_detector: "ORB" or "SIFT" (default is "ORB").
14
+ :param debug: If True, saves intermediate images for debugging.
15
+ """
16
+ self.feature_detector = feature_detector
17
+ self.debug = debug
18
+ self.detector = self._initialize_detector()
19
+
20
+ def _initialize_detector(self):
21
+ """
22
+ Initialize the chosen feature detector.
23
+ :return: OpenCV detector object.
24
+ """
25
+ if self.feature_detector.upper() == "SIFT":
26
+ return cv2.SIFT_create()
27
+ elif self.feature_detector.upper() == "ORB":
28
+ return cv2.ORB_create()
29
+ else:
30
+ raise ValueError("Invalid feature detector. Choose 'ORB' or 'SIFT'.")
31
+
32
+ def find_scaling_square(
33
+ self, reference_image_path, target_image, known_size_mm, roi_margin=30
34
+ ):
35
+ """
36
+ Detect the scaling square in the target image based on the reference image.
37
+ :param reference_image_path: Path to the reference image of the square.
38
+ :param target_image_path: Path to the target image containing the square.
39
+ :param known_size_mm: Physical size of the square in millimeters.
40
+ :param roi_margin: Margin to expand the ROI around the detected square (in pixels).
41
+ :return: Scaling factor (mm per pixel).
42
+ """
43
+ target_image = cv2.cvtColor(target_image, cv2.COLOR_RGB2GRAY)
44
+
45
+ roi = target_image.copy()
46
+ # Find contours in the ROI
47
+ roi_blurred = cv2.GaussianBlur(roi, (5, 5), 0)
48
+ _, roi_binary = cv2.threshold(
49
+ roi_blurred, 128, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
50
+ )
51
+ contours, _ = cv2.findContours(
52
+ roi_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
53
+ )
54
+
55
+ if not contours:
56
+ raise ValueError("No contours found in the cropped ROI.")
57
+
58
+ # Select the largest square-like contour
59
+ largest_square = None
60
+ largest_square_area = 0
61
+ for contour in contours:
62
+ x_c, y_c, w_c, h_c = cv2.boundingRect(contour)
63
+ aspect_ratio = w_c / float(h_c)
64
+ if 0.9 <= aspect_ratio <= 1.1:
65
+ peri = cv2.arcLength(contour, True)
66
+ approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
67
+ if len(approx) == 4:
68
+ area = cv2.contourArea(contour)
69
+ if area > largest_square_area:
70
+ largest_square = contour
71
+ largest_square_area = area
72
+
73
+ if largest_square is None:
74
+ raise ValueError("No square-like contour found in the ROI.")
75
+
76
+ # Draw the largest contour on the original image
77
+ target_image_color = cv2.cvtColor(target_image, cv2.COLOR_GRAY2BGR)
78
+ cv2.drawContours(
79
+ target_image_color, largest_square, -1, (255, 0, 0), 3
80
+ )
81
+
82
+ if self.debug:
83
+ cv2.imwrite("largest_contour.jpg", target_image_color)
84
+
85
+ # Calculate the bounding rectangle of the largest contour
86
+ x, y, w, h = cv2.boundingRect(largest_square)
87
+ square_width_px = w
88
+ square_height_px = h
89
+
90
+ # Calculate the scaling factor
91
+ avg_square_size_px = (square_width_px + square_height_px) / 2
92
+ scaling_factor = known_size_mm / avg_square_size_px # mm per pixel
93
+
94
+ return scaling_factor
95
+
96
+ def draw_debug_images(self, output_folder):
97
+ """
98
+ Save debug images if enabled.
99
+ :param output_folder: Directory to save debug images.
100
+ """
101
+ if self.debug:
102
+ if not os.path.exists(output_folder):
103
+ os.makedirs(output_folder)
104
+ debug_images = ["largest_contour.jpg"]
105
+ for img_name in debug_images:
106
+ if os.path.exists(img_name):
107
+ os.rename(img_name, os.path.join(output_folder, img_name))
108
+
109
+
110
+ def calculate_scaling_factor(
111
+ reference_image_path,
112
+ target_image,
113
+ known_square_size_mm=9.0,
114
+ feature_detector="ORB",
115
+ debug=False,
116
+ roi_margin=30,
117
+ ):
118
+ # Initialize detector
119
+ detector = ScalingSquareDetector(feature_detector=feature_detector, debug=debug)
120
+
121
+ # Find scaling square and calculate scaling factor
122
+ scaling_factor = detector.find_scaling_square(
123
+ reference_image_path=reference_image_path,
124
+ target_image=target_image,
125
+ known_size_mm=known_square_size_mm,
126
+ roi_margin=roi_margin,
127
+ )
128
+
129
+ # Save debug images
130
+ if debug:
131
+ detector.draw_debug_images("debug_outputs")
132
+
133
+ return scaling_factor
134
+
135
+
136
+ # Example usage:
137
+ if __name__ == "__main__":
138
+ import os
139
+ from PIL import Image
140
+ from ultralytics import YOLO
141
+ from app import yolo_detect, shrink_bbox
142
+ from ultralytics.utils.plotting import save_one_box
143
+
144
+ for idx, file in enumerate(os.listdir("./sample_images")):
145
+ img = np.array(Image.open(os.path.join("./sample_images", file)))
146
+ img = yolo_detect(img, ['box'])
147
+ model = YOLO("./runs/detect/train/weights/last.pt")
148
+ res = model.predict(img, conf=0.6)
149
+
150
+ box_img = save_one_box(res[0].cpu().boxes.xyxy, im=res[0].orig_img, save=False)
151
+ img = shrink_bbox(box_img, 1.20)
152
+ cv2.imwrite(f"./outputs/{idx}_{file}", img)
153
+ try:
154
+
155
+ scaling_factor = calculate_scaling_factor(
156
+ reference_image_path="./Reference_ScalingBox.jpg",
157
+ target_image=img,
158
+ known_square_size_mm=9.0,
159
+ feature_detector="ORB",
160
+ debug=False,
161
+ roi_margin=90,
162
+ )
163
+ print(f"Scaling Factor (mm per pixel): {scaling_factor:.6f}")
164
+ except Exception as e:
165
+ from traceback import print_exc
166
+ print(print_exc())
167
+ print(f"Error: {e}")