Reputation:
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?
Upvotes: 1
Views: 1535
Reputation: 18925
Pretty much the same idea as in Pillow:
IMREAD_UNCHANGED
flag to maintain the alpha channel.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
----------------------------------------
Upvotes: 6