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. iOS开发——多线程篇——多线程介绍

    一.进程和线程1.什么是进程进程是指在系统中正在运行的一个应用程序每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内 比如同时打开迅雷.Xcode,系统就会分别启动2个进程 通过“活动监 ...

  2. C++基础知识(1)----文件操作

    参照 小菜鸟上校 的博客 // file operat.cpp : 定义控制台应用程序的入口点. /*上述例子的主要功能是将一个文件的内容复制到另一个文件中, 这个功能主要由一个函数copy来实现.它 ...

  3. Java web中为什么要用Service接口和DAO接口?

    面向接口:依赖倒转原理----使用service接口的原因是为了让表示层不依赖于业务层的具体实现,使用dao接口的原理也是如此,而且便于spring ioc容器,当修改dao层,时不需要修改servi ...

  4. JDBC的应用

    JDBC的开发步骤: 1.  引入JDBC驱动架包 2.  程序中引入JDBC驱动类     3.  创建java与数据库的连接 4.  跟数据库交互:发送sql语句,接收数据库对sql语句的执行结果 ...

  5. pip/matplot/pandas的安装和使用

    pip可以很方便的安装python的各种工具库,如pandas,matplotlib,scikit等,最大优点是它会自动解决库之间的依赖性,把所有需要的库都安装好,比起手工一个一个安装方便多了. 1. ...

  6. 【GoLang】GoLang 错误处理 -- 官方推荐方式 示例

    最严谨的方式,Always检查error,并做相应的处理 项目结构: 代码: common.go: package common import ( "github.com/pkg/error ...

  7. 【云计算】marathon集群如何升级?

    Upgrading to a Newer Version We generally recommend creating a backup of the ZooKeeper state before ...

  8. Tomcat 7最大并发连接数的正确修改方法

    这是个很简单的问题,但是搜了一圈,发现大家都写错了.所以这里总结一下: 几乎所有的中文网页都介绍,要修改Tomcat的默认最大并发连接数,应该进行如下设置(实际上这些步骤是错误的): -------- ...

  9. C#中堆和栈的区别分析

    线程堆栈:简称栈 Stack托管堆: 简称堆 Heap 使用.Net框架开发程序的时候,我们无需关心内存分配问题,因为有GC这个大管家给我们料理一切.如果我们写出如下两段代码: 1 代码段1: 2 3 ...

  10. HTML文档中头部文件介绍

    meta是用来在模拟HTTP协议的响应头报文.meta 标签用于网页的<head>与</head>中,meta 标签的用处很多.meta 的属性有两种:name和http-eq ...