5

I need to read an image in Mat form using openFileDialog and display it in a pictureBox (in Visual C++/Visual Studio 2010).

I searched a lot but couldn't find the answer.

I am using this code:

openFileDialog1->Filter = "JPEG files (*.jpg)|*.jpg|Bitmap files (*.bmp)|*.bmp";
if(openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
    Mat img;
    img = imread(openFileDialog1->FileName, CV_LOAD_IMAGE_COLOR);
    pictureBox1->Image = (gcnew Bitmap(img.size().width,
                                            img.size().height,
                                            img.widthStep,
                                            Imaging::PixelFormat::Format24bppRgb,
                                            (IntPtr)img.data));

}
Todd Anderson
  • 53
  • 1
  • 1
  • 5

2 Answers2

3

This question has already been answered here:

For your requirement, you can do it like this:

Mat img;
img = imread(openFileDialog1->FileName, CV_LOAD_IMAGE_COLOR);

System::Drawing::Graphics^ graphics = pictureBox1->CreateGraphics();
System::IntPtr ptr(img.ptr());
System::Drawing::Bitmap^ b  = gcnew System::Drawing::Bitmap(img.cols,img.rows,img.step,System::Drawing::Imaging::PixelFormat::Format24bppRgb,ptr);
System::Drawing::RectangleF rect(0,0,pictureBox1->Width,pictureBox1->Height);
graphics->DrawImage(b,rect);
Community
  • 1
  • 1
sgarizvi
  • 16,623
  • 9
  • 64
  • 98
  • Thank you so much for your help. Now I have only one problem, for the first part I got this error: _error C2664: 'cv::imread' : cannot convert parameter 1 from 'System::String ^' to 'const std::string &'_ – Todd Anderson May 03 '13 at 23:28
  • Check [this post](http://stackoverflow.com/questions/946813/c-cli-converting-from-systemstring-to-stdstring) which has many answers describing how to convert `System::String` to `std::string`. – sgarizvi May 04 '13 at 06:10
  • If I change my image to grayScale with this code: cvtColor( src, src_gray, CV_BGR2GRAY ); Then this function shows 3 images beside each other. How should I change the code to display correct GrayScale Image in pictureBox? – Todd Anderson Jul 19 '13 at 11:55
1

You need to set Picturebox's Palette like this:

ColorPalette^ palette = pictureBox1->Image->Palette;
UInt32 Alpha = 0xFF;
UInt32 Intensity;

for (System::UInt16 i = 0; i < palette->Entries->Length; ++i)
{

    Intensity = i * 0xFF / 255;

    palette->Entries[i] = Color::FromArgb(static_cast<int>(Alpha),
                                          static_cast<int>(Intensity),
                                          static_cast<int>(Intensity),
                                          static_cast<int>(Intensity));
}

pictureBox1->Image->Palette = palette;
Felix
  • 11
  • 1