如何使用opencv和c++从网络摄像头框架中找到轮廓

How to find contours from a webcam frame using opencv and c++?

本文关键字:框架 轮廓 摄像头 网络 opencv 何使用 c++      更新时间:2023-10-16

我的目标是通过从网络摄像头捕获帧来找到轮廓。我能够用静态图像做到这一点,但后来我试图在网络摄像头框架中使用相同的概念,它给了我这个错误:

"OpenCV Error: Assertion failed (mtype == type0 || (CV_MAT_CN(mtype) == CV_MAT_CN
(type0) && ((1 << type0) & fixedDepthMask) != 0)) in cv::_OutputArray::create, f
ile C:builds2_4_PackSlave-win64-vc11-sharedopencvmodulescoresrcmatrix.cpp
, line 1486"

这是我在程序中用来查找等高线的代码;

 Rng rng(12345);
    Mat captureframe,con,threshold_output;
    vector<vector<Point> > contours; //
   vector<Vec4i> hierarchy;
    while(true)
            {
                capturedevice>>captureframe;
                con = captureframe.clone();
                cvtColor(captureframe,con,CV_BGR2GRAY);
    threshold( con, threshold_output, thresh, 255, THRESH_BINARY );
     findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
     Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
    for( int i = 0; i< contours.size(); i++ )
    {
    Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
     drawContours( drawing, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
    }

    imshow("contour drawing",drawing);
    }

我认为问题出在以下两行:

con = captureframe.clone();
cvtColor(captureframe,con,CV_BGR2GRAY);

第一行中,您将con作为captureFrame的克隆,这意味着con 是3通道图像,而在第二行中,您正试图使con成为灰度图像,这是1通道,因此您正在获得与图像类型相关的故障。

你应该尝试做以下(我不确定你的代码是否会在此之后运行,但你不应该在此之后得到当前错误):

con.create(captureframe.rows , captureframe.cols, CV_8UC1);
cvtColor(captureframe,con,CV_BGR2GRAY);

朋友们,非常感谢你们的帮助。我终于发现我的错误,我的申报有问题。我在网上寻找一些参考资料,然后我偶然发现了这个代码的对象检测。这家伙实际上是这样声明"轮廓"的——"std::vector <std::向量&>>contours;我的声明是"矢量轮廓"。我的声明适用于静态图像,但在从网络摄像头找到轮廓时,它给了我这个错误。谁能给我解释一下以上两种声明的区别吗?此外,根据skm的建议,我通过使用con.create(frame.rows,frame.cols,cv_8uc1)将帧捕获转换为1通道深度图像,然后将其转换为灰度图像。这一步非常关键。所以,这里是我完整的工作代码!!由于

     VideoCapture capturedevice;
        capturedevice.open(0);
        Mat frame,con;
        Mat grayframe;
         std::vector < std::vector < cv::Point > >contours; //this is very important decalartion

while(true)
        {
            capturedevice>>frame;

            con.create(frame.rows,frame.cols,CV_8UC1);
            cvtColor(frame,con,CV_BGR2GRAY);
            cv::findContours (con, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
            cv::drawContours (frame, contours, -1, cv::Scalar (0, 0, 255), 2);

            imshow("frame", frame);
waitKey(33);
        }