最近包装了下C++的人脸识别库以供C#程序调用, 遇到了C#与C库中的图像数据传递的问题, 下面说下解决办法:
C++库中的实现方法为:
/**
* Comments: 获取图像流的人脸特征值
* @Param aWidth: 图像宽度
* @Param aHeight: 图像高度
* @Param aChannel: 图像通道数 灰度图为1, RGB为3 ARGB为4
* @Param aBytes: 图像数据
* @Param aFeatures: [输出] 检测到人脸则输出该人脸的特征值
* @Return void
*/
bool SxFace_GetStreamFeature(int aWidth, int aHeight, int aChannel, unsigned char* aBytes, float* aFeatures)
{
if (!mActived)
{
return false;
}
// DEBUG_W("Height: %d, Width: %d, Bytes: %02X %02X.", aHeight, aWidth, aBytes[0], aBytes[1]);
Mat frame(aHeight, aWidth, CV_MAKETYPE(CV_8U, aChannel), aBytes);
// cv::imwrite("./test.jpg", frame);
return SxFace_GetFeature(frame, aFeatures);
}
通过字节数组将图像数据传递给库, 下面看下C#中的实现:
在C#中声明调用的方法:
/// <summary>
/// 获取图像流的人脸特征值
/// </summary>
/// <param name="aWidth">图像宽度</param>
/// <param name="aHeight">图像高度</param>
/// <param name="aChannel">图像通道数</param>
/// <param name="aBytes">图像数据</param>
/// <param name="aFeatures">识别到人脸返回人脸特征值</param>
/// <returns>识别成功与否</returns>
[DllImport("SxModule.FaceId.dll", EntryPoint = "SxFace_GetStreamFeature", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool GetStreamFeature(int aWidth, int aHeight, int aChannel, IntPtr aBytes, float[] aFeatures);
调用时需要用到BitmapData类, 下面是调用方法:
Bitmap bitmap = new Bitmap(img);
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
int channel = 4;
if (bitmap.PixelFormat == PixelFormat.Format8bppIndexed)
{
channel = 1;
}
else if (bitmap.PixelFormat == PixelFormat.Format24bppRgb)
{
channel = 3;
}
else if (bitmap.PixelFormat == PixelFormat.Format32bppArgb)
{
channel = 4;
}
float[] feature = new float[mFeatureDims];
SxFaceMethods.GetStreamFeature(img.Width, img.Height, channel, data.Scan0, feature);
bitmap.UnlockBits(data);
通过BitmapData去传递图片数据, C++中进行处理即可.