Çarşamba Ekim 9th, 2019

Xamarin.Forms Yüz Tanıma(Face Recognition)

ile Ebubekir Sezer

Merhaba arkadaşlar, Yapay zeka günümüzde hızla gelişmekte olan bir alan ve bu alan gelişirken yaptığımız uygulamalara yeni özellikler ekleyebiliyoruz. Azure üzerinde bulunan Yapay zeka uygulamalarını yani Cognitive Service’ler oluşturark bunları Xamari.Forms ile telefonda kullanmaya çalışacağım. İlk olarak Yüz tanıma servisini kullanarak uygulama yapmaya çalışacağım. Azure kullanmak için ögrencilere ücretsiz üyelik veriyor ben bu üyeliği kullanarak Azure’dan yararlanıyorum. Üyelik için buraya tıklayın.

İlk olarak Azure’a giriş yapıyorum ve Yüz tanıma Api’sini oluşturuyorum, gayet basit işlemler olduğu için burayı atlıyorum(Sorunuz olursa yazın). Xamarin.Forms blank application oluşturuyorum. Uygulamam oluştuktan sonra bir FaceRecognitionPage adında bir sayfa oluşturuyorum ve bu sayfanın tasarımını yapıyorum.

<StackLayout Margin="10">
        <Image HeightRequest="250"
               Source="defaultimage"
               x:Name="myImage"/>
        <Button Text="Take Picture"
                FontSize="Medium"
                BackgroundColor="Green"
                TextColor="White"
                Clicked="ButtonTakePicture_Clicked"/>
        <Button Text="Pick Picture"
                FontSize="Medium"
                BackgroundColor="Green"
                TextColor="White"
                Clicked="ButtonPickPicture_Clicked"/>
        <ActivityIndicator Color="Green"
                           VerticalOptions="Center"
                           HorizontalOptions="Center"
                           IsVisible="False"
                           x:Name="myActivitIndicator"/>
        <Label x:Name="labelGender"
               FontSize="Medium"
               VerticalOptions="Center"
               HorizontalOptions="Center"
               FontAttributes="Bold"
               TextColor="Black"/>
        <Label x:Name="labelAge"
               FontSize="Medium"
               VerticalOptions="Center"
               HorizontalOptions="Center"
               FontAttributes="Bold"
               TextColor="Black"/>
    </StackLayout>

Ben bütün Cognitive Service’leri deneyip bunlarla ilgili bir proje oluşturacağım için bir master-detail page oluşturup buradan farklı sayfalar devam ediyorum. Eğer kodu kopyalayıp yapıştırırsanız yukarıda ki gibi görüntü elde edersiniz. Tasarım kısmı kolaydı şimdi bunun arkasını doldurmamız lazım bunun için Microsoft’un dokümanın takip ederek oluşturmaya çalışıyorum. Dokümana buraya tıklayarak bakabilirsiniz. Ayrıca fotoğraf çekme ve seçme işlemlerini önceki yazılarımda yazmıştım ulaşmak için buraya tıklayın. Projeye Newtonsoft.Json ve Xam.Plugin.Media nuget packagelerini ekleyin.

Dokümantasyona baktıysanın orada en sonda Json çıktısını görebilirsiniz. Biz bu Json’ı C#’a çevirmeliyiz bunun için o Json’u kopyalayın ve buraya tıklayark gittiğiniz sitede C# haline getirin. Şimdi projemizde FaceModel adında bir dosya oluşturun ve o C# kodlarını buraya yapıştırın en alttaki RootObject ismini FaceModel ile değiştirmeyi unutmayın.

 public class FaceModel
    {
        public string faceId { get; set; }
        public FaceRectangle faceRectangle { get; set; }
        public FaceAttributes faceAttributes { get; set; }
    }
    public class FaceRectangle
        {
            public int top { get; set; }
            public int left { get; set; }
            public int width { get; set; }
            public int height { get; set; }
        }

        public class HeadPose
        {
            public double pitch { get; set; }
            public double roll { get; set; }
            public double yaw { get; set; }
        }

        public class FacialHair
        {
            public double moustache { get; set; }
            public double beard { get; set; }
            public double sideburns { get; set; }
        }

        public class Emotion
        {
            public double anger { get; set; }
            public double contempt { get; set; }
            public double disgust { get; set; }
            public double fear { get; set; }
            public double happiness { get; set; }
            public double neutral { get; set; }
            public double sadness { get; set; }
            public double surprise { get; set; }
        }

        public class Blur
        {
            public string blurLevel { get; set; }
            public double value { get; set; }
        }

        public class Exposure
        {
            public string exposureLevel { get; set; }
            public double value { get; set; }
        }

        public class Noise
        {
            public string noiseLevel { get; set; }
            public double value { get; set; }
        }

        public class Makeup
        {
            public bool eyeMakeup { get; set; }
            public bool lipMakeup { get; set; }
        }

        public class Occlusion
        {
            public bool foreheadOccluded { get; set; }
            public bool eyeOccluded { get; set; }
            public bool mouthOccluded { get; set; }
        }

        public class HairColor
        {
            public string color { get; set; }
            public double confidence { get; set; }
        }

        public class Hair
        {
            public double bald { get; set; }
            public bool invisible { get; set; }
            public List<HairColor> hairColor { get; set; }
        }

        public class FaceAttributes
        {
            public double smile { get; set; }
            public HeadPose headPose { get; set; }
            public string gender { get; set; }
            public double age { get; set; }
            public FacialHair facialHair { get; set; }
            public string glasses { get; set; }
            public Emotion emotion { get; set; }
            public Blur blur { get; set; }
            public Exposure exposure { get; set; }
            public Noise noise { get; set; }
            public Makeup makeup { get; set; }
            public List<object> accessories { get; set; }
            public Occlusion occlusion { get; set; }
            public Hair hair { get; set; }
        }

