Page 1 of 1

C# ONVIF example on how to make IP camera viewer with motion detection

#1 GerardoGritti  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 1
  • Joined: 22-October 14

Posted 22 October 2014 - 06:11 AM

This C# tutorial is intended to explain how to implement an ONVIF-based camera viewer that can be used to display the image of USB webcams and IP cameras as well and to detect any motion within the ROI (Region of Interest). As it is shown in the following table of contents, the tutorial consists of two main parts: one for the theoretical background and another one for C# programming.

Contents:

Part 1: Introduction
  • What is ONVIF
  • What is ’motion detection’ and how you can use this functionality

Part2: C# IP camera programming
  • Creating a new WPF Application in Visual Studio
  • Implementing a basic camera viewer application in C#
    • Creating the GUI
    • Building camera viewer feature

  • Implementing the motion detection functionality in C#
    • Improving the GUI
    • Building motion detection feature

  • Checking the result

Conclusion
List of references


Download source:
Attached File  USB_IP_Camera_Viewer_with_Motion_Detection.zip (75.34K)
Number of downloads: 13

Get the tools you need:




Part 1: Introduction

Before starting the implementation of the ONVIF IP camera viewer and motion detector, let’s take a little time to find out more about the applied technology.


What is ONVIF

ONVIF is intended to facilitate the development and use of an IP-based security standard. The ’ONVIF’ phrase is the acronym for Open Network Video Interface Forum that has been established in 2008 by Axis Communications, Bosch Security Systems and Sony with the aim to achieve interoperability between network video products regardless of manufacturer. Quoting the ONVIF:

Quote

ONVIF is an open industry forum for the development of a global standard for the interface of IP-based physical security products.


The keystones of ONVIF are as follows: standardization of communication between IP-based video devices; interoperability between IP-based security devices regardless of manufacturer; open to all companies and organizations.

The ONVIF specification defines a common protocol for the exchange of data between network video devices including video streaming, video analytics, motion detection, automatic device discovery, etc.


What is ’motion detection’ and how you can use this functionality

The ’motion detection’ phrase refers to the process of detecting any change in position of an object relative to its surroundings or the change in the surroundings relative to an object. Quoting the Axis Communications:

Quote

Video motion detection (VMD) is a way of defining activity in a scene by analyzing image data and differences in a series of images. The functionality can either be built-in into a network video product or made available with video management software.


By building motion detection functionality into your basic camera viewer application, you can allow your software to detect moving objects, particularly people (Figure 1), in the area that is under video surveillance.

Attached Image
Figure 1: How the motion detection works in an IP surveillance system

Motion detection can be easily combined with alarm functionality that provides a great way for improving any security or surveillance system by implementing motion-based alarm notifications. However, nowadays motion detection forms a vital component not only of security systems, but also of automated lighting control, home control, energy efficiency and other useful systems.


Part 2: C# IP camera programming

After finding out all you need to know about the ONVIF specification and motion detection, let’s get the programming started.

Start the implementation of this solution by connecting your camera to your network. If you use a USB webcam, you only need to plug its USB cable into one of the available USB ports of the computer, and it is usually be installed automatically. In case of any IP camera you will need some network configurations. For more information please study the user manual of your device. After you have connected your camera to the network, make sure that the Visual Studio (along with .NET Framework 4) and the camera SDK is installed on your PC.


Creating a new WPF Application in Visual Studio

Okay, let's do it! Launch your Visual Studio and create a new project: a Visual C# WPF Application is needed. Select the ’WPF Application’ type from the list, specify a name for your project, then click on the ’OK’ button.

Now let’s provide instant ONVIF-ability to your Visual Studio. Please, right-click on the ’References’ and select the ’Add Reference…’ option. On the ’Browse’ tab open the folder where the Camera SDK has been installed to, then search the ’VoIPSDK.dll’. Select this file, then click on the ’OK’ button to add this .dll as a reference to your project.


Implementing a basic camera viewer application in C#

Creating the GUI

First of all, let’s create a Graphical User Interface for your application in the Mainwindow.xaml file. Start by creating the video viewer section that consists of the camera connection field and the camera image display.

