如何将IntPtr类型转为Image类型

在用emgu的cvDisTransform函数时,除了简单的街区距离,其余距离都要求目标图为32位图像,因此,采用IntPtr dst = CvInvoke.cvCreateImage(CvInvoke.cvGetSize(src), Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_32F, 1);创建目标图像,但是,如何将dst保存到Image里边呢?

方案一:

利用marshal.copy方法,将dst数据拷贝到一个数组中dk中,然后再转化为图像

double[] dk=new double[K];
System.Runtime.InteropServices.Marshal.Copy(dst, dk, 0, dk.Length);   

初次可能成功,但之后会报错,"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."查了一堆资料,大概意思说是因为IntPtr类型的数据不足以赋给dk。如何解决却没找到理想的方法。

方案二:

利用 CvInvoke.cvCopy方法

Image<Gray, Single> timg = new Image<Gray, Single>(width,height);
CvInvoke.cvCopy(dst,timg, IntPtr.Zero);

注意,因为在创建dst时,通道数是1,所以,timg必须为单通道,否则出错。

而当cvCreateImage创建的图像时多通道时,可用cvSetImageCOI设置感兴趣的通道

Image<Gray, float> image = new Image<Gray, float>(open.FileName);
IntPtr complexImage = CvInvoke.cvCreateImage(image.Size, Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_32F, 2);
CvInvoke.cvSetImageCOI(complexImage, 1);
CvInvoke.cvCopy(image, complexImage, IntPtr.Zero);

PS:

CvInvoke.cvSetImageCOI Method

Sets the channel of interest to a given value. Value 0 means that all channels are selected, 1 means that the first channel is selected etc. If ROI is NULL and coi != 0, ROI is allocated.

你可能感兴趣的:(如何将IntPtr类型转为Image类型)