如何将Bitmap对象转换为Mat对象(opencv)?

时间:2017-02-24 11:09:11

标签: c# c++ opencv bitmap mat

我需要将一个Bitmap传递给使用opencv在C ++中创建的dll。在dll中我使用Mat对象来处理图像。我想知道如何将Bitmap对象更改为Mat对象。我尝试使用IntPtr,但我不知道如何构建Mat对象,因为Mat构造函数不支持IntPtr。有谁知道我该怎么做?如果你能用一段代码帮助我,那将是最好的。感谢。

2 个答案:

答案 0 :(得分:1)

感谢您的帮助! 我发现了另一种方法。检查我的代码: 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);
 }
}

答案 1 :(得分:0)

一种简单的方法是:

#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的问题中值得一提。