Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import matplotlib.pyplot as plt
- import cv2
- import os
- import urllib2
- import sys
- def load_sample_image(filename):
- response = urllib2.urlopen('https://raw.github.com/Itseez/opencv/master/samples/c/' + filename)
- return cv2.imdecode(np.fromstring(response.read(), dtype='uint8'), 0)
- def show_image(img):
- plt.imshow(img)
- if len(img.shape)<3:
- plt.gray()
- plt.axis("off")
- #plt.show()
- plt.savefig('sss.png', dpi=900)
- img11 = cv2.imread(sys.argv[2]) #load_sample_image('box.png')
- img1 = cv2.cvtColor( img11, cv2.COLOR_RGB2GRAY)
- img22 = cv2.imread(sys.argv[3]) #load_sample_image('box_in_scene.png')
- img2 = cv2.cvtColor( img22, cv2.COLOR_RGB2GRAY)
- print("Read img1 of size {} and img2 of size {}.".format(img1.shape, img2.shape))
- print("Image 1:")
- #show_image(img1)
- print("Image 2:")
- #show_image(img2)
- th = int(sys.argv[1])
- octaves = 7
- oct_layers = 5
- detector = cv2.SURF(th,octaves,oct_layers)
- norm = cv2.NORM_L2
- matcher = cv2.BFMatcher(norm)
- kp1, desc1 = detector.detectAndCompute(img1, None)
- kp2, desc2 = detector.detectAndCompute(img2, None)
- print '%s feature points for image1' % len(kp1)
- print '%s feature points for image2' % len(kp2)
- raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)
- def filter_matches(kp1, kp2, matches, ratio = 0.9):
- """
- Keep only matches that have distance ratio to
- second closest point less than 'ratio'.
- """
- mkp1, mkp2 = [], []
- for m in matches:
- if m[0].distance < m[1].distance * ratio:
- m = m[0]
- mkp1.append( kp1[m.queryIdx] )
- mkp2.append( kp2[m.trainIdx] )
- p1 = np.float32([kp.pt for kp in mkp1])
- p2 = np.float32([kp.pt for kp in mkp2])
- kp_pairs = zip(mkp1, mkp2)
- return p1, p2, kp_pairs
- p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
- H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 40.0)
- h1, w1 = img1.shape[:2]
- h2, w2 = img2.shape[:2]
- vis = np.zeros((max(h1, h2), w1), np.uint8)
- vis[:h1, :w1] = img1
- #vis[:h2, w1:w1+w2] = img2
- vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
- #show_image(vis)
- p1 = np.int32([kpp[0].pt for kpp in kp_pairs])
- p2 = np.int32([kpp[1].pt for kpp in kp_pairs]) #+ (w1, 0)
- # plot the matches
- color = (0, 255, 0)
- ch_valid = 0
- for (x1, y1), (x2, y2), inlier in zip(p1, p2, status):
- if inlier:
- if (abs(x2-x1)>3 or abs(y2-y1)>3):
- cv2.circle(vis, (x1, y1), 2, color, -1)
- #cv2.circle(vis, (x2, y2), 2, color, -1)
- cv2.line(vis, (x1, y1), (x2, y2), color)
- ch_valid = ch_valid + 1
- print '%s number of valid vectors' % ch_valid
- show_image(vis)
Advertisement
Add Comment
Please, Sign In to add comment