Python OpenCV warpPerspective 的背景设置

7
使用warpPerspective将图像缩小时,会在其周围产生黑色区域。可能会像这样:

或者

如何将黑色边框变成白色?
pts1 = np.float32([[minx,miny],[maxx,miny],[minx,maxy],[maxx,maxy]])
pts2 = np.float32([[minx + 20, miny + 20,
                   [maxx - 20, miny - 20],
                   [minx - 20, maxy + 20],
                   [maxx + 20, maxy + 20]])

M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(dst, M, (width, height))

如何在使用warpPerspective后移除黑边?
3个回答

15
虽然在文档中没有将borderMode设置为cv2.BORDER_TRANSPARENT,但实际上可以进行设置,并且这样做不会创建任何边框。它将保持目标图像的像素设置不变。通过这种方式,您可以使边框为白色或者是您选择的图像。
例如,对于带有白色边框的图像:
white_image = np.zeros(dsize, np.uint8)

white_image[:,:,:] = 255

cv2.warpPerspective(src, M, dsize, white_image, borderMode=cv2.BORDER_TRANSPARENT)

将为转换后的图像创建一个白色边框。除了边框外,只要背景图像与目标大小相同,您还可以加载任何内容作为背景图像。例如,如果我有一个背景全景图,我要将一张图像弯曲到上面,我可以使用全景图作为背景。

带有弯曲图像的全景图:

panorama = cv2.imread("my_panorama.jpg")

cv2.warpPerspective(src, M, panorama.shape, borderMode=cv2.BORDER_TRANSPARENT)

这太棒了 - 我确定以前需要在黑色背景上绘制,然后使用转换的遮罩进行移植。这种方法更加简洁。 - n00dle
这不是缺少了 dst 参数吗?而且文档上说的是 dsize,不是 shape。 - mLstudent33
@Trevor,这样做后,扭曲的图像现在与背景全景图重叠,它将保留背景而不是覆盖扭曲图像的像素吗?调用cv2.warpPerspective()似乎缺少dst - mLstudent33

12

如果您查看在线OpenCV文档(http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html)中的warpPerspective函数的文档,它会告诉您可以向该函数提供一个参数来指定常数边界颜色:

cv2.warpPerspective(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]])

何处

src – input image.
dst – output image that has the size dsize and the same type as src .
M – 3\times 3 transformation matrix.
dsize – size of the output image.
flags – combination of interpolation methods (INTER_LINEAR or INTER_NEAREST) and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation ( \texttt{dst}\rightarrow\texttt{src} ).
borderMode – pixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE).
borderValue – value used in case of a constant border; by default, it equals 0.

那么类似这样:

cv2.warpPerspective(dist, M, (width, height), cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, 255)

应将边框更改为恒定的白色。


为了得到白色,你需要在结尾处添加 ... cv2.BORDER_CONSTANT, 255, 255, 255) - GuySoft
2
我认为应该是:cv2.warpPerspective(dist, M, (width, height), cv2.INTER_LINEAR, borderValue=(255, 255, 255)) - 4Oh4

8

原先被接受的答案已经不再适用。尝试使用以下方法以白色填充暴露区域。

outImg = cv2.warpPerspective(img, tr, (imgWidth, imgHeight), 
    borderMode=cv2.BORDER_CONSTANT, 
    borderValue=(255, 255, 255))

可以确认。现在必须将borderMode作为命名参数传递,否则它会被静默忽略。 - couka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接