pythonopencvtransparencyimage-resizingalpha

How to resize an image and keep backround empty using OpenCV


I have the following 256x256 image:

Original 256x256

I want to resize it to 100x100 pixels using OpenCV:

img = cv2.imread('image.png')

p = 100/256
new_width = int( img.shape[1] * p ) 
new_height = int( img.shape[0] * p ) 

resized = cv2.resize(img, (new_width, new_height))

What I get after execution of the code above:

Resized 100x100

As you can see, its background colour changed to black. But I want to keep the backgound empty. What can I do?


Solution

  • Try read the image with cv2.IMREAD_UNCHANGED:

    img = cv2.imread('image.png', cv2.IMREAD_UNCHANGED)
    

    Reading with cv2.IMREAD_UNCHANGED to ensure the alpha channel (transparency) is preserved.