Concerning the fact that this application will be able to display the camera image of USB webcams and IP (network) cameras as well, it is preferred that the GUI contains the following two separate sections: ’Connect to USB camera’ and ’Connect to IP camera’. In both sections there is a need for 2-2 buttons: ’Connect’ and ’Disconnect’. Thus, a total of 4 buttons are needed.

Take a closer look at the ’Connect to USB camera’ section (Code example 1). Since almost all webcameras are simple USB PnP (Plug and Play) devices, only one ’Connect’ button is needed to be able to connect to this type of cameras. After pressing this ’Connect’ button, the program will look for an available USB camera that has been connected previously to the PC, and its image will be loaded automatically. By pressing the ’Disconnect’ button, the program will stop to display the camera image and disconnect the device. Below you can see how to add the necessary event handler for the ’Connect’ and ’Disconnect’ buttons.

<GroupBox Header="Connect to USB camera" Height="100" Width="150" HorizontalAlignment="Left" VerticalAlignment="Top">
            <Grid>
                <Button Content="Connect" Width="75" Margin="32,19,0,0" 
                        HorizontalAlignment="Left" VerticalAlignment="Top"
                        Click="ConnectUSBCamera_Click"/>
                <Button Content="Disconnect" Width="75" Margin="32,46,0,0"
                        HorizontalAlignment="Left" VerticalAlignment="Top"
                        Click="DisconnectUSBCamera_Click"/>
            </Grid>
</GroupBox>

Code example 1: The ’Connect to USB camera’ section on the GUI

Now let’s consider the case when you want to display the image of an IP camera. As it was mentioned above, in order to connect an IP camera to your LAN, some network configurations are essentially needed. During these configurations three parameters are used to establish the connection: the IP address of the camera, its username and password. To be able to connect your application to an IP camera, you need to provide these parameters within the application as well. For this reason, in the ’Connect to IP camera’ section of the GUI (Code example 2), you need to add three texboxes to be able to enter the connection details (address of the IP camera, username, password). There is also a need for the ’Connect’ and ’Disconnect’ buttons that in this section work the same way as in the ’Connect to USB camera’ section.

<GroupBox Header="Connect to IP camera" Height="100" Width="387" 
                  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="155,0,0,0">
            <Grid>
                <Label Height="25" Width="70" Content="Host" 
                       HorizontalAlignment="Left" VerticalAlignment="Top"/>
                <TextBox Name="HostTextBox" HorizontalAlignment="Left" VerticalAlignment="Top"
                         Height="23" Width="169" Margin="68,2,0,0" TextWrapping="Wrap" />
                <Label Height="25" Width="70" Content="Username" 
                       HorizontalAlignment="Left" Margin="0,26,0,0" VerticalAlignment="Top"/>
                <TextBox Name="UserTextBox" HorizontalAlignment="Left" VerticalAlignment="Top" 
                         Height="23" Width="169" Margin="68,29,0,0" TextWrapping="Wrap"/>
                <Label Height="25" Width="70" Content="Password" 
                       HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,52,0,0" />
                <PasswordBox Name="Password" HorizontalAlignment="Left" VerticalAlignment="Top"
                             Height="25" Width="169" Margin="68,56,0,0"/>
                <Button Content="Connect" HorizontalAlignment="Left" VerticalAlignment="Top"
                        Margin="267,16,0,0"  Width="75" Click="ConnectIPCamera_Click"/>
                <Button Content="Disconnect" HorizontalAlignment="Left" VerticalAlignment="Top"
                        Margin="267,43,0,0"  Width="75" Click="DisconnectIPCamera_Click" />
            </Grid>
        </GroupBox>

Code example 2: The ’Connect to IP camera’ section on the GUI

Having done the camera connection section, use the following code snippet to display a camera screen and the motion detection options on the GUI (Code example 3):

<Grid Name="CameraBox" Margin="10,105,10,166"/>

<GroupBox Header="Function" Height="160" Width="542" Margin="0,360,0,0"
                  HorizontalAlignment="Left" VerticalAlignment="Top" >
    <Grid>
                
    </Grid>
</GroupBox>

Code example 3: CameraBox to display the camera image

Finally you need to set the windows property by inserting the following line (Code example 4):

ResizeMode="NoResize" WindowStartupLocation="CenterScreen"

Code example 4: Set the windows property


