python - python关于openingRect的opencv错误

标签 python opencv numpy

当我尝试有关运动捕捉的代码时,由于该错误,我无法成功运行。

    Traceback (most recent call last):
  File "G:\machine learning\CV\Video Capture\motion capture with square.py", line 21, in <module>
    x,y,w,h=cv2.boundingRect(thresh)
error: ..\..\..\..\opencv\modules\imgproc\src\contours.cpp:1895: error: (-215) points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S) in function cv::boundingRect

首先,我认为数据类型可能不正确,因此我将类型更改为“float32”和“int32”。但这无济于事,所以我不知道。

这是我的代码:
import cv2  
import numpy as np
camera=cv2.VideoCapture(0)  
firstframe=None  
while True:  
    ret,frame = camera.read()
    #cv2.imshow("frame", frame)
    if not ret:  
        break  
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)  
    gray=cv2.GaussianBlur(gray,(21,21),0)  
    if firstframe is None:  
        firstframe=gray  
        continue  

    frameDelta = cv2.absdiff(firstframe,gray)  
    thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]  
    thresh = cv2.dilate(thresh, None, iterations=2)  
    #(cnts,_)= cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    x,y,w,h=cv2.boundingRect(thresh)  
    frame=cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)  
    cv2.imshow("frame", frame)  
    cv2.imshow("Thresh", thresh)  
    cv2.imshow("frame2", frameDelta)  
    key = cv2.waitKey(1)&0xFF  

    if key == ord("q"):  
        break  

camera.release()  
cv2.destroyAllWindows()  

最佳答案

因为cv2.boundingRect()期望采用特殊格式的一组点(x, y)坐标来计算边界rect,所以您的输入图像不是一组(x, y)点。此方法不能直接应用于图像。您必须找到给定二进制掩码的contours,然后可以迭代所有轮廓并在各个轮廓上调用cv2.boundingRect(),如下所示:

cnts, hierarchy= cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# Iterate over all the contours.
for contour in cnts:
    print cv2.boundingRect(contour)

关于python - python关于openingRect的opencv错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083893/

相关文章:

python - 尝试复制 MyClass(QObject) 在 Python 中抛出 RuntimeError

python - Maya python 反斜杠替换问题

opencv - 无法加载 EmguCV 元数据文件

c++ - opencv houghCircles ( .... ?PARAM1?, ?PARAM2?)

java - 如何用另一种语言(不是 Python)编写 Celery worker/tasks?

python - SKLearn - 无法导入 LinearModel?

c++ - 如何将openCV项目构建为dll

python - python中3D曲线的保形分段三次插值

python - Pycharm 无法导入 numpy

python - NumPy complex128除法与float64除法不一致