Displaying webcam feed in cv::Mat format in a picturebox

U.B.A.R picture U.B.A.R · Sep 27, 2012 · Viewed 9.6k times · Source

I am using OpenCV to take a live stream from a webcam and after detecting faces. I am resizing them so that only my face is displayed.

But the problem is that I am doing all this in C++ Windows Forms and I want it to be displayed in a PictureBox instead of getting the display in OpenCV imshow() window.

I'm using cv::Mat so I am having a great deal of problem with displaying in the picture box.

I have tried converting it into IplImage but that didn't work either. Also, I have tried Google but I couldn't get a working solution. I've been trying this for 3 days.

Here's my code for displaying:

                 face = getFace(frame);
                 cv::imshow("window",face);

where frame and face are cv::Mat

Answer

sgarizvi picture sgarizvi · Sep 27, 2012

Here is a C++ CLR function to draw OpenCV mat on any Windows Form Control:

void DrawCVImage(System::Windows::Forms::Control^ control, cv::Mat& colorImage)
{
    System::Drawing::Graphics^ graphics = control->CreateGraphics();
    System::IntPtr ptr(colorImage.ptr());
    System::Drawing::Bitmap^ b  = gcnew System::Drawing::Bitmap(colorImage.cols,colorImage.rows,colorImage.step,System::Drawing::Imaging::PixelFormat::Format24bppRgb,ptr);
    System::Drawing::RectangleF rect(0,0,control->Width,control->Height);
    graphics->DrawImage(b,rect);
    delete graphics;
}

This function can only draw 8 bit 3 channel images.

Try experimenting with Pixel Format of the bitmap for other image types.