Building camera viewer feature

Having done the previous GUI elements, let’s move on to the implementation of the camera viewer functionality. So start working with the Mainwindow.xaml.cs.

First of all you need to add the essential namespaces that are determined by the Camera SDK. So please add the following extra using lines (Code example 5):

using Ozeki.Media.IPCamera;
using Ozeki.Media.MediaHandlers;
using Ozeki.Media.MediaHandlers.Video;
using Ozeki.Media.Video.Controls;

Code example 5: Add some extra using lines

After this you need to add the necessary objects to be able to display the camera image (regardless of the type of the camera) (Code example 6):

private VideoViewerWPF _videoViewerWpf;

private BitmapSourceProvider _provider;

private IIPCamera _ipCamera;

private WebCamera _webCamera;

private MediaConnector _connector;

Code example 6: Add the necessary objects

In the constructor you need to instantiate the previous objects (Code example 7). After this you need to call the helpfunction (SetVideoViewer()).

public MainWindow()
        {
            InitializeComponent();

            _connector = new MediaConnector();

            _provider = new BitmapSourceProvider();

            _detector = new MotionDetector();

            SetVideoViewer();
        }

Code example 7: Instantiate the objects

Then you need to create this helpfunction that can be used to create and set the videoviewer object and add it to the user interface (Code example 8):

private void SetVideoViewer()
        {
            _videoViewerWpf = new VideoViewerWPF
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                Background = Brushes.Black
            };
            CameraBox.Children.Add(_videoViewerWpf);

            _videoViewerWpf.SetImageProvider(_provider);
        }

Code example 8: Create the SetVideViewer()

Now it’s time to establish the USB camera connection event handler. You need to create a webcamera object and connect it to the BitmapSourceprovider. After this you need to start the camera. Having done the USB camera connector, you need to implement the USB camera disconnecor, where the program stops the videoviewer and webcamera (Code example 9).

#region USB Camera Connect/Disconnect

        private void ConnectUSBCamera_Click(object sender, RoutedEventArgs e)
        {
            _webCamera = WebCamera.GetDefaultDevice();
            if (_webCamera == null) return;
            _connector.Connect(_webCamera, _provider);

            _webCamera.Start();
            _videoViewerWpf.Start();
        }

        private void DisconnectUSBCamera_Click(object sender, RoutedEventArgs e)
        {
            _videoViewerWpf.Stop();

            _webCamera.Stop();
            _webCamera.Dispose();

            _connector.Disconnect(_webCamera, _provider);
        }
#endregion

Code example 9: USB Camera Connect/Disconnect

As it was mentioned above, because of the inevitable network configurations, you can connect to an IP camera if you provide the following parameters: IP address of the camera, its username and password. For this reason, for establishing the IP camera connection event handler, you need to add these parameters to be able to connect to the camera. After this you need to start the camera (Code example 10). (The disconnection happens like in case of the USB webcamera.)

#region IP Camera Connect/Disconnect

        private void ConnectIPCamera_Click(object sender, RoutedEventArgs e)
        {
            var host = HostTextBox.Text;
            var user = UserTextBox.Text;
            var pass = Password.Password;

            _ipCamera = IPCameraFactory.GetCamera(host, user, pass);
            if (_ipCamera == null) return;
            _connector.Connect(_ipCamera.VideoChannel, _provider);

            _ipCamera.Start();
            _videoViewerWpf.Start();
        }

        private void DisconnectIPCamera_Click(object sender, RoutedEventArgs e)
        {
            _videoViewerWpf.Stop();

            _ipCamera.Disconnect();
            _ipCamera.Dispose();

            _connector.Disconnect(_ipCamera.VideoChannel, _provider);
        }
#endregion

Code example 10: IP Camera Connect/Disconnect


Implementing the motion detection functionality in C#

Improving the GUI

Okay, now let’s go back to the Mainwindow.xaml and extend the GUI with a checkbox and a label element. (Above, at Code example 3, you have added a section for the motion detection options. Now you need to add the following GUI elements between the two empty <Grid></Grid> tags.) For the checkbox you need to generate an eventhandler method (Code example 11).

<Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="5*"/>
                </Grid.ColumnDefinitions>
                <CheckBox Content="Detection" 
                          HorizontalAlignment="Center" VerticalAlignment="Center" 
                          Checked="MotionChecked" Unchecked="MotionChecked"/>
                <Label Grid.Column="1" x:Name="MotionEventLabel" 
                       FontSize="32" Foreground="Red" FontWeight="Bold"
                       HorizontalContentAlignment="Center" VerticalContentAlignment="Center" />

Code example 11: Extend the GUI with motion detection options (checkbox and label elements)


Building motion detection feature

Having done the previous modifications on the GUI, go back to the Mainwindow.xaml.cs. Here you need to declare a new field: MotionDetector (Code example 12). It will be initiated at the connection.

private MotionDetector _detector;

Code example 12: Declare a new object

Due to the MotionDetector, you need to modify the connection and disconnection of all connectors. You will se below that the detector becomes wedged between the displaying and the camera stream (Figure 2). Firstly, if the detector is turned on, it gets the camera image, then analyzes that. If the it detects any changes, the detector modifies the image (HighlightMotion, MotionColor) and transmits the modified image to the provider (that is connected to the videoViewer and displays the camera image). So this is a middle layer between the camera and videoViewer.

Attached Image
Figure 2: How the motion detector works in C#

You need to carry out these modifications in case of USB and IP cameras as well. At disconnection you also need to stop the detector.

The following code example demonstrates the modified USB Camera connector/disconnector (Code example 13):

#region USB Camera Connect/Disconnect

        private void ConnectUSBCamera_Click(object sender, RoutedEventArgs e)
        {
            _webCamera = WebCamera.GetDefaultDevice();
            if (_webCamera == null) return;
            _connector.Connect(_webCamera, _detector);
            _connector.Connect(_detector, _provider);

            _webCamera.Start();
            _videoViewerWpf.Start();
        }

        private void DisconnectUSBCamera_Click(object sender, RoutedEventArgs e)
        {
            _videoViewerWpf.Stop();

            _webCamera.Stop();
            _webCamera.Dispose();

            _connector.Disconnect(_webCamera, _detector);
            _connector.Disconnect(_detector, _provider);
        }
#endregion

Code example 13: The modified USB Camera Connect/Disconnect

And the modified IP Camera connector / disconnector can be seen below (Code example 14):

#region IP Camera Connect/Disconnect

        private void ConnectIPCamera_Click(object sender, RoutedEventArgs e)
        {
            var host = HostTextBox.Text;
            var user = UserTextBox.Text;
            var pass = Password.Password;

            _ipCamera = IPCameraFactory.GetCamera(host, user, pass);
            if (_ipCamera == null) return;
            _connector.Connect(_ipCamera.VideoChannel, _detector);
            _connector.Connect(_detector, _provider);

            _ipCamera.Start();
            _videoViewerWpf.Start();
        }

        private void DisconnectIPCamera_Click(object sender, RoutedEventArgs e)
        {
            _videoViewerWpf.Stop();

            _ipCamera.Disconnect();
            _ipCamera.Dispose();

            _connector.Disconnect(_ipCamera.VideoChannel, _detector);
            _connector.Disconnect(_detector, _provider);
        }
#endregion

Code example 14: The modified IP Camera Connect/Disconnect

Before the implementation of the Motionchecked, first you need some helpfunctions. Using the GUIThread, you can handle the event coming from the camera in an other thread (Code example 15):

void GuiThread(Action action)
{
    Dispatcher.BeginInvoke(action);
}

Code example 15: The GUIThread helpfunction

The next one is the StartMotionDetection that is used to set and start the motion detection (Code example 16). You can see below that the detected motion can be highlighted in different ways. By specifying the HighlightMotion property of the detector object, you can set how the motion will be indicated on the screen. The Highlight value can be None, DrawAround or Highlight. Furthermore, the moving shapes can be colored (in red, green or blue) with the help of the MotionColor property of the detector object. Here you need to subscribe for the MotionDetection event by using the detector_MotionDetection.

private void StartMotionDetection()
{
    _detector.HighlightMotion = HighlightMotion.Highlight;
    _detector.MotionColor = MotionColor.Red;
    _detector.MotionDetection += detector_MotionDetection;
    _detector.Start();
}

Code example 16: The StartMotionDetection helpfunction

