实验室要求使用C#做界面,但是图像处理是用C++的opencv处理的,所以将C++的处理片段打包成dll给c#调用。
C++动态库.h
#ifndef __IMAGE_H__
#define __IMAGE_H__
#ifdef IMAGE_EXPORTS
#define IMAGE_API __declspec(dllexport)
#else
#define IMAGE_API __declspec(dllimport)
#endif
extern "C" IMAGE_API void _stdcall Blur(unsigned char * src, int width, int height, int step);
#endif
C++动态库.cpp
IMAGE_API void _stdcall Blur(unsigned char * src, int width, int height, int step)
{
//生成opencv图像类
Mat img(height, width, CV_8UC3, src, step);
blur(img, img, Size(10, 10));//处理代码段
memcpy(src, img.data, sizeof(unsigned char)*img.rows*img.cols*img.channels());
//指针数据复制
img.release(); //释放内存(其实不用)
}
C#代码段
[DllImport("picture.dll", EntryPoint = "Blur")]
public static extern void Blur(IntPtr img, int width, int height, int step);
private void ImageRead(string path)
{
Bitmap image = null;
using (FileStream fs = File.OpenRead(path))
{ //OpenRead
int filelength = 0;
filelength = (int)fs.Length; //获得文件长度
Byte[] image1 = new Byte[filelength]; //建立一个字节数组
fs.Read(image1, 0, filelength); //按字节流读取
image = (Bitmap)System.Drawing.Image.FromStream(fs);
fs.Close();
}
try
{
//锁定内存变成指针形式
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
//调库
Blur(bitmapData.Scan0, bitmapData.Width, bitmapData.Height, bitmapData.Stride);
//解除锁定内存
image.UnlockBits(bitmapData);
}
catch(Exception e){}
}