ferozakbar commited on
Commit
d2cca91
·
1 Parent(s): 8d5c9df

refraction

Browse files
Files changed (1) hide show
  1. app.py +31 -20
app.py CHANGED
@@ -47,11 +47,11 @@ def postprocess(preds, r, pad, orig_shape, conf_thres=0.25, iou_thres=0.45):
47
  yc = (y_center - pad_y) / r
48
  bw = w / r
49
  bh = h / r
50
- x1 = max(0, xc - bw/2)
51
- y1 = max(0, yc - bh/2)
52
- x2 = min(orig_w, xc + bw/2)
53
- y2 = min(orig_h, yc + bh/2)
54
- boxes.append([int(x1), int(y1), int(x2-x1), int(y2-y1)])
55
  scores.append(float(conf))
56
 
57
  idxs = cv2.dnn.NMSBoxes(boxes, scores, conf_thres, iou_thres)
@@ -60,20 +60,33 @@ def postprocess(preds, r, pad, orig_shape, conf_thres=0.25, iou_thres=0.45):
60
  boxes = [boxes[i] for i in idxs]
61
  return boxes
62
 
63
- # 4. Refine each AABB into a rotated parallelogram using contours + minAreaRect
64
- def refine_boxes(img, boxes):
 
 
 
65
  refined = []
66
  for x, y, w, h in boxes:
67
  crop = img[y:y+h, x:x+w]
68
  gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
69
- blur = cv2.GaussianBlur(gray, (5,5), 0)
70
- edges = cv2.Canny(blur, 50, 150)
71
- contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 
 
 
72
  if not contours:
73
  continue
74
  cnt = max(contours, key=cv2.contourArea)
75
- rect = cv2.minAreaRect(cnt)
76
- pts = cv2.boxPoints(rect).astype(np.float32)
 
 
 
 
 
 
 
77
  pts += np.array([x, y], dtype=np.float32)
78
  refined.append(pts)
79
  return refined
@@ -82,13 +95,12 @@ def refine_boxes(img, boxes):
82
  def overlay_logo_perspective(img, quads, fallback_boxes=None):
83
  out = img.copy()
84
  h_logo, w_logo = logo.shape[:2]
85
- # Define source pts of logo corners
86
- src = np.array([[0,0], [w_logo,0], [w_logo,h_logo], [0,h_logo]], dtype=np.float32)
87
 
88
- # Use fallback axis-aligned boxes if no quads found
89
  if not quads and fallback_boxes:
90
  for x, y, w, h in fallback_boxes:
91
- quad = np.array([[x,y], [x+w,y], [x+w,y+h], [x,y+h]], dtype=np.float32)
92
  quads.append(quad)
93
 
94
  for quad in quads:
@@ -102,7 +114,7 @@ def overlay_logo_perspective(img, quads, fallback_boxes=None):
102
  else:
103
  mask = warped[..., :3].sum(axis=2) > 0
104
  for c in range(3):
105
- out[:, :, c][mask] = warped[:, :, c][mask]
106
  return out
107
 
108
  # Helper to load image from URL
@@ -112,7 +124,7 @@ def load_image_from_url(url):
112
  return np.array(img_pil)[..., ::-1]
113
 
114
  # 6. Combined pipeline: detect → refine → overlay
115
- def detect_and_overlay(uploaded_image, url):
116
  if uploaded_image is not None:
117
  img_bgr = uploaded_image[..., ::-1]
118
  elif url:
@@ -130,7 +142,6 @@ def detect_and_overlay(uploaded_image, url):
130
  # 7. Gradio UI with preloaded examples
131
  def main():
132
  image_input = gr.Image(type="numpy", label="Upload Image")
133
- # url_input = gr.Textbox(label="(OR) Image URL")
134
  examples = [
135
  ["test/1.jpg", ""],
136
  ["test/2.jpg", ""],
@@ -146,7 +157,7 @@ def main():
146
  outputs=gr.Image(type="numpy", label="Output Image"),
147
  examples=examples,
148
  title="Fenix - License Plate Logo",
149
- description="Upload or click a thumbnail",
150
  allow_flagging="never"
151
  )
152
  iface.launch(share=True)
 
47
  yc = (y_center - pad_y) / r
48
  bw = w / r
49
  bh = h / r
50
+ x1 = max(0, int(xc - bw/2))
51
+ y1 = max(0, int(yc - bh/2))
52
+ w_box = min(orig_w, int(bw))
53
+ h_box = min(orig_h, int(bh))
54
+ boxes.append([x1, y1, w_box, h_box])
55
  scores.append(float(conf))
56
 
57
  idxs = cv2.dnn.NMSBoxes(boxes, scores, conf_thres, iou_thres)
 
60
  boxes = [boxes[i] for i in idxs]
61
  return boxes
62
 
63
+ # 4. Refine each AABB into exact quadrilaterals
64
+ def refine_boxes(img, boxes):
65
+ """
66
+ Refine axis-aligned boxes into exact quadrilaterals using contour approximation.
67
+ """
68
  refined = []
69
  for x, y, w, h in boxes:
70
  crop = img[y:y+h, x:x+w]
71
  gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
72
+ # Use Otsu's thresholding
73
+ _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
74
+ # Close small gaps
75
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
76
+ closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
77
+ contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
78
  if not contours:
79
  continue
80
  cnt = max(contours, key=cv2.contourArea)
81
+ # Approximate to polygon
82
+ epsilon = 0.02 * cv2.arcLength(cnt, True)
83
+ approx = cv2.approxPolyDP(cnt, epsilon, True)
84
+ if len(approx) == 4:
85
+ pts = approx[:, 0, :].astype(np.float32)
86
+ else:
87
+ rect = cv2.minAreaRect(cnt)
88
+ pts = cv2.boxPoints(rect)
89
+ # Shift to full image coords
90
  pts += np.array([x, y], dtype=np.float32)
91
  refined.append(pts)
92
  return refined
 
95
  def overlay_logo_perspective(img, quads, fallback_boxes=None):
96
  out = img.copy()
97
  h_logo, w_logo = logo.shape[:2]
98
+ src = np.array([[0, 0], [w_logo, 0], [w_logo, h_logo], [0, h_logo]], dtype=np.float32)
 
99
 
100
+ # Fallback if no quads detected
101
  if not quads and fallback_boxes:
102
  for x, y, w, h in fallback_boxes:
103
+ quad = np.array([[x, y], [x+w, y], [x+w, y+h], [x, y+h]], dtype=np.float32)
104
  quads.append(quad)
105
 
106
  for quad in quads:
 
114
  else:
115
  mask = warped[..., :3].sum(axis=2) > 0
116
  for c in range(3):
117
+ out[..., c][mask] = warped[..., c][mask]
118
  return out
119
 
120
  # Helper to load image from URL
 
124
  return np.array(img_pil)[..., ::-1]
125
 
126
  # 6. Combined pipeline: detect → refine → overlay
127
+ def detect_and_overlay(uploaded_image, url):
128
  if uploaded_image is not None:
129
  img_bgr = uploaded_image[..., ::-1]
130
  elif url:
 
142
  # 7. Gradio UI with preloaded examples
143
  def main():
144
  image_input = gr.Image(type="numpy", label="Upload Image")
 
145
  examples = [
146
  ["test/1.jpg", ""],
147
  ["test/2.jpg", ""],
 
157
  outputs=gr.Image(type="numpy", label="Output Image"),
158
  examples=examples,
159
  title="Fenix - License Plate Logo",
160
+ description="Upload or click a thumbnail",
161
  allow_flagging="never"
162
  )
163
  iface.launch(share=True)