【问题标题】:Opencv app crashes when using external camera使用外部摄像头时 Opencv 应用程序崩溃
【发布时间】:2014-07-10 08:15:58
【问题描述】:

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

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

} }

【问题讨论】:

  • “请查看代码并帮助我找出可能出现的问题”。如果您需要帮助,请提供有关错误的更多信息:代码在哪里崩溃,错误消息是什么等。
  • 创建VideoCapture对象后,检查xps.isOpen()。如果为 false,则说明您的相机未打开。如果xps.read(frame) 返回false,你可以检查一下。

标签: opencv camera crash external


【解决方案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));
}

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多