OpenCV 网络摄像头提要未在 PictureBox 中显示 visual studio 2015

OpenCV Webcam feed not displaying in PictureBox visual studio 2015

您好,我使用 opencv 从我的默认摄像头获取网络摄像头源,我希望将其显示在我的 windows 表单的图片框中。我的网络摄像头出现了,但由于某种原因,提要从未显示在我的图片框上。请有人帮助指出 out/solve 这个问题,因为我现在被困在这里。 提前致谢。

在 myform.h 中,我有将图片框发送到 myform.cpp 文件的代码:

System::Windows::Forms::PictureBox^ mypicbox1(void)  
{
    opencv_gui::MyForm aform;
    return aform.pictureBox1;
}

绘制代码获取视频源并放入我在 myform.cpp 中的图片框是:

void opencv_gui::DrawCvImage(const cv::Mat& cvImage)
{
    System::Windows::Forms::PictureBox^ pictureBox = mypicbox1();
    // only color images are supported
    assert(cvImage.type() == CV_8UC3);

    if ((pictureBox->Image == nullptr) || (pictureBox->Width != cvImage.cols) || (pictureBox->Height != cvImage.rows))
    {
        pictureBox->Width = cvImage.cols;
        pictureBox->Height = cvImage.rows;
        pictureBox->Image = gcnew System::Drawing::Bitmap(cvImage.cols, cvImage.rows);
    }

    // Create System::Drawing::Bitmap from cv::Mat
    System::Drawing::Bitmap^ bmpImage = gcnew System::Drawing::Bitmap(
        cvImage.cols, cvImage.rows, cvImage.step,
        System::Drawing::Imaging::PixelFormat::Format24bppRgb,
        System::IntPtr(cvImage.data)
    );

    // Draw Bitmap over a PictureBox
    System::Drawing::Graphics^ g = System::Drawing::Graphics::FromImage(pictureBox->Image);

    g->DrawImage(bmpImage, 0, 0, cvImage.cols, cvImage.rows);
    pictureBox->Refresh();

    delete g;
}


//camera feed
int opencv_gui::video_cap(void)
{
    VideoCapture cap;

    if (!cap.open(0)) // open the default camera (camera 0), use something different from 0 otherwise;
        return 0;
    for (;;)
    {
        Mat frame;
        cap >> frame;
        if (frame.empty()) break; // end of video stream
        DrawCvImage(frame);
        if (waitKey(10) == 27) break; // stop capturing by pressing ESC 
    }
    // the camera will be closed automatically upon exit
    // cap.close();
    return 0;
}

这是我的调试日志:我使用像“>>>>>>>”这样的箭头来显示重要参数,用 "RED >>>>>>>" 来显示错误参数。

不得不稍微编辑一下我的代码,但我使用此处提供的答案几乎解决了我的问题:

试试这个

private: System::Void button2_MouseClick(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
{
    if (button2->Text == "Stop")
    {
        button2->Text = "Start";

    }
    else if (button2->Text == "Start")
    {
        button2->Text = "Stop";

    }

     VideoCapture capture(0);
     Mat frame;

     while (button2->Text == "Stop")
     {
         capture.read(frame);
         System::Drawing::Graphics^ graphics2 = pictureBox1->CreateGraphics();
         System::IntPtr ptr2(frame.ptr());
         System::Drawing::Bitmap^ b2 = gcnew System::Drawing::Bitmap(frame.cols,
             frame.rows, frame.step, System::Drawing::Imaging::PixelFormat::Format24bppRgb, ptr2);
         System::Drawing::RectangleF rect2(0, 0, pictureBox1->Width, pictureBox1->Height);
         graphics2->DrawImage(b2, rect2);

     }
 }