我正在尝试遵循this教程。 我使用openCV4(本教程中使用了openCV3)。我无法解决有关对轮廓进行排序的错误,这就是为什么我需要您的帮助。
我在主题上寻找了类似的错误,我尝试过this,但没有用。我收到此错误:IndexError:索引1超出了轴1的大小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'
答案 0 :(得分:0)
OpenCV 4似乎更改了findContours
的输出参数:
image, contours, hierarchy = cv.findContours( image, mode, method[, contours[, hierarchy[, offset]]] )
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)