如何将位图对象转换为Mat对象(opencv)?
问题描述:
我需要将位图传递给使用opencv在C++中创建的dll。在dll中,我使用Mat对象来处理图像。我想知道如何将Bitmap对象更改为Mat对象。我尝试使用IntPtr,但我不知道如何构建Mat对象,因为Mat构造函数不支持IntPtr。有谁知道我该怎么做?如果你能用一段代码来帮助我,那将是最好的。谢谢。如何将位图对象转换为Mat对象(opencv)?
答
一个简单的方法来做到这一点是:
#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;
}
顺便说一句,这是值得的,你是用C++/CLI工作的问题就更不用说了。
答
谢谢你的帮助! 我找到了另一种方法来做到这一点。检查我的代码: 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);
}
}
你见过[这](http://docs.opencv.org/java/2.4.9/org/opencv/android/ Utils.html) –