http://www.cnblogs.com/xrwang/archive/2010/01/26/TheInteractionOfOpenCv-EmguCvANDDotNet.html

前言

在.net中使用OpenCv和EmguCv时,必须在三者支持的图像格式之间进行转换。.net中用Bitmap类来承载图像,OpenCv中用IplImage指针来承载图像,EmguCv中用Image<TColor,TDepth>来承载图像。本文主要讲述如何在IplImage、Image<TColor,TDepth>和Bitmap之间转换。

IplImage  <=>  MIplImage

MIplImage是IplImage中的托管实现,它是.net与OpenCv之间沟通的桥梁。IplImage指针和MIplImage之间的转换主要用到了Marshal类中的PtrToStructure、StructureToPtr、AllocHGlobal和FreeHGlobal这几个静态方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/// <summary>
/// 将MIplImage结构转换到IplImage指针;
/// 注意:指针在使用完之后必须用Marshal.FreeHGlobal方法释放。
/// </summary>
/// <param name="mi">MIplImage对象</param>
/// <returns>返回IplImage指针</returns>
public static IntPtr MIplImageToIplImagePointer(MIplImage mi)
{
    IntPtr ptr = Marshal.AllocHGlobal(mi.nSize);
    Marshal.StructureToPtr(mi, ptr, false);
    return ptr;
}
 
/// <summary>
/// 将IplImage指针转换成MIplImage结构
/// </summary>
/// <param name="ptr">IplImage指针</param>
/// <returns>返回MIplImage结构</returns>
public static MIplImage IplImagePointerToMIplImage(IntPtr ptr)
{
    return (MIplImage)Marshal.PtrToStructure(ptr, typeof(MIplImage));
}

需要注意的是,不能使用 MIplImage * pmi=(MIplImage *)ptr.ToPointer();  和  IntPtr ptr=&mi; 之类的写法。

IplImage  <=>  Image<TColor,TDepth>

用了MIplImage的辅助,我们可以很容易实现IplImage指针和Image<TColor,TDepth>之间的转换。

        /// <summary>
