设置Python OpenCV warpenspecti的背景

2024-05-28 11:17:34 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用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后的黑色边框?


Tags: 图像npcv2边框dst小时黑色float32
3条回答

虽然文档中未将其列为可能的borderMode,但您也可以将borderMode=cv2.BORDER_设置为透明,并且它不会创建任何边框。它将保持目标图像的像素设置不变。通过这种方式,您可以使边框为白色或边框为您选择的图像。

例如,对于带有白色边框的图像:

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)

接受的答案不再有效。尝试用白色填充暴露区域。

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

如果您查看联机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)

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

相关问题 更多 >