使用外置摄像头时,Opencv应用程序崩溃

时间:2014-07-10 08:15:58

标签: opencv camera crash external

使用轮廓进行物体识别。代码与图像配合得很好,我修改了代码,通过摄像头输入实时识别对象。我的笔记本电脑的集成摄像头可以很好地工作,但在使用外置摄像头几秒钟后崩溃。外部相机与我使用opencv开发的一些其他应用程序一起工作正常。相机是一个200万像素的相机。请查看代码并帮助我找出可能出错的地方。我的处理器足以处理高分辨率的图像。当我在应用程序启动之前在凸轮前面引入一个对象时,应用程序似乎崩溃了。

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);

} }

1 个答案:

答案 0 :(得分:1)

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

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));
}