I have a question, how can I display the stream from my webcam in a Image container in WPF ? I already get the stream with Emgu and converted it to an BitmapSource, but now I don't understand how to bind an Image from my webcam to WPF, with caliburn (MVVM) , every X ms ....
<Image x:Name="imageWebcam" />
Ok solution found. I can't show the whole code but I can explain a little bit, to bind wpf View:
<Image x:Name="ImageWebcam" />
To my ViewModel (using Caliburn FrameWork, but this can be easily adapted to an MVVM pattern) I must bind the Image with a function having the same name :
public WriteableBitmap ImageWebcam
{
get
{
return this.imageWebcam;
}
set
{
this.imageWebcam = value;
this.NotifyOfPropertyChange(() => this.ImageWebcam);
}
}
And to update this Image I use a Timer, that must be initialize into the ViewModel constructor :
public MachinBidule()
{
timeIsRunningOut= new System.Timers.Timer();
timeIsRunningOut.AutoReset = true;
timeIsRunningOut.Interval = 10;
timeIsRunningOut.Elapsed += (sender, e) => { UpdateImage(); };
capture = new Capture(); // Capture the webcam using EmguCV
}
And now you can manage the update using a dispatcher :
// Update the image, method called by the timer every 10 ms
private void UpdateImage()
{
// If capture is working
if(capture.QueryFrame()!= null)
{
//capture an Image from webcam stream and
Image<Bgr, Byte> currentFrame = capture.QueryFrame().ToImage<Bgr, Byte>();
if (currentFrame != null)
{
Application.Current.Dispatcher.BeginInvoke(new System.Action(() => { imageWebcam = new WriteableBitmap(BitmapSourceConvert.ToBitmapSource(currentFrame)); NotifyOfPropertyChange(() => ImageWebcam); }));
}
}
}
You can notice that we need to convert from emguCV Image<Bgr,Byte>
to WPF WriteableBitmap
and notify the update with NotifyOfPropertyChange(() => ImageWebcam)
.
Please feel free to contact me or comment if you have any questions. If you've noticed any mistake don't hesitate to correct me (grammar & code).