Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

How to properly convert Mat to Bitmap C++

Hello,

I'm a student and I'm learning OpenCV (C++) and I'm having a weird question. I'm using OpenCV in C++/CLI and a C# Windows Form to show the output.

This is my plan on how to do this:

  1. Load Mat Image in C++ 2.
  2. Convert Mat to Bitmap
  3. Return the Bitmap from C++ to C# 4.
  4. Show the Bitmap on Windows Form.

Now I thought this was a good strategy but I got an error saying: 'Access Violation Exception'. So I tried to look for an answer but couldn't find it on the Web. I have all my projects in x64. The weird thing is that if I put 'imshow()' function in this method, I get a weird looking picture, but no errors.

This is the .cpp file:

Bitmap^ OpenCvWrapper::ApplyFilter() {
    Mat image = imread("C:/Users/Andries/Pictures/colored_squares.png");

    returnImg = ConvertMatToBitmap(image)
    return returnImg;
}


Bitmap^ OpenCvWrapper::ConvertMatToBitmap(cv::Mat matToConvert) {
    imshow("Window", matToConvert);
    Bitmap^ test = gcnew Bitmap(matToConvert.rows, matToConvert.cols, 4 * matToConvert.rows, System::Drawing::Imaging::PixelFormat::Format4bppIndexed, IntPtr(matToConvert.data));

    return test;
}

And this is my .cs file:

public partial class Form1 : Form
    {
        private Bitmap f;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpencvDotNet.OpenCvWrapper obj = new OpencvDotNet.OpenCvWrapper();
            f = obj.ApplyFilter();
            pictureBox1.Image = f;
    }

I can provide the header but I think that's not necessary as of now.

Now with this code I get the following output: image description

Please help.

Andries