Python OpenCV用translation matrix将小图坐标映射到大图指定位置
OpenCV Python 实现小图按坐标映射插入大图(支持旋转等变换)
核心逻辑
你提供的多组<小图像素坐标, 大图像素坐标>点对可以用来计算单应性变换矩阵(Homography Matrix),该矩阵支持平移、旋转、缩放、透视变形等所有平面变换能力,通过矩阵把小图全量像素映射到大图坐标系后,按掩码填充即可完成需求。
完整可运行代码
import cv2 import numpy as np def insert_small_to_big(big_img, small_img, src_pts, dst_pts, pre_h_matrix=None): """ 小图按坐标映射插入大图 :param big_img: 大图对象,cv2.imread读取的numpy数组 :param small_img: 小图对象,cv2.imread读取的numpy数组 :param src_pts: 小图上的坐标点列表,格式[[x1,y1],[x2,y2],...] :param dst_pts: 大图上的对应坐标点列表,顺序和src_pts一一对应 :param pre_h_matrix: 可选参数,提前计算好的变换矩阵,传入则跳过点对计算步骤 :return: 插入完成的大图 """ # 优先使用传入的变换矩阵,没有则用点对计算 if pre_h_matrix is None: src = np.array(src_pts, dtype=np.float32) dst = np.array(dst_pts, dtype=np.float32) h_matrix, _ = cv2.findHomography(src, dst) else: h_matrix = pre_h_matrix h_big, w_big = big_img.shape[:2] # 把小图变换到大图坐标系 warped_small = cv2.warpPerspective(small_img, h_matrix, (w_big, h_big)) # 生成掩码,仅保留小图有效区域 mask = cv2.warpPerspective(np.ones(small_img.shape[:2], dtype=np.uint8)*255, h_matrix, (w_big, h_big)) # 替换大图对应区域 result = big_img.copy() result[mask>0] = warped_small[mask>0] return result # 示例调用 if __name__ == "__main__": # 读取本地图像 big = cv2.imread("your_big_image.jpg") small = cv2.imread("your_small_image.png") # 你的示例坐标点对 src_points = [[75, 120], [30, 90], [56, 102], [110, 98]] dst_points = [[210, 320], [190, 305], [250, 474], [330, 520]] output = insert_small_to_big(big, small, src_points, dst_points) # 保存结果 cv2.imwrite("output.jpg", output)
关键说明
- 点对要求:单应性矩阵计算至少需要4组不共线的对应点对,你给出的示例刚好满足要求,点对数量越多变换精度越高
- 变换支持:支持任意平面变换,包括你需要的旋转、平移、缩放、透视变形等
- 无侵入:通过掩码实现区域替换,不会修改大图中小图映射范围外的内容
- 自定义矩阵支持:如果你已经提前准备好了变换矩阵,直接传入
pre_h_matrix参数即可,不需要输入点对
内容的提问来源于stack exchange,提问作者mahshid a.j
相关产品推荐
相关产品推荐

