You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV透视变换未达预期输出问题求助

OpenCV透视变换坐标不匹配问题

问题背景

我尝试用OpenCV执行透视变换,期望将new_doc_coords对应的区域变换为new_box_coords定义的矩形区域,但实际变换后计算得到的坐标与预期不符。

代码及数据

new_doc_coords = [[  72  477]
                  [ 544  477]
                  [  93 1163]
                  [ 532 1177]]

new_box_coords = [[  72  477]
                  [ 544  477]
                  [  72 1163]
                  [ 544 1163]]

# 透视变换
resmatrix = cv2.getPerspectiveTransform(np.float32(new_doc_coords), np.float32(new_box_coords))
trans_bgr_img = cv2.warpPerspective(rotated_bgr_img, resmatrix, (rotated_bgr_img.shape[1], rotated_bgr_img.shape[0]), cv2.INTER_CUBIC)

# 计算变换后的new_doc_coords
doc_coords_aug = np.hstack((new_doc_coords, np.ones((new_doc_coords.shape[0], 1))))
new_doc_coords = rot_mat.dot(doc_coords_aug.T).T.astype(int)
top_left, top_right, bottom_left, bottom_right = sort_points(new_doc_coords)
print(sort_points(new_doc_coords))

# 实际输出结果
[[  72  469]
 [ 543  484]
 [  71 1155]
 [ 509 1183]]

问题核心

按照透视变换逻辑,变换后sort_points(new_doc_coords)应与new_box_coords完全一致,但实际输出存在明显偏差。已更换多种插值方法,问题仍未解决。

已尝试操作

  • 更换不同插值方法(如INTER_CUBIC、INTER_LINEAR等)

预期结果

sort_points(new_doc_coords)的内容与new_box_coords完全匹配


解决方案

  1. 修正坐标点对应顺序
    cv2.getPerspectiveTransform要求源坐标与目标坐标必须严格一一对应(例如均按左上、右上、左下、右下的顺序排列)。检查你的new_doc_coords点顺序是否和new_box_coords完全匹配,顺序混乱会直接导致变换矩阵计算错误。

  2. 避免整数截断误差
    你在计算时用.astype(int)强制转换为整数,丢失了透视变换的浮点精度。应保留浮点类型至最终输出阶段,再按需取整。

  3. 用正确的变换矩阵验证坐标
    你当前用rot_mat计算变换后坐标是错误的,必须使用透视变换生成的resmatrix,且要做齐次坐标归一化:

    # 用透视变换矩阵resmatrix计算变换后的坐标
    doc_coords_aug = np.hstack((np.float32(new_doc_coords), np.ones((4, 1))))
    transformed_coords = resmatrix.dot(doc_coords_aug.T).T
    # 齐次坐标归一化(关键步骤)
    transformed_coords = transformed_coords[:, :2] / transformed_coords[:, 2:3]
    print(sort_points(transformed_coords.astype(int)))
    
  4. 调整warpPerspective输出尺寸
    warpPerspective的输出尺寸应匹配目标矩形的大小,而非原图像尺寸。目标矩形的尺寸可通过new_box_coords计算:

    target_width = new_box_coords[1][0] - new_box_coords[0][0]
    target_height = new_box_coords[2][1] - new_box_coords[0][1]
    trans_bgr_img = cv2.warpPerspective(rotated_bgr_img, resmatrix, (target_width, target_height), cv2.INTER_CUBIC)
    

内容的提问来源于stack exchange,提问作者John Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:03:36