python - 使用 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
有人可以帮助我吗?我需要使用透明背景,因为在后面的步骤中黑色会对我产生负面影响。
非常感谢你!!
解决方案
如果第一个代码是正确的,请执行以下操作:
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
推荐阅读
- ios - 从 iOS 本机上的 pacfile 获取代理 url
- android - 我有一个应用程序,除非通过 VS 的 xamarin 工具安装,否则它不会加载到模拟器上的启动屏幕之外
- python - 如何解决 Heroku cllect static --noiput 错误
- clip-path - 如何使用剪辑路径 css 制作圆形五边形?
- r - 在 df 连接或查找中基于字符串 %in% 的查找值?
- amazon-web-services - AWS MWAA - 气流 - 负载连接
- django - 如何在 django 管理面板中预先填充 charfield 值,作为从一个模型到另一个模型的下拉列表
- javascript - 有条件的着陆页
- excel - 试图在指定列中查找值
- html - React Router 只有一个链接工作 Github Pages