/// 将IplImage指针转换成Emgucv中的Image对象;
/// 注意:这里需要您自己根据IplImage中的depth和nChannels来决定
/// </summary>
/// <typeparam name="TColor">Color type of this image (either Gray, Bgr, Bgra, Hsv, Hls, Lab, Luv, Xyz or Ycc)</typeparam>
/// <typeparam name="TDepth">Depth of this image (either Byte, SByte, Single, double, UInt16, Int16 or Int32)</typeparam>
/// <param name="ptr">IplImage指针</param>
/// <returns>返回Image对象</returns>
public static Image<TColor, TDepth> IplImagePointerToEmgucvImage<TColor, TDepth>(IntPtr ptr)
where TColor : struct, IColor
where TDepth : new()
{
MIplImage mi = IplImagePointerToMIplImage(ptr);
return new Image<TColor, TDepth>(mi.width, mi.height, mi.widthStep, mi.imageData);
} /// <summary>
/// 将IplImage指针转换成Emgucv中的IImage接口;
/// 1通道对应灰度图像,3通道对应BGR图像,4通道对应BGRA图像。
/// 注意:3通道可能并非BGR图像,而是HLS,HSV等图像
/// </summary>
/// <param name="ptr">IplImage指针</param>
/// <returns>返回IImage接口</returns>
public static IImage IplImagePointToEmgucvIImage(IntPtr ptr)
{
MIplImage mi = IplImagePointerToMIplImage(ptr);
Type tColor;
Type tDepth;
string unsupportedDepth = "不支持的像素位深度IPL_DEPTH";
string unsupportedChannels = "不支持的通道数(仅支持1,2,4通道)";
switch (mi.nChannels)
{
case 1:
tColor = typeof(Gray);
switch (mi.depth)
{
case IPL_DEPTH.IPL_DEPTH_8U:
tDepth = typeof(Byte);
return new Image<Gray, Byte>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_16U:
tDepth=typeof(UInt16);
return new Image<Gray, UInt16>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_16S:
tDepth = typeof(Int16);
return new Image<Gray, Int16>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_32S:
tDepth = typeof(Int32);
return new Image<Gray, Int32>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_32F:
tDepth = typeof(Single);
return new Image<Gray, Single>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_64F:
tDepth = typeof(Double);
return new Image<Gray, Double>(mi.width, mi.height, mi.widthStep, mi.imageData);
default:
throw new NotImplementedException(unsupportedDepth);
}
case 3:
tColor = typeof(Bgr);
switch (mi.depth)
{
case IPL_DEPTH.IPL_DEPTH_8U:
tDepth = typeof(Byte);
return new Image<Bgr, Byte>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_16U:
tDepth = typeof(UInt16);
return new Image<Bgr, UInt16>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_16S:
tDepth = typeof(Int16);
return new Image<Bgr, Int16>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_32S:
tDepth = typeof(Int32);
return new Image<Bgr, Int32>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_32F:
tDepth = typeof(Single);
return new Image<Bgr, Single>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_64F:
tDepth = typeof(Double);
return new Image<Bgr, Double>(mi.width, mi.height, mi.widthStep, mi.imageData);
default:
throw new NotImplementedException(unsupportedDepth);
}
case 4:
tColor = typeof(Bgra);
switch (mi.depth)
{
case IPL_DEPTH.IPL_DEPTH_8U:
tDepth = typeof(Byte);
return new Image<Bgra, Byte>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_16U:
tDepth = typeof(UInt16);
return new Image<Bgra, UInt16>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_16S:
tDepth = typeof(Int16);
return new Image<Bgra, Int16>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_32S:
tDepth = typeof(Int32);
return new Image<Bgra, Int32>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_32F:
tDepth = typeof(Single);
return new Image<Bgra, Single>(mi.width, mi.height, mi.widthStep, mi.imageData);
case IPL_DEPTH.IPL_DEPTH_64F:
tDepth = typeof(Double);
return new Image<Bgra, Double>(mi.width, mi.height, mi.widthStep, mi.imageData);
default:
throw new NotImplementedException(unsupportedDepth);
}
default:
throw new NotImplementedException(unsupportedChannels);
}
} /// <summary>
/// 将Emgucv中的Image对象转换成IplImage指针;
/// </summary>
/// <typeparam name="TColor">Color type of this image (either Gray, Bgr, Bgra, Hsv, Hls, Lab, Luv, Xyz or Ycc)</typeparam>
/// <typeparam name="TDepth">Depth of this image (either Byte, SByte, Single, double, UInt16, Int16 or Int32)</typeparam>
/// <param name="image">Image对象</param>
/// <returns>返回IplImage指针</returns>
public static IntPtr EmgucvImageToIplImagePointer<TColor, TDepth>(Image<TColor, TDepth> image)
where TColor : struct, IColor
where TDepth : new()
{
return image.Ptr;//IplImage*,CvCapture*等指针在C#中都用IntPtr来代替,且其中没有cvGetMCvSize函数,故用cvGetImageROI来暂时代替
}

Image<TColor,TDepth>  <=>  Bitmap

EmguCv中已经实现了这二者之间的转换,分别是Image<TColor,TDepth>类的下列成员:

(1)public Bitmap Bitmap { get; set; }

该属性可以获取或者设置位图;对于Image<Gray, Byte>, Image<Bgr, Byte> 和 Image<Bgra, Byte>这三种情况效率很高,因为Image<TColor,TDepth>和Bitmap共享数据内存。

(2)public Bitmap ToBitmap(int width,int height)及public Bitmap ToBitmap()方法

(3)public Image(Bitmap bmp)
(4)public Image(int width,int height,int stride,IntPtr scan0)
这个构造函数几乎是万能的,只要您清楚图像的内存分布,以及想要的目的。
 
IplImage  <=>  Bitmap
    IplImage指针和Bitmap间的转换有两种方式,第一种是利用Image<TColor,TDepth>作媒介;第二种是自己写转换的方法,例如我写的下列代码:
        /// <summary>
