如何从网络摄像头拍照每一分钟

本文关键字:一分钟 摄像头 网络 | 更新日期: 2023-09-27 17:52:38

我想用我的网络摄像头拍一张快照。这是我的代码:

using System;
using System.Text;
using System.Drawing;
using System.Threading;
using AForge.Video.DirectShow;
using AForge.Video;
namespace WebCamShot
{
    class Program
    {
        static FilterInfoCollection WebcamColl;
        static VideoCaptureDevice Device;
        static void Main(string[] args)
        {
            WebcamColl = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            Console.WriteLine("Press Any Key To Capture Photo !");
            Console.ReadKey();
            Device = new VideoCaptureDevice(WebcamColl[0].MonikerString);
            Device.NewFrame += Device_NewFrame;
            Device.Start();
            Console.ReadLine();
        }
        static void Device_NewFrame(object sender, NewFrameEventArgs e)
        {
            Bitmap Bmp = (Bitmap)e.Frame.Clone();
            Bmp.Save("D:''Foo''Bar.png");
            Console.WriteLine("Snapshot Saved.");
            /*
            Console.WriteLine("Stopping ...");
            Device.SignalToStop();
            Console.WriteLine("Stopped .");
            */
        }
    }
}

它工作得很好,但是现在我想用我的代码每隔一分钟拍一次快照。

由于这个原因,我添加了这行代码:Thread.Sleep(1000 * 60); // 1000 Milliseconds (1 Second) * 60 == One minute.

不幸的是,这一行没有给我想要的结果-它仍然像前面一样拍摄快照,但它只是每分钟在文件中保存照片。我真正想做的是,我的代码将触发"Device_NewFrame"事件每隔一分钟。

我该怎么做?我很乐意得到一些帮助。谢谢你!

EDIT:按照Armen Aghajanyan的建议,我在代码中添加了计时器。该定时器每隔一分钟初始化设备对象,将新的设备对象注册到Device_NewFrame事件并启动设备的活动。之后,我取消了事件主体中的注释:

Console.WriteLine("Stopping ...");
Device.SignalToStop();
Console.WriteLine("Stopped .");

现在代码每隔一分钟快照一次

如何从网络摄像头拍照每一分钟

我建议使用Timer。运行事件。实现是直接的和干净的。http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed (v = vs.110) . aspx

 private static void TimerThread(object obj)
    {
        int delay = (int)obj;
        while (true)
        {
            takePhotos = true;
            Thread.Sleep(delay);
        }
    }
static void Main(string[] args)
    {
        WebcamColl = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        Console.WriteLine("Press Any Key To Capture Photo !");
        Console.ReadKey();
        Device = new VideoCaptureDevice(WebcamColl[0].MonikerString);
        Device.NewFrame += Device_NewFrame;
        Device.Start();
        Thread timer=new Thread(TimerThread);
         timer.Start(60000);
        Console.ReadLine();
    }
    static void Device_NewFrame(object sender, NewFrameEventArgs e)
    {
       if(!takePhotos)return;
        Bitmap Bmp = (Bitmap)e.Frame.Clone();
        Bmp.Save("D:''Foo''Bar.png");
        takePhotos=false;
        Console.WriteLine("Snapshot Saved.");
        /*
        Console.WriteLine("Stopping ...");
        Device.SignalToStop();
        Console.WriteLine("Stopped .");
        */
    }

声明一个静态变量takePhotos并初始化为true