Face Recognation in C#

 

 

 

 

 

 

EMGU CV

Emgu CV is a cross platform .Net wrapper to the Intel OpenCV image processing library. Allowing OpenCV functions to be called from .NET compatible languages such as C#, VB, VC++, IronPython etc. The wrapper can be compiled in Mono and run on Linux / Mac OS X. Unlike other wrappers such as OpenCVDotNet, SharperCV which use unsafe code, Emgu CV is written entirely in C#. The benefit is that it can be compiled in Mono and therefore is able to run on any platform Mono supports, including Linux, Solaris and Mac OS X. A lot of efforts has been spend to have a pure C# implementation since the headers have to be ported, compared with managed C++ implementation where header files can simply be included. But it is well worth it if you see Emgu CV running on Fedora 10! Plus it always gives you the comfort knowing that your code is cross-platform.

Face Recognation

1- Create a Windows Form Application
2- Add a PictureBox and a Timer (and Enable it)
3- Run it on a x86 system
4- Be sure you have the OpenCV relevant dlls (included with the Emgu CV download) in the folder where you code executes.
5- Adjust the path to find the Haarcascade xml (last line of the code)

using System;
using System.Windows.Forms;
using System.Drawing;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;

namespace opencvtut
{
    public partial class Form1 : Form
    {
        private Capture cap;
        private HaarCascade haar;

        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            using (Image<Bgr, byte> nextFrame = cap.QueryFrame())
            {
                if (nextFrame != null)
                {
                    // There is only one channel (gray scale), hence the zero index
                    // var faces = nextFrame.DetectHaarCascade(haar)[0];
                    Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>();
                    var faces =
                    grayframe.DetectHaarCascade(haar, 1.4, 4,
                    HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                    new Size(nextFrame.Width/8, nextFrame.Height/8))[0];

                    foreach (var face in faces)
                    {
                        nextFrame.Draw(face.rect, new Bgr(0,double.MaxValue,0), 3);
                    }
                    pictureBox1.Image = nextFrame.ToBitmap();
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // passing 0 gets zeroth web cam
            cap = new Capture(0);
            // adjust path to find your xml
            haar = new HaarCascade(“..\\..\\..\\..\\lib\\haarcascade_frontalface_alt2.xml”);
        }
    }
}

Retrieve and Update YouTube Content in C#


 
 
 
 
 
 

The YouTube Google API for .NET developers can be used in C# or ASP.NET applications to authenticate a YouTube user, to extract information about a single video from a list of videos or a set of search results, to fetch a list of videos, to upload videos to YouTube, to interact with YouTube videos, to access, create and update favorite videos, and to subscribe to YouTube channels.

Example 1. Authenticating a YouTube User

YouTubeRequestSettings settings = new YouTubeRequestSettings(“example app”, clientID, developerKey);
YouTubeRequest request = new YouTubeRequest(settings);

Example 2.Displaying a Feed of Videos

Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
printVideoFeed(videoFeed);
static void printVideoFeed(Feed<Video> feed)
{
foreach (Video entry in feed.Entries)
{
printVideoEntry(entry);
}
}

Example 3. Searching YouTube Videos

YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
//order results by the number of views (most viewed first)
query.OrderBy = “viewCount”;
// search for puppies and include restricted content in the search results
// query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
query.Query = “C# Learners”;
query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
Feed<Video> videoFeed = request.Get<Video>(query);
printVideoFeed(videoFeed);

Example 4. Uploading Videos to YouTube

Video newVideo = new Video();
newVideo.Title =”Serialization”;
newVideo.Tags.Add(new MediaCategory(“Autos”, YouTubeNameTable.CategorySchema));
newVideo.Keywords = “Programming, C#”;
newVideo.Description = “This video explains how to use Serialization in C#”;
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory(“mydevtag, anotherdevtag”,
YouTubeNameTable.DeveloperTagSchema));
newVideo.YouTubeEntry.setYouTubeExtension(“location”, “Vancouver, BC”);
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(“c:\\Serialization.mov”,
“video/quicktime”);
Video createdVideo = request.Upload(newVideo);

Example 5. Adding a Favorite Video to YouTube

YouTube users can choose to mark videos that they watch as favorite videos. A user’s favorite videos feed can be retrieved from the following URL:

http://gdata.youtube.com/feeds/api/users/username/favorites

To add a favorite video, insert a YouTubeEntry object that identifies the video to the authenticated user’s favorite videos feed:

string videoEntryUrl = “http://gdata.youtube.com/feeds/api/videos/CSharplearners”;
YouTubeEntry videoEntry = (YouTubeEntry) service.Get(videoEntryUrl);
service.Insert(new Uri(feedUrl), videoEntry);

Cryptographic Algorithms by Applications in .NET Framework 4.0

 

 

 

 

 

 

 
 

Different implementations are available for cryptographic algorithms. For example, the base for all symmetric algorithms is SymmetricAlgorithm, which is inherited by the following algorithms: Aes, DES, RC2, Rijndael, and TripleDES.

