-2

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?

3
  • you need to load the image with 4 channels. 3 for the colors 1 for transparency/alpha. im = cv2.imread('image.png', cv2.IMREAD_UNCHANGED) should work. if you allready have data: im = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2RGBA) Commented Jul 15, 2024 at 11:12
  • 1
    you WILL get artefacts at edges between transparent and opaque areas. if you're lucky, those edges will just appear darker, but they may be tinted with wild colors. that depends on what colors the transparent pixels happen to be given. Commented Jul 15, 2024 at 12:18
  • 1
    This question is similar to: Set white background for a png instead of transparency with OpenCV. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 15, 2024 at 12:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

that's still not going to solve the artefacts that'll happen due to the resize()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.