import matplotlib.pyplot as plt import numpy as np import cv2 img1 = cv2.imread(r"images/contract_left.png") img1 = cv2.cvtColor(img1,cv2.COLOR_BGR2RGB) img2 = cv2.imread(r"images/contract_right.png") img2 = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB) fig = plt.figure(figsize=(18,18)) a = fig.add_subplot(1,2,1) imgplot = plt.imshow(img1) a.set_title("11") a = fig.add_subplot(1,2,2) imgplot = plt.imshow(img2) a.set_title("12") def detectAndDesc(img): img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) descripter = cv2.SIFT_create() kps,desc = descripter.detectAndCompute(img,None) kps = np.float32([kp.pt for kp in kps]) return kps,desc def matchKeyPoints(kp1,des1,kp2,des2,ratio=0.75,reprojThresh=4.0): matcher = cv2.BFMatcher() rawMatches = matcher.knnMatch(des1,des2,k=2) matches = [] for n in rawMatches: if len(n)==2 and n[0].distance< n[1].distance*ratio: matches.append((n[0].trainIdx,n[0].queryIdx)) if len(matches)>4: p1 = np.float32([kp1[i] for (_,i) in matches]) p2 = np.float32([kp2[i] for (i,_) in matches]) H,status = cv2.findHomography(p1,p2,cv2.RANSAC,reprojThresh) return matches,H,status else: return None,None,False kp1,des1 = detectAndDesc(img1) kp2,des2 = detectAndDesc(img2) ratio = 0.75 reprojThresh = 4.0 matches,H,status = matchKeyPoints(kp1,des1,kp2,des2,ratio,reprojThresh) result = cv2.warpPerspective(img1,H,(img1.shape[1]+img2.shape[1],img1.shape[0])) fig = plt.figure(figsize=(18,18)) a = fig.add_subplot(2,1,1) imgplot = plt.imshow(result) a.set_title("11") result[0:img2.shape[0],0:img2.shape[1]]=img2 a = fig.add_subplot(2,1,2) imgplot = plt.imshow(result) a.set_title("12")
|