Class’ımızı ekledikten sonra artık sayfamızın .cs kısmına gidelim ve işlemlerimizi tamamlayalım. Burada Subscription Key’inizi ve End Point url’ini kullanacağız. Aşağıdaki kodu kendi projenize eklerseniz yüz tanıma işlemimiz gerçeklecektir. Ben yüz tanımda sadece cinsiyeti ve yaşı kullandım ama çok fazla özellik var bunları kendiniz bakarak kullanabilirsiniz.

 public partial class FaceRecognitionPage : ContentPage
    {
        MediaFile mediaFile;
        const string subscriptionKey = "Key";
        const string uriBase = "End-Point";

        public FaceRecognitionPage()
        {
            InitializeComponent();
        }

        private  void ButtonTakePicture_Clicked(object sender, EventArgs e)
        {
            TakePicture();
        }

        private void ButtonPickPicture_Clicked(object sender, EventArgs e)
        {
            PickPicture();
        }

        //Analysis of the Picture
        public async void MakeAnalysisRequest(string imageFilePath)
        {
            myActivitIndicator.IsVisible = true;
            myActivitIndicator.IsRunning = true;

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

            string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
               "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
               "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

            string uri = uriBase + "?" + requestParameters;
            HttpResponseMessage response;
            byte[] byteData = GetImageAsByteArray(imageFilePath);

            using (ByteArrayContent content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response = await client.PostAsync(uri, content);
                string contentString = await response.Content.ReadAsStringAsync();

                //Display Result
                List<FaceModel> faceModels = JsonConvert.DeserializeObject<List<FaceModel>>(contentString);
                if(faceModels.Count != 0)
                {
                    labelGender.Text = "Gender : " + faceModels[0].faceAttributes.gender;
                    labelAge.Text = "Age : " + faceModels[0].faceAttributes.age;
                }
            }

            myActivitIndicator.IsVisible = false;
            myActivitIndicator.IsRunning = false;
        }

        public byte[] GetImageAsByteArray(string imageFilePath)
        {
            using (FileStream fileStream =
                new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
            {
                BinaryReader binaryReader = new BinaryReader(fileStream);
                return binaryReader.ReadBytes((int)fileStream.Length);
            }
        }

        //Taking Picture Process
        async void TakePicture()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsTakePhotoSupported || !CrossMedia.Current.IsCameraAvailable)
            {
                await DisplayAlert("ERROR", "Camera is NOT available", "OK");
                return;
            }

            mediaFile = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
            {
                Directory = "Sample",
                Name = "myImage.jpg"
            });

            if (mediaFile == null)
            {
                return;
            }

            myImage.Source = ImageSource.FromStream(() =>
            {
                return mediaFile.GetStream();
            });

            MakeAnalysisRequest(mediaFile.Path);
        }

        //Picking Picture Process
        async void PickPicture()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                await DisplayAlert("ERROR", "Pick Photo is NOT supported", "OK");
                return;
            }

            var file = await CrossMedia.Current.PickPhotoAsync();

            if (file == null)
            {
                return;
            }

            myImage.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                return stream;
            });

            MakeAnalysisRequest(file.Path);
        }
    }

Soru ve görüşlerinizi e-mail veya yorum olarak belirtirseniz sevinirim. Bir sonraki yazıda Metin Analizi Api’sini kullanmaya çalışacağım.