Reputation: 11
I need to pass a Bitmap to dll created in C++ with opencv. In the dll I use Mat object for processing the image. I would want to know how can I change the Bitmap object into a Mat object. I tried using IntPtr but I do not know how to build the Mat object since the Mat constructor does not support IntPtr. Does anyone know how can I do this? It would be best if you could help me with a piece of code. Thanks.
Upvotes: 0
Views: 2303
Reputation: 11
Thank you for your help! I found another way to do it. Check my code: C#:
[DllImport("addborders.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int main(IntPtr pointer, uint height,uint width);
unsafe
{
fixed (byte* p = ImageToByte(img))
{
var pct = (IntPtr) p;
x = main(pct, (uint)img.Height, (uint)img.Width);
}
textBox1.Text = x.ToString();
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
C++
extern "C"
{
__declspec(dllexport)
int main(unsigned char* image,unsigned int height,unsigned int width)
{
cv::Mat img = cv::Mat(height, width, CV_8UC1, image);
}
}
Upvotes: 1
Reputation: 305
A simple way to do it is:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace System;
using namespace System::Drawing;
int main(array<System::String ^> ^args) {
Bitmap^ img = gcnew Bitmap(10, 10, System::Drawing::Imaging::PixelFormat::Format24bppRgb);
// or: Bitmap^ img = gcnew Bitmap("input_image_file_name");
System::Drawing::Rectangle blank = System::Drawing::Rectangle(0, 0, img->Width, img->Height);
System::Drawing::Imaging::BitmapData^ bmpdata = img->LockBits(blank, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format24bppRgb);
cv::Mat cv_img(cv::Size(img->Width, img->Height), CV_8UC3, bmpdata->Scan0.ToPointer(), cv::Mat::AUTO_STEP);
img->UnlockBits(bmpdata);
cv::imwrite("image.png", cv_img);
return 0;
}
BTW, it is worth to mention in the question that you are working with C++/CLI.
Upvotes: 3