首页 > 解决方案 > 使用 OpenCV 处理透明背景

问题描述

我正在尝试获取图像中最大的黄色物体。我正在执行以下操作:

def findYellow(img):
    hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    lower_yellow, upper_yellow = np.array([18, 50, 90]), np.array([30, 255, 255])
    mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
    _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    max_contour = max(contours, key = cv2.contourArea)
    mask = np.zeros(img.shape[:2], dtype = 'uint8')
    cv2.drawContours(mask, [max_contour], -1, (255), -1)
    result = cv2.bitwise_and(img, img, mask=mask)
    cv2.imwrite('result.png', result)
    return result

到目前为止,一切都是正确的。

但现在我想做同样的事情,但背景透明(因为现在是黑色的,mask = np.zeros())。

我知道我必须使用 alpha 通道,mask = np.zeros((600,800, 4), dtype = 'uint8')但会出现此错误。

结果 = cv2.bitwise_and(img, img, mask=mask) cv2.error: OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\modules\core\src\arithm.cpp:241 : 错误: (-215:Assertion failed) (mtype == 0 || mtype == 1) && _mask.sameSize(*psrc1) in function 'cv::binary_op'

因此,我的想法是将我当前的 BGR 图像转换为 BGRA,b = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)但再次失败并出现相同的错误。

def findYellow(img):
    hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    lower_yellow, upper_yellow = np.array([18, 50, 90]), np.array([30, 255, 255])
    mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
    _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    max_contour = max(contours, key = cv2.contourArea)
    mask = np.zeros((600, 800, 4), dtype = 'uint8')
    cv2.drawContours(mask, [max_contour], -1, (255), -1)
    b = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
    result = cv2.bitwise_and(b, b, mask=mask)
    cv2.imwrite('result.png', result)
    return result

有人可以帮助我吗?我需要使用透明背景,因为在后面的步骤中黑色会对我产生负面影响。

非常感谢你!!

标签: pythonopencv

解决方案


如果第一个代码是正确的,请执行以下操作:

result = cv2.bitwise_and(img, img, mask=mask)
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:,:,3] = mask #Set mask as alpha channel
cv2.imwrite('result.png', result)
return result

推荐阅读