Search code examples
c++opencvc++-clipictureboxrtsp

C++ rtsp stream in Windows Forms


I have a program that receives rtsp video from the camera and transmits it to the picturebox. It only works for a few seconds, then the program hangs, help find the error.

private: System::Void start_Click(System::Object^ sender, System::EventArgs^ e) {
if (start->Text == "Start stream"){
    start->Text = "Stop stream";
}
else if (start->Text == "Stop stream") {
    pictureBox1->Refresh();
    start->Text = "Start stream";
}
cv::VideoCapture stream = cv::VideoCapture(ip[n]);
cv::Mat frame;
while (start->Text == "Stop stream")
{
    stream.read(frame);
    System::Drawing::Graphics^ graphics = pictureBox1->CreateGraphics();
    System::IntPtr ptr(frame.ptr());
    System::Drawing::Bitmap^ b = gcnew System::Drawing::Bitmap(frame.cols, frame.rows, frame.step, System::Drawing::Imaging::PixelFormat::Format24bppRgb, ptr);
    System::Drawing::RectangleF rect(0, 0, pictureBox1->Width, pictureBox1->Height);
    graphics->DrawImage(b, rect);
    delete graphics;    
}

Solution

  • Fixed by changing while(expression)

    cv::VideoCapture stream = cv::VideoCapture(ip[n]);
            cv::Mat frame;
            if (stream.isOpened())
            {
                flag = true;
                while (cv::waitKeyEx(1) != 27)
                {
                    stream.read(frame);
                    System::Drawing::Graphics^ graphics = pictureBox1->CreateGraphics();
                    System::IntPtr ptr(frame.ptr());
                    System::Drawing::Bitmap^ b = gcnew System::Drawing::Bitmap(frame.cols, frame.rows, frame.step, System::Drawing::Imaging::PixelFormat::Format24bppRgb, ptr);
                    System::Drawing::RectangleF rect(0, 0, pictureBox1->Width, pictureBox1->Height);
                    graphics->DrawImage(b, rect);
                    delete graphics;
                }
            }