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

时间:2014-03-23 19:27:35

标签: c# webcam aforge webcam-capture

我试图通过我的网络摄像头拍摄快照。 这是我的代码:

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"事件每一分钟。

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

编辑:正如Armen Aghajanyan所说,我在我的代码中添加了计时器。 此计时器每隔一分钟初始化设备对象,将新的Device对象注册到Device_NewFrame事件并启动设备的活动。 在那之后,我在事件的正文中取消注释了这段代码:

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

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

2 个答案:

答案 0 :(得分:2)

我建议使用Timer.Elapsed事件。实施是直截了当的。 http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed(v=vs.110).aspx

答案 1 :(得分:2)

 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

初始化
相关问题