I have this image:
And, would like to cut out the transparent background like this:
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:
- Load image using the
IMREAD_UNCHANGED
flag to maintain the alpha channel. - Get the bounding box within the alpha channel, determined by the non-zero pixels.
- Crop the image by proper Numpy array indexing.
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
----------------------------------------