简体   繁体   English

OpenCV Perspective Transform给出了意想不到的结果

[英]OpenCV Perspective Transform giving unexpected result

I am trying to transform from a trapezoid (in the first image) to a rectangle (in the second image), but getting a strange result (in the third image). 我试图从梯形(在第一个图像中)转换为矩形(在第二个图像中),但得到一个奇怪的结果(在第三个图像中)。

在此输入图像描述

My plan was to use a perspective transform, defined by the four corner points of the trapezoid and the four corner points of the rectangle. 我的计划是使用透视变换,由梯形的四个角点和矩形的四个角点定义。

In this example, for the trapezoid they are: 在这个例子中,对于梯形,它们是:

ptsTrap = [[  50.          100.        ]
           [  50.          200.        ]
           [ 250.           64.73460388]
           [ 250.          235.26539612]]

and for the rectangle: 对于矩形:

ptsRect = [[  50.  100.]
           [  50.  200.]
           [ 250.  100.]
           [ 250.  200.]]

I am getting a perspective transform from these points: 我从这些点获得了一个透视变换:

T = cv2.getPerspectiveTransform(ptsTrap, ptsRect)

And then building the image from that: 然后从中构建图像:

arrTrapToRect = cv2.warpPerspective(arrTrap, T, arrTrap.shape[:2])

However, as you can see from the image, this isn't giving the expected transformation. 但是,正如您从图像中看到的那样,这并未给出预期的转换。

I can't seem to work out why even the points that defined the transform are not being projected according to it. 我似乎无法弄清楚为什么即使定义变换的点也没有根据它进行投影。 Any ideas? 有任何想法吗?

Your methodology is correct. 你的方法是正确的。 The problem arises when you specify the coordinates of your corner points. 指定角点的坐标时会出现问题。 I don't know how you calculated them, but you have swapped your X and Y axes. 我不知道你是如何计算它们的,但你已经交换了你的X轴和Y轴。 This is reflected in the transformation applied to your final image. 这反映在应用于最终图像的变换中。 I find the corner points to be: 我发现角点是:

ptsTrap = [[[  99.   51.]]
           [[  64.  251.]]
           [[ 234.  251.]]
           [[ 199.   51.]]]

ptsRect = [[[ 102.   49.]]
           [[ 100.  249.]]
           [[ 200.  250.]]
           [[ 200.   50.]]]

Finding the perspective transform from these points gives the correct result: 从这些点中查找透视变换会得到正确的结果: 透视变换结果

For reference, this is the code I used: 作为参考,这是我使用的代码:

import cv2
import numpy as np

def find_corners(image):
    im = cv2.Canny(image, 100, 200)

    cnt = cv2.findContours(im,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]
    cnt = cv2.approxPolyDP(cnt[0], 5, True)
    return cnt.astype(np.float32)

def main(argv):
    trap = cv2.imread('trap.png', cv2.IMREAD_GRAYSCALE)
    rect = cv2.imread('rect.png', cv2.IMREAD_GRAYSCALE)

    ptsTrap = find_corners(trap)
    ptsRect = find_corners(rect)

    T = cv2.getPerspectiveTransform(ptsTrap, ptsRect)

    warp = cv2.warpPerspective(trap, T, rect.shape[:2])

    cv2.imshow('', warp)
    cv2.imwrite('warp.png', warp)
    cv2.waitKey()
    cv2.destroyAllWindows()

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

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