-215 opencv type_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.5.5 active
4.8.0 active
4.9.0 active

Root Cause

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

generic

中文

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

Official Documentation

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

Workarounds

  1. 95% success 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)
    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. 85% success edges = cv2.Canny(img_gray, 50, 150) contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    edges = cv2.Canny(img_gray, 50, 150)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

中文步骤

  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)

Dead Ends

Common approaches that don't work:

  1. 60% fail

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

  2. 40% fail

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

  3. 70% fail

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