Home > Blockchain >  How to cut out transparent background?
How to cut out transparent background?

Time:09-18

I have this image:

enter image description here

And, would like to cut out the transparent background like this:

enter image description here

Using PIL it would be:

from PIL import Image
im = Image.open("image")
im.getbbox()
im2 = im.crop(im.getbbox())
im2.save("result")

But, how to do this using an OpenCV variant?

CodePudding user response:

Pretty much the same idea as in Pillow:

import cv2

im = cv2.imread('h62rP.png', cv2.IMREAD_UNCHANGED)
x, y, w, h = cv2.boundingRect(im[..., 3])
im2 = im[y:y h, x:x w, :]
cv2.imwrite('result.png', im2)

The resulting image looks exactly the same as the one provided.

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19042-SP0
Python:        3.9.6
PyCharm:       2021.2
OpenCV:        4.5.3
----------------------------------------
  • Related