C# | Logiciel de reconnaissance facial

Paradise'

Premium
Inscription
30 Juin 2013
Messages
4 259
Réactions
4 384
Points
20 795
header.png

Sommaire

I - Introduction & prérequis
II - Préparation du projet
III - Codage

1.png


Durant ce tutoriel vous allez apprendre à utiliser Face API en C Sharp proposé par l'entreprise Microsoft .
Cette API est payante mais une version gratuite est disponible qui permet d'effectué 30.000 requêtes par mois, ce qui je pense est quand même pas mal.

En premier il faudra allez obtenir notre clef au près de Microsoft , pour cela il faudra se rendre ici puis se connecter avec un compte ( compte Microsoft ).
Ensuite il faudra allez prendre l'accès gratuit de Face, ensuite on obtiendra deux clefs.




2.png


Donc dans notre application on aura juste deux outils à mettre :
- 1 PictureBox | Nom : FacePhoto
- 1 Bouton | Nom : BrowseButton

Ensuite on va allez installer le Package proposé par Microsoft pour ce faire :
Projet > Gérer les packages NuGet...
On va dans Parcourir et on cherche Microsoft.ProjectOxford.Face et on l'installe.

Puis on ajoute au projet la bibliothèque : PresentationCore


3.png

Tout d'abord on déclare l'utilisation de certaines bibliothèque, en ajoutant aussi la Bibliothèque WindowsBase.
Code:
using System.IO;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows;

Ensuite on va mettre notre clef obtenue précédemment
Code:
        private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("VOTRE CLEF");

Par la suite on déclare la méthode fournie par Microsoft :
Code:
        private async Task<FaceRectangle[]> UploadAndDetectFaces(string imageFilePath)
        {
            try
            {
                using (Stream imageFileStream = File.OpenRead(imageFilePath))
                {
                    var faces = await faceServiceClient.DetectAsync(imageFileStream);
                    var faceRects = faces.Select(face => face.FaceRectangle);
                    return faceRects.ToArray();
                }
            }
            catch (Exception)
            {
                return new FaceRectangle[0];
            }
        }

Pour finir voici le code de notre bouton :

Code:
       private async void BrowseButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "JPEG|*.jpg";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                Image image = Image.FromFile(dialog.FileName);
            }
            string filePath = dialog.FileName;
            Uri fileUri = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();
            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource = fileUri;
            bitmapSource.EndInit();
            FacePhoto.ImageLocation = bitmapSource.ToString();
            Form1.ActiveForm.Text = "Detection...";
            FaceRectangle[] faceRects = await UploadAndDetectFaces(filePath);
            Form1.ActiveForm.Text = String.Format("Detection terminée. " + faceRects.Length + " visage(s) détécté");
            if (faceRects.Length > 0)
            {
                DrawingVisual visual = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                    new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi = bitmapSource.DpiX;
                double resizeFactor = 96 / dpi;
                foreach (var faceRect in faceRects)
                {
                    drawingContext.DrawRectangle(
                        System.Windows.Media.Brushes.Transparent,
                        new System.Windows.Media.Pen(System.Windows.Media.Brushes.Red, 2),
                        new Rect(
                            faceRect.Left * resizeFactor,
                            faceRect.Top * resizeFactor,
                            faceRect.Width * resizeFactor,
                            faceRect.Height * resizeFactor
                            )
                    );
                }
                drawingContext.Close();
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96,
                    96,
                    PixelFormats.Pbgra32);
                faceWithRectBitmap.Render(visual);
                System.Drawing.Bitmap bitmap;
                using (MemoryStream outStream = new MemoryStream())
                {
                    BitmapEncoder enc = new BmpBitmapEncoder();
                    enc.Frames.Add(BitmapFrame.Create(faceWithRectBitmap));
                    enc.Save(outStream);
                    bitmap = new System.Drawing.Bitmap(outStream);
                }
                FacePhoto.Image = bitmap;
            }
        }

Faites attention comme vous avez pu le voir le terme async a été ajouté avant le private pour le bouton.

Voici le rendu final du logiciel :

aafe4f84e975796641ed9b05e8f43d361.png
 
Haut