请问C#+openCV问题
请问我下边这段代码怎么总是出错呢?总是出现这样的错误:MIplImage img =(MIplImage)Marshal.PtrToStructure(src, typeof(MIplImage));-----未将对象引用设置到对象实例?
这段代码是实现IntPtr向Image<>类型的转化。
public Image ShowIplImageInWindow(IntPtr src)
{
MIplImage img =(MIplImage)Marshal.PtrToStructure(src, typeof(MIplImage));
Bitmap disp = new Bitmap(img.width, img.height, PixelFormat.Format24bppRgb);
BitmapData bmp = disp.LockBits(new Rectangle(0, 0, img.width, img.height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
long linebytes = (img.width * 24 + 31) / 32 * 4;
unsafe
{
byte* pixel = (byte*)bmp.Scan0.ToPointer();
if (img.nChannels == 3)
{
for (int i = 0; i < img.height; i++)
{
for (int j = 0, n = 0; j < img.width; j++, n++)
{
byte b = ((byte*)img.imageData + img.widthStep * i)[3 * j];
byte g = ((byte*)img.imageData + img.widthStep * i)[3 * j + 1];
byte r = ((byte*)img.imageData + img.widthStep * i)[3 * j + 2];
*(pixel + linebytes * (i) + n) = b;
n++;
*(pixel + linebytes * (i) + n) = g;
n++;
*(pixel + linebytes * (i) + n) = r;
}
}
}
else if (img.nChannels == 1)
{
for (int i = 0; i < img.height; i++)
{
for (int j = 0, n = 0; j < img.width; j++, n++)
{
byte g = ((byte*)img.imageData + img.widthStep * i)[j];
*(pixel + linebytes * (i) + n) = g;
n++;
*(pixel + linebytes * (i) + n) = g;
n++;
*(pixel + linebytes * (i) + n) = g;
}
}
}
else
{
return null;
}
}
disp.UnlockBits(bmp);
return (Image)disp;
}