Click here to Skip to main content
15,867,594 members
Articles / Desktop Programming / Win32

Fabrika LAB: WebCam Video

Rate me:
Please Sign up or sign in to vote.
5.00/5 (20 votes)
22 May 2013CPOL3 min read 112K   12.4K   40   27
Free and easy way to access a web camera by using the Aforge library.

Introduction

There are many articles across web explaining how to access web camera. Most of them address DirectShow as a recommended approach. Since dealing with DirectShow from .NET languages is not very trivial, I have decided to use Aforge library. Aforge is great open source library for manipulating images and many other things including DirectShow video.

Image 1

In this article I will show you how easy is to connect to WebCam and to display some user generated content on top of the video. This approach might be useful for augmented reality applications.

Background

While I was working for biometric enrolment software for capturing ICAO compatible facial images for national documents I wanted to use web cam as a source. After evaluating different approached, I choose one that is free and easy to use.

Using the code

I have published source code as a Visual Studio 2012 project. Language that is used in a sample is VB.NET. I believe it is easy to understand and can be easily ported to any other .NET languages.

Import AForge Library

You can go to AForge web site and download current release of the component and include following assemblies into the project (solution):

  • AForge.dll (core)
  • AForge.Math.dll
  • AForge.Imaging.dll
  • AForge.Video.dll
  • AForge.Video.DirectShow
  • AForge.Controls

Image 2

Probably the easiest way is to use NuGet Manager (Visual Studio > Tools > Library Package Manager > Manage NuGet packages for solution) and search for online packages, as show in the picture below.

Enumerate Video Sources and Video Modes

After you have referenced AForge libraries, you need to enumerate video sources (list of WebCams available) and their video modes (resolutions). 

VB.NET
Private Sub EnumerateVideoDevices()
    ' enumerate video devices
    videoDevices = New FilterInfoCollection(FilterCategory.VideoInputDevice)
    If videoDevices.Count <> 0 Then
        ' add all devices to combo
        For Each device As FilterInfo In videoDevices
            ComboBoxSources.Items.Add(device.Name)
        Next
    Else
        ComboBoxSources.Items.Add("No DirectShow devices found")
    End If
    ComboBoxSources.SelectedIndex = 0
End Sub

Private Sub EnumerateVideoModes(device As VideoCaptureDevice)
    ' get resolutions for selected video source
    Me.Cursor = Cursors.WaitCursor
    ComboBoxModes.Items.Clear()
    Try
        videoCapabilities = videoDevice.VideoCapabilities
        For Each capabilty As VideoCapabilities In videoCapabilities
            If Not ComboBoxModes.Items.Contains(capabilty.FrameSize) Then
                ComboBoxModes.Items.Add(capabilty.FrameSize)
            End If
        Next
        If videoCapabilities.Length = 0 Then
            ComboBoxModes.Items.Add("Not supported")
        End If
        ComboBoxModes.SelectedIndex = 0
    Finally
        Me.Cursor = Cursors.[Default]
    End Try
End Sub

EnumerateVideoDevices will check for all DirectShow devices available on the computer and enumerate them in videoDevices variable. After we get all the available devices user can choose which camera to use. This is needed in new devices, where more than one camera is present - like new Microsoft tablet devices with front and back camera.

Once device is chosen we have to provide user a choice to select the camera resolution and speed at which the camera will deliver us new frames. For enumerating modes for selecting camera, we use EnumerateVideoModes function. As this process can take some time, it is recommended to change default cursor or even better to use async or BackgroundWorker to complete this job. 

Start and Stop Video

Use AForge.Controls assembly to add new controls to Toolbox. One of the tools added is called VideoSourcePlayer and it is used to display live video from camera. Below snippets shows how to start and end showing live video stream to this control. 

VB
Private Sub CameraStart()
    If videoDevice IsNot Nothing Then
        If (videoCapabilities IsNot Nothing) AndAlso (videoCapabilities.Length <> 0) Then
            videoDevice.DesiredFrameSize = DirectCast(ComboBoxModes.SelectedItem, Size)
        End If
        VideoSourcePlayer1.VideoSource = videoDevice
        VideoSourcePlayer1.Start()
    End If
End Sub

Private Sub CameraStop()
    If VideoSourcePlayer1.VideoSource IsNot Nothing Then
        ' stop video device
        VideoSourcePlayer1.SignalToStop()
        VideoSourcePlayer1.WaitForStop()
        VideoSourcePlayer1.VideoSource = Nothing
    End If
End Sub

The method CameraStart assigns the selected video source and video mode to the Aforge's control VideoSourcePlayer. After calling .Start method the video is shown on this component. To stop showing video you need to signal VideoSourcePlayer control to stop  displaying video from camera source. Be aware that video thread is different than the thread of your user interface.