What is AES?
Aes is inherited by two classes: AesCryptoServiceProvider and AesManaged. The AesCryptoServiceProvider class is a wrapper around the Windows Cryptography API (CAPI) implementation of Aes, whereas the AesManaged class is written entirely in managed code.

What is CNG?
There is also a third type of implementation, Cryptography Next Generation (CNG), in addition to the managed and CAPI implementations. An example of a CNG algorithm is ECDiffieHellmanCng. CNG algorithms are available on Windows Vista and later.

You can choose which implementation is best for you. The managed implementations are available on all platforms that support the .NET Framework. The CAPI implementations are available on older operating systems, and are no longer being developed. CNG is the very latest implementation where new development will take place. However, the managed implementations are not certified by the Federal Information Processing Standards (FIPS), and may be slower than the wrapper classes.

What is Stream Design?
The common language runtime uses a stream-oriented design for implementing symmetric algorithms and hash algorithms. The core of this design is the CryptoStream class, which derives from the Stream class. Stream-based cryptographic objects support a single standard interface (CryptoStream) for handling the data transfer portion of the object. Because all the objects are built on a standard interface, you can chain together multiple objects and you can perform multiple operations on the data without needing any intermediate storage for it. The streaming model also enables you to build objects from smaller objects. For example, a combined encryption and hash algorithm can be viewed as a single stream object, although this object might be built from a set of stream objects.

What is Cryptographic Configuration?
Cryptographic configuration lets you resolve a specific implementation of an algorithm to an algorithm name, allowing extensibility of the .NET Framework cryptography classes. You can add your own hardware or software implementation of an algorithm and map the implementation to the algorithm name of your choice. If an algorithm is not specified in the configuration file, the default settings are used.

How to Choose a Suitable Cryptographic Algorithm by Application?
You can select an algorithm for different reasons: for example, for data integrity, for data privacy, or to generate a key. Symmetric and hash algorithms are intended for protecting data for either integrity reasons (protect from change) or privacy reasons (protect from viewing). Hash algorithms are used primarily for data integrity. Here is a list of recommended algorithms by application:

Data privacy: Aes

Data integrity: HMACSHA256 – HMACSHA512

Digital signature: ECDsa – RSA

Key exchange: ECDiffieHellman – RSA

Random number generation: RNGCryptoServiceProvider

Generating a key from a password: Rfc2898DeriveBytes

Installed Windows Services in C#

 

 

 

 

 

 

 

 

 

 

The following code checks whether a windows services installed on your machine or not.

public static void ISWindowsServiceInstalled(string serviceName)
{
    // get list of Windows services
    ServiceController[] services = ServiceController.GetServices();

    foreach (ServiceController service in services)
    {
        if (service.ServiceName == serviceName)
            return true;
    }
    return false;
}

File Content and Directory Search using Directory.GetFiles and PLINQ

 

 

 

 

 

Array of File Names

Starting .NET 4, you can use PLINQ queries to parallelize operations on file directories. The following code snippet shows how you can write a query by using the GetFiles method to populate an array of file names in a directory and all subdirectories. This method does not return until the entire array is populated, and therefore it can introduce latency at the beginning of the operation. However, after the array is populated, PLINQ can be used to search inside all the files with the specific extension located in a particular directory for a specific word very quickly. For measuring the performance, you can create a folder called CLOBS and create 8 large text files (1GB each).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

After running the project, the CPU usage goes up as it is shown in the following figure:

Finding all matches in 8 large text files (1GB each) takes 407.03 seconds as it is shown in the output window:

ZAM 3D for WPF

 

 

 

 

 

 
 

 
What is ZAM 3D?

ZAM 3D is a 3D XAML Tool for Microsoft Windows .NET 3.5+ Application Development. It provides developers and designers with a quick and easy solution for creating 3D elements for Microsoft Expression Blend and Visual Studio projects. It also acts as a 3ds or dxf to XAML converter. Electric Rain ZAM 3D™ is a full-featured 3D modeling application that enables easy creation, customization and animation of 3D interface elements for Windows .NET 3.5+ based applications. Once a 3D scene is created, ZAM 3D automatically generates the XAML (eXtensible Application Markup Language) markup necessary to convert the 3D elements into a Windows Presentation Foundation “WPF” 3D scene. XAML files created with ZAM 3D can be directly integrated into your application development environment to create rich and engaging user experiences never before possible.

ZAM 3D Interface

The ZAM 3D interface is built to be highly approachable, yet very powerful. It supplies all of the basic modeling features such as primitives, materials, lighting, etc., as well as several 2D to 3D tools like the Extrusion Editor and a Lathe Editor. Furthermore, there is a very robust Advanced Modeling environment that allows full mesh manipulation. For more information on the ZAM 3D interface, please visit the Swift 3D portion of our Website as the functionality is very similar.

File Content and Directory Search using Directory.EnumerateFiles and PLINQ

Enumerable Collection of File Names

Starting .NET 4, you can enumerate directories and files by using methods that return an enumerable collection of strings of their names. In previous versions of the .NET Framework, you could only obtain arrays of these collections. Enumerable collections provide better performance than arrays.

