如何结合Meta AI SAM生成的掩码正确使用cv2.bitwise_and()?
问题解决:SAM掩码在OpenCV bitwise_and中报错「mask data type = 0 is not supported」
错误原因
SAM生成的掩码是布尔类型(numpy.bool_),而OpenCV的cv2.bitwise_and对掩码有严格要求:必须是8位无符号单通道数组(uint8),且非0值被视为有效区域。布尔类型数组在OpenCV中会被识别为data type 0,不符合参数要求,因此触发报错。
修复方案
将SAM输出的布尔掩码转换为uint8类型,并把布尔值True映射为255(OpenCV中标准的有效掩码值),再传入bitwise_and函数。
修改后的代码
masks, scores, logits = mask_predictor.predict( box=box, multimask_output=True) for i, (mask, score) in enumerate(zip(masks, scores)): print("image.shape" + str(image.shape)) # image.shape(506, 447, 3) print("mask.shape" + str(mask.shape)) # mask.shape(506, 447) # 转换掩码为OpenCV支持的uint8类型 cv_mask = mask.astype(np.uint8) * 255 masked_img = cv2.bitwise_and(image, image, mask=cv_mask)
说明
转换后的掩码形状保持不变,但数据类型变为uint8,其中掩码区域的值为255,非掩码区域为0,完全符合OpenCV的掩码要求,此时bitwise_and可以正常执行,实现「屏蔽原始图像中不在掩码范围内的区域」的目标。
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

