图片对比
import cv2 as cv
import numpy as np
def display_img(img):
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()
def double_img(file1,file2):
img1 = cv.imread(file1)
img2 = cv.imread(file2)
res = np.hstack((img1,img2))
display_img(res)
double_img("left_01.png","right_01.png")
全景图片拼接
import cv2
import numpy as np
import matplotlib.pyplot as plt
def display_img(img):
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def matchKeypoints(kpsA,kpsB,featuresA,featuresB,ratio,reth):
matcher = cv2.BFMatcher()
rawMatchers = matcher.knnMatch(featuresA,featuresB,2)
matchers =[]
for m in rawMatchers:
if (len(m)==2 and m[0].distance<m[1].distance*ratio):
matchers.append((m[0].trainIdx,m[0].queryIdx))
if len(matchers)>4:
ptsA = np.float32([kpsA[i] for (_,i) in matchers])
ptsB = np.float32([kpsB[i] for (i,_) in matchers])
H,status = cv2.findHomography(ptsA,ptsB,cv2.RANSAC,reth)
return matchers,H,status
return None
def detectAndDescribe(img):
sift = cv2.xfeatures2d.SIFT_create()
kps,des = sift.detectAndCompute(img,None)
kps = np.float32([kp.pt for kp in kps])
return kps,des
def drawMatches(imageA, imageB, kpsA, kpsB, matches, status):
(hA, wA) = imageA.shape[:2]
(hB, wB) = imageB.shape[:2]
vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
vis[0:hA, 0:wA] = imageA
vis[0:hB, wA:] = imageB
for ((trainIdx, queryIdx), s) in zip(matches, status):
if s == 1:
ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
cv2.line(vis, ptA, ptB, (0, 255, 0), 1)
return vis
def stitch(imageA,imageB, ratio=0.75, reprojThresh=4.0,showMatches=False):
(kpsA, featuresA) = detectAndDescribe(imageA)
(kpsB, featuresB) = detectAndDescribe(imageB)
M = matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh)
if M is None:
return None
matchers, H, status = M
result = cv2.warpPerspective(imageA, H, (imageA.shape[1] + imageB.shape[1], imageA.shape[0]))
result[0:imageB.shape[0], 0:imageB.shape[1]] = imageB
if showMatches:
vis = drawMatches(imageA, imageB, kpsA, kpsB, matchers, status)
return (result, vis)
return result
def operate_img(file1,file2):
img1 = cv2.imread(file1)
img2 = cv2.imread(file2)
result, vis =stitch(img2,img1, showMatches=True)
display_img(result)
display_img(vis)
def main():
f1,f2 ="left_01.png","right_01.png"
operate_img(f1,f2)
main()
效果
素材