import cv2 import numpy as np

读取大图和小图

large_image = cv2.imread('IMG/phone4.png') small_image = cv2.imread(r'C:\Users\Administrator\Desktop/6.png') small_image = cv2.resize(small_image, (large_image.shape[1], large_image.shape[0]))

orb = cv2.ORB_create()

在大图中检测特征点和描述符

kp1, des1 = orb.detectAndCompute(large_image, None)

在小图中检测特征点和描述符

kp2, des2 = orb.detectAndCompute(small_image, None)

bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

特征匹配

matches = bf.match(des1, des2)

根据距离进行排序

matches = sorted(matches, key=lambda x: x.distance)

选择前n个最佳匹配

n = 10 best_matches = matches[:n]

获取最佳匹配的特征点坐标

src_pts = np.float32([kp1[m.queryIdx].pt for m in best_matches]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in best_matches]).reshape(-1, 1, 2)

计算透视变换矩阵

M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

获取小图的宽度和高度

h, w = small_image.shape[:2]

定义小图的四个角点坐标

pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2)

通过透视变换将小图的四个角点映射到大图中

dst = cv2.perspectiveTransform(pts, M)

使用 cv2.warpPerspective 函数进行透视变换,并绘制正确的边框形状和位置

warped_image = cv2.warpPerspective(small_image, M, (large_image.shape[1], large_image.shape[0])) large_image = cv2.addWeighted(large_image, 1, warped_image, 0.5, 0)

显示结果

cv2.imshow('Result', large_image) cv2.waitKey(0) cv2.destroyAllWindows()

OpenCV 图像匹配与透视变换:使用 ORB 和 cv2.warpPerspective 实现精准边框绘制

原文地址: https://www.cveoy.top/t/topic/lTHN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录