设置Python OpenCV warpPerspective的背景

时间:2015-05-14 01:45:42

标签: python opencv image-processing

使用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 个答案:

答案 0 :(得分:9)

如果从在线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)

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

答案 1 :(得分:8)

虽然它没有在文档中列为可能的borderMode,但您也可以设置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)

答案 2 :(得分:6)

接受的答案不再适用。尝试用白色填充曝光区域。

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