【问题标题】:How do I transform Bitmap object into Mat object(opencv)?如何将位图对象转换为 Mat 对象(opencv)?
【发布时间】:2017-07-15 04:43:37
【问题描述】:
我需要将位图传递给使用 opencv 在 C++ 中创建的 dll。在 dll 中,我使用 Mat 对象来处理图像。我想知道如何将 Bitmap 对象更改为 Mat 对象。我尝试使用 IntPtr,但我不知道如何构建 Mat 对象,因为 Mat 构造函数不支持 IntPtr。有谁知道我该怎么做?最好能帮我写一段代码。谢谢。
【问题讨论】:
标签:
c#
opencv
bitmap
c++-cli
mat
【解决方案1】:
一个简单的方法是:
#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 的问题中值得一提。
【解决方案2】:
感谢您的帮助!
我找到了另一种方法。检查我的代码:
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);
}
}