gpt4 book ai didi

opencv - 使用外部摄像头时,Opencv应用程序崩溃

转载 作者:行者123 更新时间:2023-12-03 17:48:58 25 4
gpt4 key购买 nike

正在使用轮廓进行对象识别。该代码可以很好地处理图像,我修改了代码以使用摄像机输入实时识别对象。笔记本电脑的内置凸轮可以使一切正常运行,但是在使用外接摄像机时几秒钟后会崩溃。外部相机与我使用opencv开发的其他一些应用程序配合良好。该相机是20MP相机。请查看代码,并帮助我找出可能出问题的地方。我的处理器足以应付高分辨率的图像。似乎当我在启动应用程序之前在凸轮前面引入一个不存在的对象时,该应用程序崩溃了。

include <iostream>
include "opencv2/highgui/highgui.hpp"
include "opencv2/imgproc/imgproc.hpp"
using namespace cv; using namespace std;
int main()
{
int largest_area = 0;
int largest_contour_index = 0;
Rect bounding_rect;
int x = 0;
int y = 0;
VideoCapture xps(0);
Mat src;

while (1)
{

xps.read(src);


vector<vector<Point>> contours; // Vector for storing contour
vector<Vec4i> hierarchy;


Mat thr(src.rows, src.cols, CV_8UC1);
Mat dst(src.rows, src.cols, CV_8UC1, Scalar::all(0));
cvtColor(src, thr, CV_BGR2GRAY); //Convert to gray
threshold(thr, thr, 80, 255, THRESH_BINARY_INV);
findContours(thr, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

for (int i = 0; i< contours.size(); i++) // iterate through each contour.
{
double a = contourArea(contours[i], false); // Find the area of contour
if (a>largest_area)
{
largest_area = a;
largest_contour_index = i;
bounding_rect = boundingRect(contours[i]);
}

}


Scalar color(255, 255, 255);
drawContours(dst, contours, largest_contour_index, color, CV_FILLED, 8, hierarchy);
rectangle(src, bounding_rect, Scalar(0, 255, 0), 1, 8, 0);

x = bounding_rect.x + bounding_rect.width / 2;
y = bounding_rect.y + bounding_rect.height / 2;

circle(src, Point(x, y), 1, Scalar(0, 0, 255));

imshow("src", src);
imshow("largest Contour", dst);
waitKey(2);

}
}

最佳答案

我认为,崩溃是由于可能找不到的轮廓造成的。为避免此问题,请使用标记,如果找到了轮廓,则绘制它们。

bool found = findContours(thr, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); 

/* for loop */

if(found)
{
drawContours(dst, contours, largest_contour_index, color, CV_FILLED, 8, hierarchy);
rectangle(src, bounding_rect, Scalar(0, 255, 0), 1, 8, 0);

x = bounding_rect.x + bounding_rect.width / 2;
y = bounding_rect.y + bounding_rect.height / 2;

circle(src, Point(x, y), 1, Scalar(0, 0, 255));
}

关于opencv - 使用外部摄像头时,Opencv应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24671537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com