使用opencv,如何去除透明图像中的非对象?

Jam*_*e H 3 python opencv image image-processing

我是图像处理方面的新手。

我正在尝试调整透明图像中绑定对象的矩形/框架的大小。

在此输入图像描述

但我不知道怎么做。

请帮我。

非常感谢。P/s:它不会与作物重复。在裁剪中,您修复了一个元组(从 x、y、w、h 裁剪)。但在我的照片中,我不知道在哪里裁剪。我们需要首先检测包含我的对象(太阳镜)的最小化矩形,然后进行裁剪。

api*_*i55 6

首先,您必须在 OpenCV 中加载支持 alpha 的图像

import cv2
import numpy as np #needed in the second step
im = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)
Run Code Online (Sandbox Code Playgroud)

注意cv2.IMREAD_UNCHANGED,它等于 -1。这将加载 BGRA 格式的图像

然后你找到对象的边界矩形

# axis 0 is the row(y) and axis(x) 1 is the column
y,x = im[:,:,3].nonzero() # get the nonzero alpha coordinates
minx = np.min(x)
miny = np.min(y)
maxx = np.max(x)
maxy = np.max(y) 
Run Code Online (Sandbox Code Playgroud)

然后裁剪对象

cropImg = im[miny:maxy, minx:maxx]
Run Code Online (Sandbox Code Playgroud)

最后显示结果并将其保存到磁盘

cv2.imwrite("cropped.png", cropImg)
cv2.imshow("cropped", cropImg)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)

我没有时间测试这段代码,所以我可能有错字。我希望它对你有帮助。有问题可以评论这个答案

更新

这是一个删除多余白色部分的小更新:

首先得到一个布尔掩码,它是白色的

whiteCellsMask = np.logical_and(cropImg[:,:,0] == 255, np.logical_and(cropImg[:,:,1] == 255, cropImg[:,:,2]== 255))
Run Code Online (Sandbox Code Playgroud)

然后将屏蔽值的 alpha 更改为 0

cropImg[whiteCellsMask,:] = [255, 255, 255, 0]
Run Code Online (Sandbox Code Playgroud)

这会将所有白色像素 (255,255,255) 更改为透明像素 (alpha = 0)。