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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
def ransac(image1, image2, detector_type):
|
| 10 |
+
"""
|
| 11 |
+
Finds the homography matrix using the RANSAC algorithm with the selected feature detector.
|
| 12 |
+
"""
|
| 13 |
+
gray1 = cv2.cvtColor(image1, cv2.COLOR_RGB2GRAY)
|
| 14 |
+
gray2 = cv2.cvtColor(image2, cv2.COLOR_RGB2GRAY)
|
| 15 |
+
|
| 16 |
+
if detector_type == "SIFT":
|
| 17 |
+
detector = cv2.SIFT_create()
|
| 18 |
+
matcher = cv2.FlannBasedMatcher(dict(algorithm=1, trees=5), dict(checks=50))
|
| 19 |
+
elif detector_type == "ORB":
|
| 20 |
+
detector = cv2.ORB_create()
|
| 21 |
+
matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
|
| 22 |
+
elif detector_type == "BRISK":
|
| 23 |
+
detector = cv2.BRISK_create()
|
| 24 |
+
matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
|
| 25 |
+
elif detector_type == "AKAZE":
|
| 26 |
+
detector = cv2.AKAZE_create()
|
| 27 |
+
matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
|
| 28 |
+
elif detector_type == "KAZE":
|
| 29 |
+
detector = cv2.KAZE_create()
|
| 30 |
+
matcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
|
| 31 |
+
else:
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
kp1, des1 = detector.detectAndCompute(gray1, None)
|
| 35 |
+
kp2, des2 = detector.detectAndCompute(gray2, None)
|
| 36 |
+
|
| 37 |
+
if des1 is None or des2 is None or len(kp1) < 2 or len(kp2) < 2:
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
if detector_type == "SIFT":
|
| 42 |
+
matches = matcher.knnMatch(des1, des2, k=2)
|
| 43 |
+
good_matches = []
|
| 44 |
+
if matches:
|
| 45 |
+
for m, n in matches:
|
| 46 |
+
if m.distance < 0.75 * n.distance:
|
| 47 |
+
good_matches.append(m)
|
| 48 |
+
else:
|
| 49 |
+
matches = matcher.match(des1, des2)
|
| 50 |
+
good_matches = sorted(matches, key=lambda x: x.distance)
|
| 51 |
+
except cv2.error as e:
|
| 52 |
+
print(f"Error during matching: {e}")
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
if len(good_matches) > 10:
|
| 56 |
+
src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
|
| 57 |
+
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
|
| 58 |
+
H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
|
| 59 |
+
return H
|
| 60 |
+
else:
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
def get_bounding_box_points(json_data):
|
| 64 |
+
"""
|
| 65 |
+
Extracts and calculates the four corner points of the bounding box, assuming x,y are top-left.
|
| 66 |
+
"""
|
| 67 |
+
print_area = json_data['printAreas'][0]
|
| 68 |
+
x = print_area['position']['x']
|
| 69 |
+
y = print_area['position']['y']
|
| 70 |
+
w = print_area['width']
|
| 71 |
+
h = print_area['height']
|
| 72 |
+
rotation_deg = print_area['rotation']
|
| 73 |
+
|
| 74 |
+
points = np.float32([
|
| 75 |
+
[0, 0],
|
| 76 |
+
[w, 0],
|
| 77 |
+
[w, h],
|
| 78 |
+
[0, h]
|
| 79 |
+
]).reshape(-1, 1, 2)
|
| 80 |
+
|
| 81 |
+
rotation_rad = math.radians(rotation_deg)
|
| 82 |
+
cos_theta = math.cos(rotation_rad)
|
| 83 |
+
sin_theta = math.sin(rotation_rad)
|
| 84 |
+
rotation_matrix = np.array([
|
| 85 |
+
[cos_theta, -sin_theta],
|
| 86 |
+
[sin_theta, cos_theta]
|
| 87 |
+
])
|
| 88 |
+
|
| 89 |
+
rotated_points = np.dot(points.reshape(-1, 2), rotation_matrix.T)
|
| 90 |
+
final_points = rotated_points + np.array([x, y])
|
| 91 |
+
return final_points.reshape(-1, 1, 2)
|
| 92 |
+
|
| 93 |
+
def process_and_plot_all_detectors(image1_np, image2_np, json_file):
|
| 94 |
+
"""
|
| 95 |
+
Processes the images with all available detectors and returns image data for display and download.
|
| 96 |
+
"""
|
| 97 |
+
if image1_np is None or image2_np is None:
|
| 98 |
+
return [None] * 6
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
with open(json_file.name, 'r') as f:
|
| 102 |
+
data = json.load(f)
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(f"Error: Could not read JSON file. {e}")
|
| 105 |
+
return [None] * 6
|
| 106 |
+
|
| 107 |
+
detectors = ["SIFT", "ORB", "BRISK", "AKAZE", "KAZE"]
|
| 108 |
+
gallery_images = []
|
| 109 |
+
download_files = [None] * 5
|
| 110 |
+
|
| 111 |
+
for i, detector_type in enumerate(detectors):
|
| 112 |
+
H = ransac(image1_np, image2_np, detector_type)
|
| 113 |
+
|
| 114 |
+
if H is not None:
|
| 115 |
+
box_points = get_bounding_box_points(data)
|
| 116 |
+
|
| 117 |
+
output_flat_img = image1_np.copy()
|
| 118 |
+
cv2.polylines(output_flat_img, [np.int32(box_points)], isClosed=True, color=(0, 0, 255), thickness=5)
|
| 119 |
+
|
| 120 |
+
transformed_box_points = cv2.perspectiveTransform(box_points, H)
|
| 121 |
+
|
| 122 |
+
output_perspective_img = image2_np.copy()
|
| 123 |
+
cv2.polylines(output_perspective_img, [np.int32(transformed_box_points)], isClosed=True, color=(0, 0, 255), thickness=5)
|
| 124 |
+
|
| 125 |
+
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
|
| 126 |
+
axes[0].imshow(cv2.cvtColor(output_flat_img, cv2.COLOR_BGR2RGB))
|
| 127 |
+
axes[0].set_title(f'Original (Flat) - {detector_type}')
|
| 128 |
+
axes[0].axis('off')
|
| 129 |
+
|
| 130 |
+
axes[1].imshow(cv2.cvtColor(image2_np, cv2.COLOR_BGR2RGB))
|
| 131 |
+
axes[1].set_title('Original (Perspective)')
|
| 132 |
+
axes[1].axis('off')
|
| 133 |
+
|
| 134 |
+
axes[2].imshow(cv2.cvtColor(output_perspective_img, cv2.COLOR_BGR2RGB))
|
| 135 |
+
axes[2].set_title('Projected Bounding Box')
|
| 136 |
+
axes[2].axis('off')
|
| 137 |
+
|
| 138 |
+
plt.tight_layout()
|
| 139 |
+
|
| 140 |
+
file_name = f"result_{detector_type.lower()}.png"
|
| 141 |
+
plt.savefig(file_name)
|
| 142 |
+
plt.close(fig)
|
| 143 |
+
|
| 144 |
+
gallery_images.append(file_name)
|
| 145 |
+
download_files[i] = file_name
|
| 146 |
+
else:
|
| 147 |
+
print(f"Warning: Homography matrix could not be found with {detector_type} detector. Skipping this result.")
|
| 148 |
+
# We don't append None to the gallery_images list to avoid the error.
|
| 149 |
+
# download_files[i] remains None, which is handled correctly by gr.File.
|
| 150 |
+
|
| 151 |
+
return [gallery_images] + download_files
|
| 152 |
+
|
| 153 |
+
iface = gr.Interface(
|
| 154 |
+
fn=process_and_plot_all_detectors,
|
| 155 |
+
inputs=[
|
| 156 |
+
gr.Image(type="numpy", label="Image 1 (Flat)"),
|
| 157 |
+
gr.Image(type="numpy", label="Image 2 (Perspective)"),
|
| 158 |
+
gr.File(type="filepath", label="JSON File")
|
| 159 |
+
],
|
| 160 |
+
outputs=[
|
| 161 |
+
gr.Gallery(label="Results"),
|
| 162 |
+
gr.File(label="Download SIFT Result"),
|
| 163 |
+
gr.File(label="Download ORB Result"),
|
| 164 |
+
gr.File(label="Download BRISK Result"),
|
| 165 |
+
gr.File(label="Download AKAZE Result"),
|
| 166 |
+
gr.File(label="Download KAZE Result")
|
| 167 |
+
],
|
| 168 |
+
title="Homography and Bounding Box Projection with All Detectors",
|
| 169 |
+
description="Upload two images and a JSON file to see the bounding box projection for all 5 feature extraction methods. Each result can be downloaded separately."
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
iface.launch()
|
requirements(2).txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
opencv-python
|
| 3 |
+
numpy
|
| 4 |
+
matplotlib
|