C#中的图像数据传递给C++中的cv::Mat实现方法

本文介绍了一种在C++人脸识别库与C#程序间传递图像数据的有效方法。通过使用BitmapData和字节数组,解决了C#与C库之间的图像数据兼容性问题,实现了图像流的人脸特征值提取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近包装了下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++中进行处理即可.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值