The eventhandler method will be called in an other thread and it will indicate on the GUI if any motion is detected (Code example 17).

void detector_MotionDetection(object sender, MotionDetectionEvent e)
        {
            GuiThread(() =>
            {
                if (e.Detection)
                    MotionEventLabel.Content = "Motion Detected";
                else
                    MotionEventLabel.Content = "Motion Stopped";
            });
        }

Code example 17: The eventhandler method

Finally, you need to stop the detector and unsubscribe from the MotionDetection event (Code example 18).

private void StopMotionDetection()
        {
            _detector.Stop();
            _detector.MotionDetection -= detector_MotionDetection;
            _detector.Dispose();
        }

Code example 18: The StopMotionDetection method

In the MotionChecked you need to use the previous functions. If the checkbox is checked, the program calls the StartMotionDetection(), else it calls the StopMotionDetection() (Code example 19).

private void MotionChecked(object sender, RoutedEventArgs e)
        {
            MotionEventLabel.Content = String.Empty;
            var check = sender as CheckBox;
            if (check != null)
            {
                if ((bool)check.IsChecked)
                    StartMotionDetection();
                else
                    StopMotionDetection();
            }
        }

Code example 19: The MotionChecked method

Okay, and now it’s time to run the application.


Checking the result

Having done the coding section above, let’s run the application to check the results. After you have run the program, the following GUI can be seen (Figure 3):

Attached Image
Figure 3: The GUI of the ONVIF IP camera viewer extended with motion detection

Now check how you can connect to a camera. (It is assumed that you have already connected a USB webcamera and an IP camera as well to your network – learn more about this topic at the beginning of the ’Part 2: C# IP camera programming’ section.) If you want to use a USB webcam, click on the ’Connect’ button in the ’Connect to USB camera’ section of the GUI. The program will display the image of the webcam that is connected to your PC (Figure 4):

Attached Image
Figure 4: The ONVIF IP camera viewer displays the image of the connected USB webcam

Now let’s see how to proceed if you want to use an IP camera. Firstly, disconnect the USB camera streaming – if you have connected at all – by clicking on the corresponding ’Disconnect’ button. Now take a look at the ’Connect to IP camera’ section. Enter the IP address of your IP camera into the ’Host’ text input field, then enter the belonging username and the password below it. After specifying the required parameters, click on the ’Connect’ button and the application will load the image of the defined IP camera soon (Figure 5):

Attached Image
Figure 5: The ONVIF IP camera viewer displays the image of the connected IP camera

Now let’s check out how the motion detection feature work. For the demonstration the last connected IP camera has been used. In order to activate the motion detection functionality you need to check the ’Detection’ checkbox under the camera image.

On the following figure you can see that when somebody appeared in the area that is under IP camera surveillance, the camera immediately indicated the moving by red highlighting. In addition to the highlighting, the program indicated the motion by displaying the ’Motion Detected’ subtitle under the camera image.

Attached Image
Figure 6: The ONVIF IP camera viewer detects and highlights the motion

The highlighting on the camera image lasted until the moving object could be seen. When the man got downstairs and any movement ceased on the stairs, the red highlighting disappeared and the ’Motion Stopped’ subtitle appeared under the camera image (Figure 7).

Attached Image
Figure 7: There is no movement detected by the ONVIF IP camera viewer

It’s as easy as that!


Conclusion

After providing detailed information about the ONVIF techonolgy and motion detection, this C# tutorial described step-by-step how to implement an ONVIF-based camera viewer that can be used to display the image of USB webcams and IP cameras as well and to detect any motion within the ROI (Region of Interest). This solution can be useful for any developers or system integrators who want to improve their IP-based security/surveillance system. Wish you good work!


List of references



Get the tools you need:



Is This A Good Question/Topic? 1
  • +

Replies To: C# ONVIF example on how to make IP camera viewer with motion detection

#2 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 947
  • View blog
  • Posts: 2,356
  • Joined: 15-February 11

Posted 22 October 2014 - 08:15 PM

Interesting tutorial. I currently have a few cameras around my house and you've just opened up my appetite. I have a question though. Is it possible to reduce the motion detection's sensitivity? I won't want a tree triggering the motion detection and raising a lot of false positives. Good work by the way.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1