LukeJacob2023 commited on
Commit
3f0a18a
·
verified ·
1 Parent(s): fd8d7f1

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +65 -0
  2. requirements.txt +0 -0
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import gradio as gr
4
+
5
+ def sift_ransac_matching(image, template):
6
+ # Convert to grayscale
7
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
8
+ gray_template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
9
+
10
+ # Initialize SIFT detector
11
+ sift = cv2.SIFT_create()
12
+
13
+ # Find the keypoints and descriptors with SIFT
14
+ kp1, des1 = sift.detectAndCompute(gray_image, None)
15
+ kp2, des2 = sift.detectAndCompute(gray_template, None)
16
+
17
+ # BFMatcher with default params
18
+ bf = cv2.BFMatcher()
19
+ matches = bf.knnMatch(des1, des2, k=2)
20
+
21
+ # Apply ratio test
22
+ good_matches = []
23
+ for m, n in matches:
24
+ if m.distance < 0.75 * n.distance:
25
+ good_matches.append(m)
26
+
27
+ if len(good_matches) > 4:
28
+ # Extract location of good matches
29
+ src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
30
+ dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
31
+
32
+ # Use RANSAC to find homography
33
+ M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
34
+
35
+ if M is not None:
36
+ # Compute the match score
37
+ num_matches = np.sum(mask)
38
+ match_score = num_matches / len(good_matches) # Matching score as a ratio
39
+
40
+ # Set a threshold for match score
41
+ threshold = 0.8 # Adjust this threshold as needed
42
+
43
+ # Determine if the template is found based on the match score
44
+ if match_score >= threshold:
45
+ return "Template found"
46
+ else:
47
+ return "Template not found"
48
+ else:
49
+ return "Template not found"
50
+ else:
51
+ return "Not enough good matches are found. Template not found"
52
+
53
+ # Gradio interface
54
+ iface = gr.Interface(
55
+ fn=sift_ransac_matching,
56
+ inputs=[
57
+ gr.Image(type="numpy", label="Image"),
58
+ gr.Image(type="numpy", label="Template"),
59
+ ],
60
+ outputs=gr.Text(label="Result"),
61
+ title="Advanced Template Matching",
62
+ description="Upload an image and a template to check if the template is present in the image using SIFT and RANSAC.",
63
+ )
64
+
65
+ iface.launch()
requirements.txt ADDED
Binary file (2.19 kB). View file