-215 opencv type_error ai_generated true

cv::error: (-215:断言失败) _src.type() == CV_8UC1 在函数 'cv::findContours' 中

cv::error: (-215:Assertion failed) _src.type() == CV_8UC1 in function 'cv::findContours'

ID: opencv/contours-not-found-in-binary-image

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
4.5.5 active
4.8.0 active
4.9.0 active

根因分析

findContours 需要8位单通道二值图像,但输入图像是多通道或非8位类型。

English

findContours requires an 8-bit single-channel binary image, but the input is multi-channel or non-8-bit.

generic

官方文档

https://docs.opencv.org/4.x/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0

解决方案

  1. img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  2. edges = cv2.Canny(img_gray, 50, 150)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

无效尝试

常见但无效的做法:

  1. 60% 失败

    Grayscale may still have multiple channels (e.g., 3-channel grayscale) or be 16-bit. findContours explicitly needs CV_8UC1.

  2. 40% 失败

    Canny output is binary but may still have non-zero values outside 0-255 if not properly normalized; thresholding ensures binary.

  3. 70% 失败

    Resize does not change channel count; the image remains 3-channel.