Skip to content

Instantly share code, notes, and snippets.

@heaven00
Created December 17, 2014 13:10
Show Gist options
  • Save heaven00/f0453fc23e1814f549fe to your computer and use it in GitHub Desktop.
Save heaven00/f0453fc23e1814f549fe to your computer and use it in GitHub Desktop.
SIFT test script
import numpy as np
import cv2
from matplotlib import pyplot as plt
def show_img(img1, img2, p1, p2, status):
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
vis[:h1, :w1] = img1
vis[:h2, w1:w1+w2] = img2
vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
p2 += (w1, 0)
# plot the matches
color = (0, 255, 0)
for (x1, y1), (x2, y2), inlier in zip(p1, p2, status):
if inlier:
cv2.circle(vis, (x1, y1), 2, color, -1)
cv2.circle(vis, (x2, y2), 2, color, -1)
cv2.line(vis, (x1, y1), (x2, y2), color)
plt.imshow(vis)
plt.axis('off')
plt.show()
def main():
"""
execute this function when the script is ran.
"""
sign = cv2.imread('signs_3.png')
img = cv2.imread('a3.jpg')
sign = cv2.cvtColor(sign, cv2.COLOR_BGR2GRAY)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
detector = cv2.SURF()
sign_kp, sign_desc = detector.detectAndCompute(sign, None)
img_kp, img_desc = detector.detectAndCompute(img, None)
matcher = cv2.BFMatcher()
matches = matcher.knnMatch(sign_desc, trainDescriptors=img_desc, k=2)
#filter matches
matches = [(match[0].queryIdx, match[1].trainIdx) for match in matches \
if match[0].distance < match[1].distance * 0.75]
sign_pts = np.float32([sign_kp[match[0]].pt for match in matches])
img_pts = np.float32([img_kp[match[1]].pt for match in matches])
_, status = cv2.findHomography(sign_pts, img_pts, cv2.RANSAC, 5.0)
show_img(sign, img, sign_pts, img_pts, status)
#for all desc matches get the keypoints
if __name__ == "__main__":
main()
@heaven00
Copy link
Author

A note to self do not use SIFT for shape detection, try template matching.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment