繁体   English   中英

透视变换图像片段并变换回

[英]perspective transform image segment and transform back

我目前正在尝试从图像中切出感兴趣的区域,根据片段中的信息进行一些计算,然后将片段转换回原始 position 或将片段上完成的计算中的一些坐标转换回原始图像。

以下是一些代码片段:

    x, y, w, h = cv2.boundingRect(localized_mask)

    p1 = [x, y + h]
    p4 = [x, y]
    p3 = [x + w, y]
    p2 = [x + w, y + h]

    w1 = int(np.linalg.norm(np.array(p2) - np.array(p3)))
    w2 = int(np.linalg.norm(np.array(p4) - np.array(p1)))
    h1 = int(np.linalg.norm(np.array(p1) - np.array(p2)))
    h2 = int(np.linalg.norm(np.array(p3) - np.array(p4)))

    maxWidth = max(w1, w2)
    maxHeight = max(h1, h2)

    neighbor_points = [p1, p2, p3, p4]
    output_poins = np.float32(
        [
            [0, 0],
            [0, maxHeight],
            [maxWidth, maxHeight],
            [maxWidth, 0],
        ]
    )

    matrix = cv2.getPerspectiveTransform(np.float32(neighbor_points), output_poins)
    result = cv2.warpPerspective(
        mask, matrix, (maxWidth, maxHeight), cv2.INTER_LINEAR
    )

    

这里有一些图片来说明这个问题:

带有标记RoI的原始文件:

带有标记投资回报率的原始文件

带有标记的转换片段:

带有标记的转换片段

我尝试使用以下代码片段将片段转换回原始 position:

    test2 = cv2.warpPerspective(
        result, matrix, (maxHeight, maxWidth), cv2.WARP_INVERSE_MAP
    )
    test3 = cv2.warpPerspective(
        result, matrix, (img.shape[1], img.shape[0]), cv2.WARP_INVERSE_MAP
    )

两者都产生了具有片段形状的黑色图像或具有原始图像形状的黑色图像。

但老实说,我对代码片段中的白色标记更感兴趣,所以我尝试使用以下代码片段手动转换它们:

    inverse_matrix = cv2.invert(matrix)[1]
    inverse_left=[]
    for point in output_dict["left"]["knots"]:
        trans_point = [point.x, point.y] + [1]
        trans_point = np.float32(trans_point)

        x, y, z = np.dot(inverse_matrix, trans_point)
        new_x = np.uint8(x/z)
        new_y = np.uint8(y/z)
        inverse_left.append([new_x, new_y])       

但是我没有考虑到图像内 RoI 的RoI和结果坐标(左上半部分的白点)并没有出现在我想要的位置。

在此处输入图像描述

有没有人知道我做错了什么或知道这个问题的更好解决方案? 谢谢。

终于找到了一个解决方案,它就像我想象的那样简单......

我首先反转了用于获取图像片段的转换矩阵,然后循环并转换了基于片段的计算得出的每个坐标。

代码看起来像这样:

inv_matrix = cv2.invert(matrix)
for point in points:
   x, y = (cv2.transform(np.array([[[point.x, point.y]]]), inv_matrix[1]).squeeze())[:2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM