学习了基于OpenCvSharp获取摄像头数据,同时学习了基于ViewFaceCore的人脸识别用法,将这两者结合即是从摄像头中识别人脸。本文测试测试C#调用OpenCvSharp和ViewFaceCore从摄像头中识别人脸,并进行人脸红框标记。
新建Winform项目,在Nuget包管理器其中添加以下包:
Hompus.VideoInputDevices
DirectShowLib.Standard
OpenCvSharp4
OpenCvSharp4.Extensions
OpenCvSharp4.runtime.win
ViewFaceCore
ViewFaceCore.all_models
ViewFaceCore.Extension.SkiaSharp
ViewFaceCore.runtime.win.x64
关键代码如下所示,通过OpenCvSharp从摄像头获取图片后,调用ViewFaceCore模块识别图片中的人脸,并用红框标记人脸,最后显示图片。
m_capture.Read(m_image);if (m_image.Empty())return;Bitmap image= OpenCvSharp.Extensions.BitmapConverter.ToBitmap(m_image);var bitmap = SKBitmap.Decode(m_image.ToBytes());
FaceDetector faceDetector = new FaceDetector();FaceLandmarkConfig config = new FaceLandmarkConfig();
config.MarkType = MarkType.Normal;FaceLandmarker faceMark = new FaceLandmarker(config);FaceInfo[] infos = faceDetector.Detect(bitmap);using(Graphics graphics = Graphics.FromImage(image))
{for (int i = 0; i < infos.Length; i++){graphics.DrawRectangle(Pens.Red,infos[i].Location.X,infos[i].Location.Y,infos[i].Location.Width,infos[i].Location.Height);}
} faceDetector.Dispose();
faceMark.Dispose();pictureBox1.Image = image;
最后是程序运行效果,在手机的B站上找了“花都兄弟”的视频,对着摄像头播放,可以看到能够识别到人脸并标记。
参考文献:
[1]https://github.com/ViewFaceCore/ViewFaceCore
[2]https://github.com/shimat/opencvsharp
[3]https://www.bilibili.com/video/BV1Je411p7BQ/?spm_id_from=333.337.search-card.all.click