Visual Studio 2017 @ Windows 10 x64 @ ASUS x450J
1. Form Application
1-1. New project by Form Template.
1-2. nuget Add emgu 4.1.1.3497
1-3. Toolbox add Emgu.CV ImageBox (imageBox1)
1-4. Form1.cs
add System.ServiceModel 4.0
namespace wk12webcam
{
// nuget add emgu.cv
// ref add System.ServiceModel 4.0
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.Util;
public partial class Form1 : Form
{
private VideoCapture _capture = null;
private Mat _frame;
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
_capture = new VideoCapture();
_capture.ImageGrabbed += _capture_ImageGrabbed;
_frame = new Mat();
_capture.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_capture.Dispose();
}
private void _capture_ImageGrabbed(object sender, EventArgs e)
{
if (_capture != null && _capture.Ptr != IntPtr.Zero)
{
_capture.Retrieve(_frame, 0);
imageBox1.Image = _frame;
}
}
}
}
1-5. Results:
2. WPF
2-1. New project by WPF Template.
2-2. nuget Add emgu 4.1.1.3497
2-3. MainWindow.xaml
<Grid>
<Image Name="imageBox1"/>
</Grid>
2-4. MainWindow.xaml.ccs
Similar procedure causes error as follows
ref: http://csjoublog.blogspot.com/2018/12/emgu-webcam-capture-wpf.html2-2. nuget Add emgu 4.1.1.3497
2-3. MainWindow.xaml
<Grid>
<Image Name="imageBox1"/>
</Grid>
2-4. MainWindow.xaml.ccs
Similar procedure causes error as follows
namespace wk12WPFWebcam
{
// Add System.ServiceModel 4.0
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.Util;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Interop;
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
private VideoCapture _capture = null;
private Mat _frame;
public MainWindow()
{
InitializeComponent();
this.Closing += MainWindow_Closing;
_capture = new VideoCapture();
//_capture.ImageGrabbed += _capture_ImageGrabbed;
_frame = new Mat();
//_capture.Start();
ComponentDispatcher.ThreadIdle += ComponentDispatcher_ThreadIdle;
}
private void ComponentDispatcher_ThreadIdle(object sender, EventArgs e)
{
using (var imageFrame = _capture.QueryFrame().ToImage<Bgr, Byte>())
{
if (imageFrame != null)
{
imageBox1.Source = ConvertBitmapToImageSource(imageFrame.Bitmap);
}
}
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_capture.Dispose();
}
private ImageSource ConvertBitmapToImageSource(Bitmap imToConvert)
{
Bitmap bmp = new Bitmap(imToConvert);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
BitmapImage image = new BitmapImage();
image.BeginInit();
ms.Seek(0, SeekOrigin.Begin);
image.StreamSource = ms;
image.EndInit();
ImageSource sc = (ImageSource)image;
return sc;
}
}
}