【问题标题】:Working with transparent background using OpenCV使用 OpenCV 处理透明背景
【发布时间】:2021-03-29 19:51:36
【问题描述】:

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

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: error: (-215:Assertion failed) (mtype == 0 || mtype == 1) && _mask.sameSize(*psrc1) 在函数'cv::binary_op'中

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

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

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

非常感谢!!

【问题讨论】:

    标签: python opencv


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2014-11-30
      • 2021-03-14
      • 1970-01-01
      • 2018-09-22
      • 2011-03-08
      • 2014-05-07
      • 2020-11-20
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多