给采集视频的增加人脸

发布时间 2023-09-12 18:09:05作者: 湘灵
 1 static void Main(string[] args)
 2 {
 3     Mat frame = new Mat();
 4     var Capture = new VideoCapture("http://192.168.1.3:4747/video?1280x720"); // 这里是DroidCam手机端的IP地址和端口号 ?1280x720
 5     Console.WriteLine($"摄像头是否打开:{Capture.IsOpened()}");
 6     //声明窗口
 7     Cv2.NamedWindow("video", WindowFlags.KeepRatio);
 8     Cv2.ResizeWindow("video", 1280, 720);
 9 
10     //加载人眼、人脸模型数据
11     CascadeClassifier faceFinder = new CascadeClassifier(@"haarcascades\haarcascade_frontalface_default.xml");
12     CascadeClassifier eyeFinder = new CascadeClassifier(@"haarcascades\haarcascade_eye_tree_eyeglasses.xml");
13     var Count = new ConcurrentDictionary<long, int>();
14     long PreviousTime = 0;
15     long FPS = 0;
16     while (true)
17     {
18         bool res = Capture.Read(frame);//会阻塞线程
19         if (!res || frame.Empty())
20         {
21             continue;
22         }
23         var times = GettimeStamp();
24         if (PreviousTime != times && Count.ContainsKey(times - 1))
25         {
26             PreviousTime = times;
27             FPS = Count[times - 1];
28             Console.WriteLine($"每秒处理图片:{FPS}帧");
29         }
30         Count.AddOrUpdate(times, 1, (k, v) => v + 1);
31 
32         Cv2.PutText(frame, $"{FPS}", new Point(10, 70), HersheyFonts.HersheyPlain, 4, new Scalar(0, 0, 255), 3);
33         //进行检测识别
34         Rect[] faceRects = faceFinder.DetectMultiScale(frame);
35         Rect[] eyeRects = eyeFinder.DetectMultiScale(frame);
36         //如果有检测到,就绘制结果到图像上
37         if (faceRects.Length > 0)
38         {
39             Cv2.Rectangle(frame, faceRects[0], new Scalar(0, 0, 255), 3);
40         }
41         if (eyeRects.Length > 1)
42         {
43             Cv2.Rectangle(frame, eyeRects[0], new Scalar(255, 0, 0), 3);
44             Cv2.Rectangle(frame, eyeRects[1], new Scalar(255, 0, 0), 3);
45         }
46         //显示结果
47         Cv2.ImShow("video", frame);
48         Cv2.WaitKey(1);
49         //省略几个以加快图像的速度
50         Capture.Grab();
51         Capture.Grab();
52         Capture.Grab();
53         Capture.Grab();
54     }
55     Capture.Release();
56     //销毁所有的窗口
57     Cv2.DestroyAllWindows();
58     Console.WriteLine("录制完毕!");
59     Console.ReadLine();
60 }