OpenCV - Turn Transparent Part of PNG white

别说谁变了你拦得住时间么 提交于 2019-12-13 01:52:48

问题


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

I have a set of images who 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


回答1:


You should load image with -1, which is IMREAD_UNCHANGED, i.e.

img = cv2.imread("./Green/imgage-000.png", cv2.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.



来源:https://stackoverflow.com/questions/48816703/opencv-turn-transparent-part-of-png-white

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!