Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background of Python OpenCV warpPerspective

When using warpPerspective to scale the image to be smaller, there are black area around it. It may be like:

or

How to make the black borders to be white?

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))

How to remove the black borders after warpPerspective?

like image 996
Ovilia Avatar asked May 14 '15 01:05

Ovilia


1 Answers

While it is not listed in the documentation as a possible borderMode, you can also set borderMode=cv2.BORDER_TRANSPARENT and it will not create any border whatsoever. It will keep the unchanged pixel settings of the destination image. In this manner you could make the border white or the border an image of your choice.

For example for image with a white border:

white_image = np.zeros(dsize, np.uint8)

white_image[:,:,:] = 255

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

Will create a white border for transformed image. In addition to the border you can also load anything as background image as long as it is the same size as the destination. For example, if I had a background panorama that I was warping an image onto I could use the panorama as the background.

Panorama with the warped image overlayed:

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

cv2.warpPerspective(src, M, panorama.shape, borderMode=cv2.BORDER_TRANSPARENT)
like image 86
Trevor Fiez Avatar answered Oct 23 '22 15:10

Trevor Fiez