Parallel LINQ (PLINQ)

In .NET 4, you can use Parallel LINQ (PLINQ) for queries that contain computationally expensive operations on every element over all the files in a specified directory tree.
The following code snippet shows how to parallelize operations on file directories. The PLINQ query uses the Directory.EnumerateFiles method to search inside all the files with the specific extension located in the particular directory for a specific word. For measuring the performance, you can create a folder called CLOBS and create 8 large text files (1GB each).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

After running the project, the CPU usage goes up as it is shown in the following figure:

Finding all matches in 8 large text files (1GB each) takes 402.596 seconds as it is shown in the output window:

File Content and Directory Search using Directory.EnumerateFiles and LINQ

Enumerable Collection of File Names

Starting .NET 4, you can enumerate directories and files by using methods that return an enumerable collection of strings of their names. In previous versions of the .NET Framework, you could only obtain arrays of these collections. Enumerable collections provide better performance than arrays.

LINQ Query

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. With LINQ, a query is now a first-class language construct, just like classes, methods, events and so on. The following example shows how to use Directory.EnumerateFiles method and LINQ query to search inside all the files with the specific extension located in the particular directory for a specific word. For measuring the performance, you can create a folder called CLOBS and create 8 large text files (1GB each).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

After running the project, the CPU usage goes up as it is shown in the following figure:

Finding all matches in 8 large text files (1GB each) takes 144.06 seconds as it is shown in the output window:

Data Races & Synchronization in .NET 4.5


 

 

 

 

 

 

Data Races

A data race—or race condition—occurs when data is accessed concurrently from multiple threads. Specifically, it happens when one or more threads are writing a piece of data while one or more threads are also reading that piece of data. This problem arises because Windows programs (in C++ and the Microsoft .NET Framework alike) are fundamentally based on the concept of shared memory, where all threads in a process may access data residing in the same virtual address space.

Synchronization
In general, a race condition is when non-deterministic behavior results from threads accessing shared data or resources without following suitable synchronization protocols or locks for serializing threads and to ensure single-threaded access. Accessing shared data from multiple threads concurrently requires that either that shared state be immutable or that the application utilize synchronization to ensure the consistency of the data.

Locking

The following code ensures that the work inside the critical region is executed by at most one thread at a time.

Leaking Locks

The external influences may cause exceptions to occur on a block of code even if that exception is not explicitly stated in the code. This problem is called “Asynchronous Exceptions“. For example, a thread abort may be injected into a thread between any two instructions, though not within a finally block except in extreme conditions. If such an abort occurred after the call to Monitor.Enter but prior to entering the try block, the monitor would never be exited, and the lock would be “leaked.” To help prevent against this, the just-in-time (JIT) compiler ensures that, as long as the call to Monitor.Enter is the instruction immediately before the try block, no asynchronous exception will be able to sneak in between the two. Unfortunately, it is not always the case that these instructions are immediate neighbors. it is often the case that developers want to enter a lock conditionally, such as with a timeout, and in such cases there are typically branching instructions between the call and entering the try block.

Reliable Locking

To address this, in the .NET Framework 4 new overloads of Monitor.Enter and Monitor.TryEnter have been added, supporting a new pattern of reliable lock acquisition and release:

public static void Enter(object obj, ref bool lockTaken);

This overload guarantees that the lockTaken parameter is initialized by the time Enter returns, even in the face of asynchronous exceptions. This leads to the following new, reliable pattern for entering a lock:

Chart FX for WPF

 

 

 

 

 

Chart FX for WPF makes the application experience more enjoyable and intuitive to the user. Chart FX 7 integrates seamlessly into Visual Studio 2010, 2008 and 2005, providing developers with unprecedented data visualization capabilities. Chart FX 7 takes full advantage of the .NET Framework and cutting-edge technologies such as AJAX to create visually-rich, lightweight and secure charts that will enhance your enterprise application’s display layer.

Features:

Chart FX for WPF’s cutting-edge features will unleash new ways of exploring and analyzing your enterprise data.

1-Stylish Visual Attributes
With it’s impressive chart types, animations, motifs, layouts, palettes, borders, markers and multiple axes, Chart FX for WPF allows you to create visually-appealing charts in minutes.
2-Full XAML Support
For the first time ever, both developers and designers will be able to fully “style” chart elements and tightly couple Chart FX for WPF to their application and user interface guidelines.
3-Powerful 3D Engine
Chart FX leverages WPF’s 3D engine to allow users to manipulate any of the chart’s elements and also provide a compelling UI to make analyzing data more intuitive.
4-Innovative User Interactivity
Users can select any of the chart elements they would like to manipulate and provide compelling user interfaces to make the process of analyzing data more powerful and intuitive.
5-Flexible Data Binding
Through the magic of WPF data binding, LINQ and Chart FX, you can easily populate a chart based on other controls, XML files, databases and other underlying data.
6-Seamless IDE Integration
Chart FX for WPF maintains programmability, developer productivity and IDE integration with both Visual Studio 2008 and Expression Blend.

Copyright © All Rights Reserved - C# Learners