- 1 year ago
C# Code Project; View Video of Camera with an Overlay (Windows OS)
To view video from a camera with an overlay in a C# Windows application, you can use the AForge.NET library, which provides easy-to-use functions for working with cameras and video streams. Here's a step-by-step guide to achieve this:
Install the AForge.Video library using NuGet Package Manager:
In Visual Studio, go to "Tools" > "NuGet Package Manager" > "Package Manager Console" and run the following command:
mathematicaInstall-Package AForge.Video
Create a new Windows Forms Application in Visual Studio.
Add a
PictureBox
control and aLabel
control to the form. ThePictureBox
will display the camera video stream, and theLabel
will be used as an overlay.Add the following namespaces at the top of your form's code-behind file:
csharpusing AForge.Video;
using AForge.Video.DirectShow;
Declare class-level variables for video source and video player:
csharpprivate FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
Initialize the video source and start capturing the video in the
Form_Load
event:csharpprivate void Form1_Load(object sender, EventArgs e)
{
// Enumerate video devices (cameras)
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
{
MessageBox.Show("No video devices found.");
return;
}
// Create video source using the first camera
videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
// Set the NewFrame event handler to display video frames
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
// Start capturing video
videoSource.Start();
}
Add the
videoSource_NewFrame
event handler to update thePictureBox
with the new video frame and draw an overlay on top of it:csharpprivate void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap frame = (Bitmap)eventArgs.Frame.Clone();
// Draw overlay on the frame
using (Graphics g = Graphics.FromImage(frame))
{
g.DrawString("Overlay Text", new Font("Arial", 16), Brushes.Red, 10, 10);
// Add other overlay elements as needed
}
// Display the frame in the PictureBox
pictureBox1.Image = frame;
}
Don't forget to stop the video capture when closing the form:
csharpprivate void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (videoSource != null && videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource.WaitForStop();
}
}
That's it! When you run the application, you should see the camera's video stream in the PictureBox
, with the specified overlay text displayed on the video. Feel free to modify the overlay text and add other graphical elements to customize the overlay as needed.