赞
踩
在网上有很多关于这方面的博客,但是都没有说完整,按照他们的博客做下来代码都不能跑。所以我就自己写个博客补充一下
我这使用的.NET框架版本是 .NetFramework4.7.1
使用Nuget安装这两个程序包就够了,不需要其他的配置
一定要安装OpenCvSharp4.runtime.win 否则运行后会报错
对单个图片进行人脸识别:
- string path = "D:\\素材\\R-C (1).jpg"; //aaaa.mp4
- Mat srcImg = Cv2.ImRead(path, (ImreadModes)1);
-
- //加载人眼、人脸模型数据
- OpenCvSharp.CascadeClassifier faceFinder = new CascadeClassifier(@"G:\baiduDownload\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml");
- OpenCvSharp.CascadeClassifier eyeFinder = new CascadeClassifier(@"G:\baiduDownload\opencv\sources\data\haarcascades\haarcascade_eye_tree_eyeglasses.xml");
- //进行检测识别
- Rect[] faceRects = faceFinder.DetectMultiScale(srcImg);
- Rect[] eyeRects = eyeFinder.DetectMultiScale(srcImg);
- //如果有检测到,就绘制结果到图像上
- if (faceRects.Length > 0)
- {
- Cv2.Rectangle(srcImg, faceRects[0], new Scalar(0, 0, 255), 3);
- }
- if (eyeRects.Length > 1)
- {
- Cv2.Rectangle(srcImg, eyeRects[0], new Scalar(255, 0, 0), 3);
- Cv2.Rectangle(srcImg, eyeRects[1], new Scalar(255, 0, 0), 3);
- }
- //显示结果
- Cv2.ImShow("showImg", srcImg);
- Cv2.WaitKey(1);
对摄像头的画面或者本地视频画面进行人脸识别:
- //读取本地的视频
- FrameSource video = Cv2.CreateFrameSource_Video("D:\\素材\\aaaa.mp4");
-
- //使用摄像头
- //FrameSource video = Cv2.CreateFrameSource_Camera(1);
-
- //声明窗口
- Cv2.NamedWindow("video", WindowFlags.Normal);
- while (true)
- {
- //获取帧
- Mat frame = new Mat();
- video.NextFrame(frame);
- //加载人眼、人脸模型数据
- OpenCvSharp.CascadeClassifier faceFinder = new CascadeClassifier(@"G:\baiduDownload\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml");
- OpenCvSharp.CascadeClassifier eyeFinder = new CascadeClassifier(@"G:\baiduDownload\opencv\sources\data\haarcascades\haarcascade_eye_tree_eyeglasses.xml");
- //进行检测识别
- Rect[] faceRects = faceFinder.DetectMultiScale(frame);
- Rect[] eyeRects = eyeFinder.DetectMultiScale(frame);
- //如果有检测到,就绘制结果到图像上
- if (faceRects.Length > 0)
- {
- Cv2.Rectangle(frame, faceRects[0], new Scalar(0, 0, 255), 3);
- }
- if (eyeRects.Length > 1)
- {
- Cv2.Rectangle(frame, eyeRects[0], new Scalar(255, 0, 0), 3);
- Cv2.Rectangle(frame, eyeRects[1], new Scalar(255, 0, 0), 3);
- }
- //显示结果
- Cv2.ImShow("video", frame);
- Cv2.WaitKey(1);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。