Reputation: 337
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:
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
Upvotes: 3
Views: 5857
Reputation: 150735
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:
The nested bitwise_not
is ugly but is the only way I found to make it work.
Upvotes: 9