OpenCV中的外围像素warpPerspective()

Kev*_*ine 5 opencv

我的申请要求将一个四边形映射到另一个四边形.这些都不是矩形.

但是,我从warpPerspective()得到的结果总是一个矩形.我已经尝试将"异常值"标志设置为不同的值,以防止扭曲四边形外的像素出现在目标图像中,但似乎没有任何效果.我想要的是一个扭曲的四边形,扭曲的四边形外面的像素设置为透明.

我该如何实现这一目标?

或者,是否有一种直接的方法来掩盖OpenCV中四边形外的区域,以便我可以只将四边形复制到另一个图像?

如果它是相关的,我使用Python绑定到OpenCV.

这是我目前的代码:

def warpImage(image, corners, target, width, height):
    mat = cv2.getPerspectiveTransform(corners, target)
    out = numpy.zeros(shape=(width, height), dtype="uint8")
    out = cv2.warpPerspective(image, mat, (width,height), out, cv2.INTER_CUBIC)
    return out
Run Code Online (Sandbox Code Playgroud)

角和目标都是非矩形四边形.但是,输出是一个全宽x高的矩形.没有像素是黑色或透明的.相反,它们是角四边形内外的图像像素.我只想要里面的那些.

Kev*_*ine 0

我发现的最佳选择是循环遍历像素并使用 matplotlib pnpoly() 函数将扭曲四边形中的像素复制到重新映射数组,如下所示:

import matplotlib.nxutils as nx 

def warpImage(image, corners, target, width, height, x0, y0, remap):
    mat = cv2.getPerspectiveTransform(corners, target)
    out = cv2.warpPerspective(image, mat, (width,height), flags=cv2.INTER_CUBIC)
    for x in range(0,width):
        for y in range(0,height):
            if nx.pnpoly(x,y,target) == 1:
                for i in range(0,3):
                    remap[y+y0,x+x0,i] = out[y,x,i]

    return remap
Run Code Online (Sandbox Code Playgroud)

我循环遍历图像中的所有四边形,并在重映射中累积转换后的版本。

必须访问每个像素不是很有效,但幸运的是这是一次性转换。