繁体   English   中英

为什么我不能用 openCV4 对轮廓区域进行排序

[英]Why can I not sort a contourArea with openCV4

我正在尝试按照教程进行操作。 我使用openCV4(教程中使用了openCV3)。 我无法修复有关对轮廓进行排序的错误,这就是我需要您帮助的原因。

我在主题上寻找过类似的错误,我试过这个,但没有用。 我收到此错误:IndexError: index 1 is out of bounds for axis 0 with size 1

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True: #Infinite loop to work on all the pictures
    ret, frame = cap.read()
    if ret is False:
        break

    roi = frame
    rows, cols, _ = roi.shape
    gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) #converts color
    gray_roi = cv2.GaussianBlur(gray_roi, (7, 7), 0) #Apply a gaussien filter

    _ , threshold, = cv2.threshold(gray_roi, 3, 255, cv2.THRESH_BINARY_INV) 
    _ , cnts = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    if cnts is None:
        print('No eyes found!')
    else:
        cnts = sorted(cnts, key=lambda x: cv2.contourArea(x), reverse=True)
        for cnt in cnts:
            (x, y, w, h) = cv2.boundingRect(cnt)

            cv2.rectangle(roi, (x, y), (x + w, y + h), (255, 0, 0), 2)
            cv2.line(roi, (x + int(w/2), 0), (x + int(w/2), rows), (0, 255, 0), 2)
            cv2.line(roi, (0, y + int(h/2)), (cols, y + int(h/2)), (0, 255, 0), 2)
            break

        #cv2.imshow("Threshold", threshold)
        #cv2.imshow("gray roi", gray_roi)
        #cv2.imshow("Roi", roi)

cv2.destroyAllWindows()

输出直接显示错误,甚至不打印“找不到眼睛”(与我收到索引错误时相比)这是错误:

Traceback (most recent call last):
  File "eye_motion_tracking.py", line 22, in <module>
    cnts = sorted(cnts, key=lambda x: cv2.contourArea(x), reverse=True)
  File "eye_motion_tracking.py", line 22, in <lambda>
    cnts = sorted(cnts, key=lambda x: cv2.contourArea(x), reverse=True)
cv2.error: OpenCV(4.1.0) /home/rshah/opencv/opencv-4.1.0/modules/imgproc/src/shapedescr.cpp:274: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'contourArea'

看来 OpenCV 4 更改了findContours的输出参数:

OpenCV 3.4.6 findContours轮廓

image, contours, hierarchy  =   cv.findContours(    image, mode, method[, contours[, hierarchy[, offset]]]  )

OpenCV 4.0.0 findContours轮廓

contours, hierarchy =   cv.findContours(    image, mode, method[, contours[, hierarchy[, offset]]]  )

这意味着您的代码实际上正在接收hierarchy而不是contours 只是改变

    _ , cnts = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    cnts = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM