使用OpenCV实现图像匹配拼接后获取图像角点坐标的方法
解决拼接图像角点坐标获取问题
你当前代码的核心问题是错误定义了原图像的角点,使用了负坐标[[0,0],[0,-1],[-1,-1],[-1,0]],这并非图像的实际顶点,导致无法得到正确的拼接后坐标。以下是修正后的实现:
修正代码
matchess = np.asarray(good) if len(good) > 500: # 筛选足够数量的优质匹配对 src_pts = np.float32([kp1[m.queryIdx].pt for m in matchess[:,0] ]).reshape(-1,1,2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in matchess[:,0] ]).reshape(-1,1,2) H, masked = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) # 获取img1的四个实际顶点(原图像坐标系) h1, w1 = img1.shape[:2] img1_corners = np.float32([ [0, 0], # 左上角 [w1 - 1, 0], # 右上角 [w1 - 1, h1 - 1],# 右下角 [0, h1 - 1] # 左下角 ]).reshape(-1, 1, 2) # 将img1的角点通过单应矩阵转换到拼接后的图像坐标系 transformed_corners = cv2.perspectiveTransform(img1_corners, H) # 执行图像拼接 stitched_img_size = (img2.shape[1] + img1.shape[1], img2.shape[0]) warped_img1 = cv2.warpPerspective(img1, H, stitched_img_size) warped_img1[0:img2.shape[0], 0:img2.shape[1]] = img2 # 输出拼接后img1的角点坐标 print("拼接后img1的角点坐标:") for i, corner in enumerate(transformed_corners): x, y = corner[0][0], corner[0][1] print(f"角点{i+1}: ({round(x, 2)}, {round(y, 2)})")
关键说明
- 正确提取原图像角点:使用
img1.shape获取图像的宽高,生成真实的四个顶点坐标,这是坐标转换的基础 - 单应矩阵的作用:
cv2.perspectiveTransform通过单应矩阵H,将img1的角点从自身坐标系映射到拼接后的大图像坐标系中 - 坐标对应关系:
transformed_corners中的每个坐标,直接对应拼接后图像warped_img1中img1区域的四个角点位置
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

