我已经研究了一些示例,以使用OpenCV在C ++中创建运动检测器,该运动检测器在移动对象周围绘制了一个矩形。
运行代码时,会弹出以下错误:
OpenCV错误:声明失败<0 <= I && I
> in cv :: InputArray :: getMat ,文件C:\ Users \ grapeot \ Source \ opencv \ modules \ core \ src \ matrix.cpp,第1192行
经过一些研究,我得出的结论是,这可能与通过 cnts 进行的循环有关(请参见下面的代码)。在python中,遍历Mat对象非常简单,但是对于C ++,这是我想出的最好方法。
如何解决此错误,或者为循环找到更好的解决方案? (如果错误甚至与此部分有关)
这些是示例:Python Tutorial Python Example C++ Example
这是我的代码:(对不起,无法在此处正确设置格式)
#include <opencv2/opencv.hpp>
#include <opencv2/video/tracking.hpp>
#include <opencv2/core/ocl.hpp>
using namespace cv;
using namespace std;
int main(int argc, char **argv) {
Mat frame,
gray,
frameDelta,
thresh,
firstFrame;
vector<vector<Point>> cnts;
Rect rect;
Point pt1, pt2;
VideoCapture cap(0);
String text;
cap >> frame;
cvtColor(frame, firstFrame, COLOR_BGR2GRAY);
GaussianBlur(firstFrame, firstFrame, Size(21, 21), 0, 0);
if (cap.isOpened()) {
while (true) {
cap >> frame;
if (frame.empty()) {
break;
}
text = "No motion detected";
// convert image to grayscale
cvtColor(frame, gray, COLOR_BGR2GRAY);
// blur image to decrease sensitivity of motion detection
GaussianBlur(gray, gray, Size(21, 21), 0, 0);
// compare current and previous frame, store result in frameDelta
absdiff(firstFrame, gray, frameDelta);
// we only look for differences larger than a certain threshold
threshold(frameDelta, thresh, 10, 255, THRESH_BINARY);
dilate(thresh, thresh, Mat());
findContours(thresh, cnts, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
for (int i = 0; i < cnts.size(); i++) {
if (contourArea(cnts[i]) < 500) {
continue;
}
// calculate box surrounding the contours
rect = boundingRect(cnts);
pt1.x = rect.x;
pt1.y = rect.y;
pt2.x = rect.x + rect.width;
pt2.y = rect.y + rect.height;
// draw the box
rectangle(frame, pt1, pt2, (0, 255, 0), 2);
text = "Motion detected";
}
putText(frame, text, Point(10, 20), FONT_HERSHEY_DUPLEX, 0.45, (0, 0, 255), 2);
imshow("Bounding Rectangles", frame);
imshow("delta", frameDelta);
if (waitKey(1) == 27) {
break;
}
}
}
return 0;
}