import cv2import numpy as np# 读取大图和小图large_image = cv2imreadIMGphone4png #图形都是24位small_image = cv2imreadrCUsersAdministratorDesktop6png #图形都是24位small_image = cv2resizesmall_image large_imageshape1 lar
可以尝试使用cv2.warpPerspective函数来进行透视变换,并绘制正确的边框形状和位置。以下是修改后的代码:
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)
绘制正确的边框形状和位置
large_image = cv2.polylines(large_image, [np.int32(dst)], True, (0, 255, 0), 2, cv2.LINE_AA)
显示结果
cv2.imshow('Result', large_image) cv2.waitKey(0) cv2.destroyAllWindows()
原文地址: https://www.cveoy.top/t/topic/i7Sv 著作权归作者所有。请勿转载和采集!