Click here to Skip to main content
Click here to Skip to main content

Fabrika LAB: WebCam Video

, 22 May 2013
Rate this:
Please Sign up or sign in to vote.
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.

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

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). 

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. 

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. 

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)

About the Author

Dejan Mauer
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 | ;)
Follow on   Twitter

Comments and Discussions

 
QuestionVideo Resolution PinmemberMember 162645928-May-14 0:57 
QuestionVery nice. 5 [modified] Pinmemberpdoxtader7-Oct-13 9:00 
Questionhow can capture image from cam? Pingroupirfanansari4-Oct-13 7:57 
AnswerRe: how can capture image from cam? PinmemberDejan Mauer4-Oct-13 20:05 
QuestionGetting a snap-shot of a frame while recording PinmemberChrisKweks18-Jun-13 17:19 
AnswerRe: Getting a snap-shot of a frame while recording PinmemberDejan Mauer20-Jun-13 1:35 
GeneralRe: Getting a snap-shot of a frame while recording PinprofessionalChrisKweks20-Jun-13 4:21 
GeneralMy vote of 5 PinmemberNalaBI22-May-13 2:40 
GeneralMy vote of 5 PinmemberMihai MOGA12-Apr-13 19:15 
QuestionWebforms Pinmemberedwarmartinez3-Apr-13 8:47 
AnswerRe: Webforms PinmemberDejan Mauer12-Apr-13 21:50 
I would look to some kind of web services to transfere image captured with web cam to client.
GeneralMy vote of 5 PinmemberDianaLopez23-Mar-13 18:38 
GeneralMy vote of 5 PinmemberVitorHugoGarcia11-Mar-13 7:12 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 23 May 2013
Article Copyright 2013 by Dejan Mauer
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid