我想使用相机拍摄网络摄像头。为此,我使用了2个引用:AForge.Video.dll
和AForge.Video.DirectShow.dll
。
Here's我发现了一个片段:
public FilterInfoCollection CamsCollection;
public VideoCaptureDevice Cam = null;
void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
frameholder.Source = (Bitmap)eventArgs.Frame.Clone();
/* ^
* Here it cannot convert implicitly from System.Drawing.Bitmap to
* System.Windows.Media.ImageSource
*/
}
private void startcam_Click(object sender, RoutedEventArgs e)
{
CamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
Cam = new VideoCaptureDevice(CamsCollection[1].MonikerString);
Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
Cam.Start();
}
private void stopcam_Click(object sender, RoutedEventArgs e)
{
Cam.Stop();
}
}
他们使用PictureBox
来显示帧。当我在WPF工作时,我使用了this
总结一下,这是我目前的代码。
public FilterInfoCollection CamsCollection;
public VideoCaptureDevice Cam = null;
void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();
BitmapImage bi = new BitmapImage();
bi.BeginInit ();
MemoryStream ms = new MemoryStream ();
imgforms.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
frameholder.Source = bi;
/* ^ runtime error here because `bi` is occupied by another thread.
*/
bi.EndInit();
}
private void startcam_Click(object sender, RoutedEventArgs e)
{
CamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
Cam = new VideoCaptureDevice(CamsCollection[1].MonikerString);
Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
Cam.Start();
}
private void stopcam_Click(object sender, RoutedEventArgs e)
{
Cam.Stop();
}
答案 0 :(得分:7)
修改1:有关同一主题的详细解释,请查看我的blogpost。
我使用Dispatcher
类作为互斥锁来修复错误:
void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
imgforms.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
//Using the freeze function to avoid cross thread operations
bi.Freeze();
//Calling the UI thread using the Dispatcher to update the 'Image' WPF control
Dispatcher.BeginInvoke(new ThreadStart(delegate
{
frameholder.Source = bi; /*frameholder is the name of the 'Image' WPF control*/
}));
}
现在它按预期运行,并且在fps没有任何下降的情况下我获得了良好的性能。
答案 1 :(得分:1)
如果您想支持Silverlight,无论是针对Web还是独立或WP7,您都不应该从WPF开始,因为Silverlight中缺少WPF的许多功能。
这是一个Silverlight 4+教程:
http://www.silverlightshow.net/items/Capturing-the-Webcam-in-Silverlight-4.aspx