/// 将IplImage指针转换成位图对象;
/// 对于不支持的像素格式,可以先使用cvCvtColor函数转换成支持的图像指针
/// </summary>
/// <param name="ptr">IplImage指针</param>
/// <returns>返回位图对象</returns>
public static Bitmap IplImagePointerToBitmap(IntPtr ptr)
{
MIplImage mi = IplImagePointerToMIplImage(ptr);
PixelFormat pixelFormat; //像素格式
string unsupportedDepth = "不支持的像素位深度IPL_DEPTH";
string unsupportedChannels = "不支持的通道数(仅支持1,2,4通道)";
switch(mi.nChannels)
{
case 1:
switch (mi.depth)
{
case IPL_DEPTH.IPL_DEPTH_8U:
pixelFormat = PixelFormat.Format8bppIndexed;
break;
case IPL_DEPTH.IPL_DEPTH_16U:
pixelFormat = PixelFormat.Format16bppGrayScale;
break;
default:
throw new NotImplementedException(unsupportedDepth);
}
break;
case 3:
switch (mi.depth)
{
case IPL_DEPTH.IPL_DEPTH_8U:
pixelFormat = PixelFormat.Format24bppRgb;
break;
case IPL_DEPTH.IPL_DEPTH_16U:
pixelFormat = PixelFormat.Format48bppRgb;
break;
default:
throw new NotImplementedException(unsupportedDepth);
}
break;
case 4:
switch (mi.depth)
{
case IPL_DEPTH.IPL_DEPTH_8U:
pixelFormat = PixelFormat.Format32bppArgb;
break;
case IPL_DEPTH.IPL_DEPTH_16U:
pixelFormat = PixelFormat.Format64bppArgb;
break;
default:
throw new NotImplementedException(unsupportedDepth);
}
break;
default:
throw new NotImplementedException(unsupportedChannels); }
Bitmap bitmap = new Bitmap(mi.width, mi.height, mi.widthStep, pixelFormat, mi.imageData);
//对于灰度图像,还要修改调色板
if (pixelFormat == PixelFormat.Format8bppIndexed)
SetColorPaletteOfGrayscaleBitmap(bitmap);
return bitmap;
} /// <summary>
/// 将位图转换成IplImage指针
/// </summary>
/// <param name="bitmap">位图对象</param>
/// <returns>返回IplImage指针</returns>
public static IntPtr BitmapToIplImagePointer(Bitmap bitmap)
{
IImage iimage = null;
switch (bitmap.PixelFormat)
{
case PixelFormat.Format8bppIndexed:
iimage = new Image<Gray, Byte>(bitmap);
break;
case PixelFormat.Format16bppGrayScale:
iimage = new Image<Gray, UInt16>(bitmap);
break;
case PixelFormat.Format24bppRgb:
iimage = new Image<Bgr, Byte>(bitmap);
break;
case PixelFormat.Format32bppArgb:
iimage = new Image<Bgra, Byte>(bitmap);
break;
case PixelFormat.Format48bppRgb:
iimage = new Image<Bgr, UInt16>(bitmap);
break;
case PixelFormat.Format64bppArgb:
iimage = new Image<Bgra, UInt16>(bitmap);
break;
default:
Image<Bgra, Byte> tmp1 = new Image<Bgra, Byte>(bitmap.Size);
Byte[, ,] data = tmp1.Data;
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
Color color = bitmap.GetPixel(i, j);
data[j, i, 0] = color.B;
data[j, i, 1] = color.G;
data[j, i, 2] = color.R;
data[j, i, 3] = color.A;
}
}
iimage = tmp1;
break;
}
return iimage.Ptr;
} /// <summary>
/// 设置256级灰度位图的调色板
/// </summary>
/// <param name="bitmap"></param>
public static void SetColorPaletteOfGrayscaleBitmap(Bitmap bitmap)
{
PixelFormat pixelFormat = bitmap.PixelFormat;
if (pixelFormat == PixelFormat.Format8bppIndexed)
{
ColorPalette palette = bitmap.Palette;
for (int i = 0; i < palette.Entries.Length; i++)
palette.Entries[i] = Color.FromArgb(255, i, i, i);
bitmap.Palette = palette;
}
}

