You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV cv2.findContours报错:环境变更后参数传递异常排查

解决OpenCV findContours报错问题

以下是用于去除图像手指区域的代码,此前运行正常,环境变更后调用cv2.findContours时出现参数错误:

def remove_fingers(image_bf, mask_color):
    image_array = np.array(image_bf, dtype=np.uint8)
    height, width, _ = image_array.shape

    # RGB转HSV
    hsv_array = np.array([[rgb_to_hsv(r, g, b) for (r, g, b) in row] for row in image_array])

    # 确定肤色掩膜范围
    lower_skin = (0, 15, 20)
    upper_skin = (35, 100, 100)
    lower_skin_2 = (320, 15, 20)
    upper_skin_2 = (360, 100, 100)

    # 创建掩膜
    mask = hsv_filter(hsv_array, lower_skin, upper_skin) | hsv_filter(hsv_array, lower_skin_2, upper_skin_2)
    print(mask.dtype)  # 输出: bool
    print(mask.shape)  # 输出: (height, width)

    mask = (mask.astype(np.uint8)) * 255

    print(mask.dtype)  # 输出: uint8
    print(mask.shape)  # 输出: (height, width)
    print(np.unique(mask))  # 输出: array([0, 255], dtype=uint8)  
    contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

报错信息如下:

contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'findContours'
Overload resolution failed:

  • image is not a numpy array, neither a scalar
  • Expected Ptrcv::UMat for argument 'image'

已确认mask是仅包含0和255的uint8类型二维numpy数组,怀疑是OpenCV或matplotlib等依赖环境变更导致问题。

可行解决方案:

  • 转换为连续内存数组:OpenCV对输入数组的内存连续性有要求,可将mask转为连续数组后再传入:
    mask = np.ascontiguousarray(mask)
    contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
  • 显式转换为UMat类型:直接将numpy数组转为OpenCV的UMat格式,匹配参数要求:
    mask_umat = cv2.UMat(mask)
    contours, hierarchy = cv2.findContours(mask_umat, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
  • 检查依赖版本兼容性:OpenCV 4.x与部分numpy版本存在兼容性问题,尝试重新安装匹配版本的依赖,例如:
    pip uninstall opencv-python numpy
    pip install opencv-python==4.7.0 numpy==1.24.3
    
  • 验证hsv_filter输出:确认hsv_filter函数返回的是标准二维bool数组,避免因自定义函数输出异常导致后续转换出现隐性问题。

内容的提问来源于stack exchange,提问作者ss tt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:52:40