OpenCV – Turn Transparent Part of PNG white

Question:

I am new to OpenCV so please bear with me if my qustion seems silly to you.

I have a set of images that all have a transparent border on the left and right like you can see below:
enter image description here

I want to erase these borders so I thought about edge detection which would be easy to do if I could transform these transparent borders to a white color. In the Docs I found that you can do this:

img = cv2.imread("./Green/image-000.png", 1)
cv2.imwrite('../image-000.png', img)

This erases the alpha channel of the png image but turns it into black.
Is there something similar that turns the borders white?
Or is there even a simpler method of erasing these borders?
You would make me really happy if you could help me!

PS: I use Python 2.7 and OpenCV 3.4

Asked By: Joh

||

Answers:

You should load image with IMREAD_UNCHANGED, i.e.

import cv2 as cv
img = cv.imread("./Green/imgage-000.png", cv.IMREAD_UNCHANGED)

Then, your image will have 4 channels (BGRA), and you can use alpha channel mask to turn the corresponding part to white:

alpha_channel = img[:, :, 3]
_, mask = cv.threshold(alpha_channel, 254, 255, cv.THRESH_BINARY)  # binarize mask
color = img[:, :, :3]
new_img = cv.bitwise_not(cv.bitwise_not(color, mask=mask))

I tested this code with a transparent PNG where the color channels were black and the information was in the transparency:

input image with gradual transparency
output image with binary pixels

The nested bitwise_not is ugly but is the only way I found to make it work.

Answered By: Quang Hoang
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.