首页 > 解决方案 > python opencv findContours() 错误 cpp 197

问题描述

尝试使用 findContours() 但不断收到 cpp:197 错误(-210:不支持的格式或格式组合)

我在其他文件中使用了相同的格式,并且效果很好。不知道为什么它在这里不起作用。

完整错误:

Traceback (most recent call last):
  File "C:/Users/FreddyMac/PycharmProjects/TestProj/ballTrackingAbsDiff.py", line 33, in <module>
    cnts = cv2.findContours(th1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-cff9bdsm\opencv\modules\imgproc\src\contours.cpp:197: error: (-210:Unsupported format or combination of formats) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function 'cvStartFindContours_Impl'

我检查了图像的类型,并且是正确的“uint8”类型。

请参阅下面的代码。

import cv2
import imutils

vs = cv2.VideoCapture('ballsFlying.MP4')
while True:
    # read frame1, resize and convert to grayscale
    ret, frame1 = vs.read()
    if frame1 is None:
        break
    frame1 = imutils.resize(frame1, width=600)
    gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)

    # read frame2, resize and convert to grayscale
    ret2, frame2 = vs.read()
    if frame2 is None:
        break
    frame2 = imutils.resize(frame2, width=600)
    gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)

    # compute the difference between frames
    dist = cv2.absdiff(frame1, frame2)
    # blur image
    blurred = cv2.GaussianBlur(dist, (9, 9), 0)

    # global thresholding
    ret3, th1 = cv2.threshold(blurred, 85, 255, cv2.THRESH_BINARY)
    print(th1.dtype)

    cnts = cv2.findContours(th1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # other way to find contours = same error
    # hierarchy, contours = cv2.findContours(th1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    cv2.imshow('dist', frame1)
    cv2.imshow('thresh', th1)
    cv2.imshow('blurred', blurred)

    # show the frame to our screen
    key = cv2.waitKey(100) & 0xFF
    # if the 'q' key is pressed, stop the loop
    if key == ord("q"):
        break

# otherwise, release the camera
vs.release()
# close all windows
cv2.destroyAllWindows()

标签: pythonopencv

解决方案


好吧,错误说明了答案:

FindContours 在 mode != CV_RETR_FLOODFILL 时仅支持 CV_8UC1 图像,否则仅在函数中支持 CV_32SC1 图像

由于您没有使用CV_RETR_FLOODFILL,因此您的图像应该是CV_32SC1单通道图像。findContours适用于单通道图像。

使用灰色图像,问题将得到解决。

dist = cv2.absdiff(gray1, gray2)

结果:

th


在此处输入图像描述

模糊


在此处输入图像描述


推荐阅读