OpenCv,EmguCv及.net之间的互动(The Interaction of OpenCv, EmguCv AND .net)的更多相关文章

  1. 在Visual Studio中使用序列图描述对象之间的互动

    当需要描述多个对象之间的互动,可以考虑使用序列图. 在建模项目下添加一个名称为"Basic Flow"的序列图. 比如描述客户是如何在MVC下获取到视图信息的. 备注: ● 通常是 ...

  2. Opencv入门-第一回-梦牵机器视觉翼,初识Opencv域(安装Opencv)

    各位看官,您是不是瞅着Opencv进来的?(你这不是废话吗>_>) 这Opencv(开源计算机视觉库)啊,说来话长,最初是上个世纪末(1999年)由Intel建立起来的.近十多年人工智能这 ...

  3. OpenCV Mat与UIImage之间的转换

    UIImage 转 OpenCV cvMat: - (cv::Mat)cvMatWithImage:(UIImage *)image { CGColorSpaceRef colorSpace = CG ...

  4. 【前端学习笔记】ajax与php之间的互动

    ajax通常会牵扯到跨域问题,所以我们通常的解决方案是,通过ajax将参数传到后台php文件中 在后台通过php文件进行跨域访问api,再将结果返回到ajax响应中.需要注意一下几点: 1.可以通过& ...

  5. OpenCV实现的高斯滤波探究_1(《学习OpenCV》练习题第五章第三题ab部分)

    首先看下OpenCV 官方文档对于cvSmooth各个参数的解释: Smooths the image in one of several ways. C: void cvSmooth(const C ...

  6. 基于opencv的gpu与cpu对比程序,代码来自opencv的文档中

    原文链接: http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/gpu/gpu-basics-similarity/gpu-basi ...

  7. OpenCV学习笔记(01)我的第一个OpenCV程序(环境配置)

    昨天刚刚考完编译原理,私心想着可以做一些与考试无关的东西了.一直想做和图像处理相关的东西,趁这段时间有空学习一下OpenCV,搭建环境真是一件麻烦的事情,搞了近三个小时终于OK了.先来张图: 大致描述 ...

  8. 快速遍历OpenCV Mat图像数据的多种方法和性能分析 | opencv mat for loop

    本文首发于个人博客https://kezunlin.me/post/61d55ab4/,欢迎阅读! opencv mat for loop Series Part 1: compile opencv ...

  9. 浅入浅出EmguCv(一)OpenCv与EmguCv

    最近接触计算机视觉方面的东西,于是准备下手学习opencv,从官网下载windows的安装版,配置环境,一系列步骤走完后,准备按照惯例弄个HelloWord.也就是按照网上的教程,打开了那个图像处理领 ...

随机推荐

  1. nginx命令

    window  cmd 到nginx的文件夹 start nginx    启动命令 nginx -s reload 重新启动 nginx -s stop   关闭   linux   到 sbin ...

  2. BZOJ1798——[Ahoi2009]Seq维护序列seq

    1.题目大意:区间修改乘法操作和加法操作,求区间和 2.分析:为了填补bzoj2631的坑还是写一发题解吧,首先呢,既然想要双标记,但是这两个标记之间又有着制约作用,所以要定义优先级,这个优先级就定义 ...

  3. iTool拷贝app到电脑上

    iTool拷贝app到电脑上 方法一. iTool找到你的app, 归档在桌面, 桌面就生成了ipa, 其实ipa是一个压缩包, 使用解压软件解压之后 生成Payload文件夹, 点开就可以看到Clo ...

  4. 说说JSON和JSONP,也许你会豁然开朗

    前言 由于Sencha Touch 2这种开发模式的特性,基本决定了它原生的数据交互行为几乎只能通过AJAX来实现. 当然了,通过调用强大的PhoneGap插件然后打包,你可以实现100%的Socke ...

  5. Hashtable和HashMap类的区别

    Hashtable和HashMap类有三个重要的不同之处.第一个不同主要是历史原因.Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现. ...

  6. 一个CMS案例实战讲解PHP代码审计入门

    前言 php代码审计介绍:顾名思义就是检查php源代码中的缺点和错误信息,分析并找到这些问题引发的安全漏洞. 1.环境搭建: 工欲善其事必先利其器,先介绍代码审计必要的环境搭建 审计环境 window ...

  7. ndk学习5: ndk中使用c++

    默认情况下ndk不支持标准C++库,异常, rtti等   在ndk文档有关于C++ support的详细介绍   一. 使用C++标准库 介绍: 默认是使用最小额度的C++运行时库, 在Applic ...

  8. mysql导入导出数据库命令

    1.导出数据库:mysqldump -u 用户名 -p 数据库名 > 导出的文件名 如我输入的命令行: mysqldump -u root -p news > /home/jason/sq ...

  9. 【GoLang】转载:我为什么放弃Go语言,哈哈

    我为什么放弃Go语言 作者:庄晓立(Liigo) 日期:2014年3月 原创链接:http://blog.csdn.NET/liigo/article/details/23699459 转载请注明出处 ...

  10. 用Kibana和logstash快速搭建实时日志查询、收集与分析系统

    Logstash是一个完全开源的工具,他可以对你的日志进行收集.分析,并将其存储供以后使用(如,搜索),您可以使用它.说到搜索,logstash带有一个web界面,搜索和展示所有日志. kibana ...