如何剪出透明背景?

How to cut out transparent background?

我有这张图片:

而且,想把透明背景剪成这样:

使用 PIL 它将是:

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

但是,如何使用 OpenCV 变体来做到这一点?

与枕头中的想法几乎相同:

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)

生成的图片看起来与提供的图片完全一样。

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