c# – 从视频获取图像

前端之家收集整理的这篇文章主要介绍了c# – 从视频获取图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个应用程序,可以访问连接到PC的摄像头,录制视频并从视频中获取图像.我使用AForge.NET库访问摄像机: http://www.aforgenet.com/framework/

我不知道如何命名为AForge.Video.NewFrameEventHandler的事件.在此代码中,事件将返回空值到位图而不是视频中的新帧,或者事件不被调用.我想要将帧从视频到每帧的图片框,以便像视频流一样,点击停止按钮后,我想让最后一张图像保持显示图片框中.有人知道吗为什么我的代码不工作?

码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using AForge.Video.DirectShow;
  6. using System.Drawing;
  7. using AForge.Video;
  8.  
  9. namespace CameraDevice
  10. {
  11. public class CameraImaging
  12. {
  13. // enumerate video devices
  14. public FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice );
  15. //camera
  16. public VideoCaptureDevice videoSource;
  17. //screen shot
  18. public Bitmap bitmap;
  19. public CameraImaging()
  20. {
  21. // create video source
  22. VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString );
  23. // set NewFrame event handler
  24. videoSource.NewFrame += new NewFrameEventHandler( video_NewFrame );
  25. }
  26. public void StartVideo(VideoCaptureDevice videoSource)
  27. {
  28. // start the video source
  29. videoSource.Start();
  30. // ...
  31. }
  32. public void StopVideo(VideoCaptureDevice videoSource)
  33. {
  34. // stop the video source
  35. videoSource.Stop();
  36. // ...
  37. }
  38. private void video_NewFrame( object sender,NewFrameEventArgs eventArgs )
  39. {
  40. // get new frame
  41. bitmap = eventArgs.Frame;
  42. // process the frame
  43. }
  44. }
  45. }

类似的代码在这里:http://www.aforgenet.com/framework/features/directshow_video.html[ ^]

在Windows窗体我运行这个视频在一个线程,这样做:

  1. private void VideoRecording()
  2. {
  3. camImg.videoSource.Start();
  4.  
  5. while (!StopVideo)
  6. {
  7. pictureBox1.Image = camImg.bitmap;
  8. pictureBox1.Invalidate();
  9. }
  10. camImg.videoSource.Stop();
  11.  
  12. }

解决方法

@H_404_17@ 如果我记得正确,位图需要立即被复制,因为它在事件之后被覆盖.使用参考在这里是不好的.尝试像:
  1. private void video_NewFrame( object sender,NewFrameEventArgs eventArgs )
  2. {
  3. // copy the new frame
  4. bitmap = new Bitmap(eventArgs.Frame);
  5. // process the frame
  6. }

要么

  1. private void video_NewFrame( object sender,NewFrameEventArgs eventArgs )
  2. {
  3. // clone new frame
  4. bitmap = eventArgs.Frame.Clone();
  5. // process the frame
  6. }

此外,您不应该为此使用额外的线程,AForge已经这样做了.

>呼叫开始(例如在加载事件中或按下按钮之后)
>处理框架事件

private void VideoStream_NewFrame(object sender,AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap newFrame = new Bitmap(eventArgs.Frame);
pictureBox1.Image = newFrame;
}
>呼叫停止(关闭事件或按钮)

如果遇到WinForm控件的问题,例如您需要知道这些控件是在另一个线程上创建的标签,您需要使用Invoke.例如:

  1. label_ms.Invoke((MethodInvoker)(() => label_ms.Text = msTimeSpan.TotalMilliseconds.ToString()));

最好的办法是查看框架附带的AForge样本:
http://aforge.googlecode.com/svn/trunk/Samples/Video/Player/

猜你在找的C#相关文章