Add Your Own Content to the Video 

It is useful to interact with the video by adding your own content to it. Sample below shows how to add custom string to the video. By using well known Graphics object you can interact with the video. 

VB
Private Sub VideoSourcePlayer1_NewFrame(sender As Object, _
        ByRef image As Bitmap) Handles VideoSourcePlayer1.NewFrame
    ' add overlay
    Dim g As Graphics = Graphics.FromImage(image)
    g.DrawString("Augmented reality?", _
       New Font("Arial", 16), Brushes.Black, New Rectangle(10, 10, 200, 50))
    g.Dispose()
End Sub

This might be the most important part of this article, as it allows developer to access video source. The current video frame is accessible from the parameter variable image. By using the Graphics object, it is possible to add different graphical information to the video, like displaying date and time. One could use the image to make advanced processing, line finding an object in image or displaying some other useful information related to the current image.

I hope I have shown you how easy is to use web cameras in your projects and I hope to see some good apps using the web cameras.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) CENT SI d.o.o.
Slovenia Slovenia
I have strange hobby - programming.
While I am not programming I am tasting some good beers Wink | ;)

Comments and Discussions

 
QuestionResolution Pin
Happy816-Oct-16 3:12
Happy816-Oct-16 3:12 
PraiseWell Done Pin
Saheed Adeniji10-May-16 22:57
Saheed Adeniji10-May-16 22:57 
QuestionOur hobbies are exactly the same Pin
bhanline24-Jul-15 6:03
bhanline24-Jul-15 6:03 
QuestionScanner Functionality Pin
MutazS27-May-15 16:50
MutazS27-May-15 16:50 
Questioncapture a video file frame by frame Pin
Member 1120561717-Nov-14 2:35
Member 1120561717-Nov-14 2:35 
AnswerRe: capture a video file frame by frame Pin
Dejan Mauer17-Nov-14 18:44
Dejan Mauer17-Nov-14 18:44 
AnswerRe: capture a video file frame by frame Pin
Robert Perry-130528-Mar-15 13:26
Robert Perry-130528-Mar-15 13:26 
QuestionI need Help you Pin
royji12326-Sep-14 16:14
royji12326-Sep-14 16:14 
QuestionRecording Pin
Member 1079638025-Sep-14 8:48
Member 1079638025-Sep-14 8:48 
QuestionWebCam cannot connect Pin
anniww5-Aug-14 0:01
anniww5-Aug-14 0:01 
AnswerRe: WebCam cannot connect Pin
Dejan Mauer17-Aug-14 20:58
Dejan Mauer17-Aug-14 20:58 
GeneralRe: WebCam cannot connect Pin
Member 101383558-Aug-16 3:27
Member 101383558-Aug-16 3:27 
QuestionVideo Resolution Pin
Member 162645928-May-14 0:57
Member 162645928-May-14 0:57 
QuestionVery nice. 5 Pin
pdoxtader7-Oct-13 9:00
professionalpdoxtader7-Oct-13 9:00 
AnswerRe: Very nice. 5 Pin
Dejan Mauer17-Nov-14 18:45
Dejan Mauer17-Nov-14 18:45 
Questionhow can capture image from cam? Pin
irfanansari4-Oct-13 7:57
irfanansari4-Oct-13 7:57 
AnswerRe: how can capture image from cam? Pin
Dejan Mauer4-Oct-13 20:05
Dejan Mauer4-Oct-13 20:05 
QuestionGetting a snap-shot of a frame while recording Pin
ChrisKweks18-Jun-13 17:19
professionalChrisKweks18-Jun-13 17:19 
AnswerRe: Getting a snap-shot of a frame while recording Pin
Dejan Mauer20-Jun-13 1:35
Dejan Mauer20-Jun-13 1:35 
GeneralRe: Getting a snap-shot of a frame while recording Pin
ChrisKweks20-Jun-13 4:21
professionalChrisKweks20-Jun-13 4:21 
GeneralMy vote of 5 Pin
NalaBI22-May-13 2:40
NalaBI22-May-13 2:40 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA12-Apr-13 19:15
professionalȘtefan-Mihai MOGA12-Apr-13 19:15 
This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information. Keep it up once again.
QuestionWebforms Pin
edwarmartinez3-Apr-13 8:47
edwarmartinez3-Apr-13 8:47 
AnswerRe: Webforms Pin
Dejan Mauer12-Apr-13 21:50
Dejan Mauer12-Apr-13 21:50 
GeneralMy vote of 5 Pin
DianaLopez23-Mar-13 18:38
DianaLopez23-Mar-13 18:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.