I am attempting to write a Windows Console program that is capable of acquiring imagery from a webcam or a virtual webcam, extracting a bitmap frame from the video source and saving the frame to the filesystem as a bitmap file.
Currently I use a program called OBS Studio to emulate a video source with the "Virtual Camera" option.
Here is the code:
using System;
using AForge.Video.DirectShow;
using AForge.Video;
using System.Drawing;
namespace webcamc
{
class Program
{
FilterInfoCollection filterInfoCollection;
VideoCaptureDevice videoCaptureDevice;
Bitmap bitmap;
static void Main(string[] args)
{
var program = new Program();
program._init();
}
void _handleNewFrameEvent(object sender, NewFrameEventArgs eventArgs)
{
bitmap = new Bitmap(eventArgs.Frame);
}
void _init()
{
filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
videoCaptureDevice = new VideoCaptureDevice(filterInfoCollection[0].MonikerString);
videoCaptureDevice.Start();
videoCaptureDevice.NewFrame += new NewFrameEventHandler(_handleNewFrameEvent);
string ActiveDir = AppDomain.CurrentDomain.BaseDirectory;
string filepath = System.IO.Path.Combine(ActiveDir, @"C://Pic");
string fileName = System.IO.Path.Combine(filepath, @"name.bmp");
bool fileNotExists = !System.IO.File.Exists(fileName);
if (fileNotExists)
{
bitmap.Save(fileName);
}
}
}
}
Unfortunately, I am unable to understand why the _handleNewFrameEvent
method that I pass to the NewFrameEventHandler
is not triggered; i have inspected the code with a debugger and the breakpoint is not hit.
I am quite sure that the device list and the device moniker is acquired correctly.
However I doubt very much the videoCaptureDevice
instance. I am not sure but it looks like it is not correctly instantiated since all the pertaining values appear to be 0.
Here is an image of the debugger showing the ill-instantiated video capture device
Could anyone please point me in the right direction?
Thank you.
I would first move
videoCaptureDevice.Start();
belowvideoCaptureDevice.NewFrame += new NewFrameEventHandler(_handleNewFrameEvent);
as you only want to start running the camera feed once you can receive the new frames (but I am not confident that this will solve your problem).Maybe there is an error being thrown by the starting of the webcam so adding a
vDevIn.VideoSourceError += new VideoSourceErrorEventHandler(errorHandler)
and see if there is any error thrown using function below: