Having decided to try AForge for video and imaging stuff, I tried to implement this simple demo:
private void Main_Load(object sender, EventArgs e)
{
// enumerate video devices
FilterInfoCollection videoDevices = new FilterInfoCollection(
FilterCategory.VideoInputDevice);
// create video source
VideoCaptureDevice videoSource = new VideoCaptureDevice(
videoDevices[0].MonikerString);
// set NewFrame event handler
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
// start the video source
videoSource.Start();
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
this.pictureBox1.Image = eventArgs.Frame;
}
The problem is that I always get an ArgumentException
, though doesn't always happen right away. It pops up on Application.Run(new Main());
, but the top of the stacktrace looks like this:
at System.Drawing.Image.get_Width() at System.Drawing.Image.get_Size()
at System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)
at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
Not sure if this is relevant, but the ParamName
attribute of the exception is null. I've tried wrapping the image assignment in a try...catch block, but this didn't help. I've also checked to make sure that the image is not null before assignment. I've also checked for non-null, but 0x0 sized images.
What have I done wrong? Can anyone suggest a workaround?
I think the problem is that you do not make a copy of the passed bitmap (frame) in your event handler.
The AForge documentation says:
Since video source may have multiple clients, each client is responsible for making a copy (cloning) of the passed video frame, because the video source disposes its own original copy after notifying of clients.
So, if you directly assign the frame to the picture box
the bitmap could be disposed by the AForge framework while the PictureBox
is trying to draw the bitmap.