def rectify_image(img1, img2):标签:src,plt,dst,内参,opencv,rectified,img1,pts,极线 From: https://www.cnblogs.com/xmyingg/p/18082432
# 初始化SIFT检测器
sift = cv2.SIFT_create()
# 检测关键点和计算描述符
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# 使用FLANN匹配器进行特征点匹配
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# 选择良好的匹配点
src_pts = []
dst_pts = []
# ratio test as per Lowe's paper
for i, (m, n) in enumerate(matches):
if m.distance < 0.8 * n.distance:
dst_pts.append(kp2[m.trainIdx].pt)
src_pts.append(kp1[m.queryIdx].pt)
src_pts = np.int32(src_pts)
dst_pts = np.int32(dst_pts)
F, mask = cv2.findFundamentalMat(src_pts, dst_pts, cv2.FM_LMEDS)
# We select only inlier points
src_pts = src_pts[mask.ravel() == 1]
dst_pts = dst_pts[mask.ravel() == 1]
# # 计算极线
# img11 = img1
# img22 = img2
# # Find epilines corresponding to points in right image (second image) and
# # drawing its lines on left image
# lines1 = cv2.computeCorrespondEpilines(dst_pts.reshape(-1, 1, 2), 2, F)
# lines1 = lines1.reshape(-1, 3)
# img5, img6 = drawlines(img11, img22, lines1, src_pts, dst_pts)
# # Find epilines corresponding to points in left image (first image) and
# # drawing its lines on right image
# lines2 = cv2.computeCorrespondEpilines(src_pts.reshape(-1, 1, 2), 1, F)
# lines2 = lines2.reshape(-1, 3)
# img3, img4 = drawlines(img22, img11, lines2, dst_pts, src_pts)
# plt.subplot(121), plt.imshow(img5)
# plt.subplot(122), plt.imshow(img3)
# plt.show()
# 极线校正
rectified_results = cv2.stereoRectifyUncalibrated(
src_pts.reshape(-1, 2), dst_pts.reshape(-1, 2), F, img1.shape[:2]
)
rectified_img1 = rectified_results[1]
rectified_img2 = rectified_results[2]
rectified_img1 = cv2.warpPerspective(img1, rectified_img1, img1.shape[:2][::-1])
rectified_img2 = cv2.warpPerspective(img2, rectified_img2, img2.shape[:2][::-1])
plt.subplot(121), plt.imshow(rectified_img1)
plt.subplot(122), plt.imshow(rectified_img2)
plt.show()