Learn Azure Computer Vision API using WPF

Computer vision API is giving to the extracts rice information from your images and visual data content and typically by doing moderation of images to help the clergy engaged as an assistant to your service.

Computer vision API is giving to the extracts rice information from your images and visual data content and typically by doing moderation of images to help the clergy engaged as an assistant to your service.

Introduction:

In this article, you will learn Microsoft Azure Cognitive Service – Computer Vision API using WPF Application

What is computer vision API?

Computer vision API is giving to the extracts rice information from your images and visual data content and typically by doing moderation of images to help the clergy engaged as an assistant your service.

Explore computer vision API:

  • Analyze an image
  • Read Text in images
  • Recognize celebrities and landmarks
  • Analyze video
  • Generate thumbnail

Start Computer vision API from MS Azure:

First you make sure that Azure login portal. After login this portal go to New > AI + Cognitive Service> Computer Vision API.

You have to fill required field as per your requirement. I am using free cost of service for demo proposes.

Choose pricing tire & click the create button once you service will be ready, shows the notification succeeded message on top of the corner.

Let’s click on the service name of computer_vision_API from your dashboard. Then you can be see the overview of service and End Point (API Link)

You can grab the your access keys

Azure API Using WPF:

You can follow the quick start in this URL & you can use this API they given the language. Here I am start computer vision API –Analyze an image with C# & WPF application.

C# Code:

using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Win32;

namespace WPF_AzureAI
{
    public partial class MainWindow : Window
    {
        const string subscriptionKey = "e8230d69dd1f4440bef4abaca1135f93";
        const string uriBase = "htts://southeastasia.api.cognitive.microsoft.com/vision/v1.0/analyze";
static string bindingString = string.Empty;
        string imageFilePath = string.Empty;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
           
            MakeAnalysisRequest(imageFilePath);
            RichTextBox.Document.Blocks.Clear();
            RichTextBox.Document.Blocks.Add(new Paragraph(new Run(bindingString)));

        }
static async void MakeAnalysisRequest(string imageFilePath)
        {
            HttpClient client = new HttpClient();
            string requestParameters;
            string uri;

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

                 requestParameters = "visualFeatures=Categories,Description,Color&language=en";

                 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();

                bindingString=JsonPrettyPrint(contentString);
                
            }
           
        }

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


        static string JsonPrettyPrint(string json)
        {
            if (string.IsNullOrEmpty(json))
                return string.Empty;

            json = json.Replace(Environment.NewLine, "").Replace("\t", "");

            StringBuilder sb = new StringBuilder();
            bool quote = false;
            bool ignore = false;
            int offset = 0;
            int indentLength = 3;

            foreach (char ch in json)
            {
                switch (ch)
                {
                    case '"':
                        if (!ignore) quote = !quote;
                        break;
                    case '\'':
                        if (quote) ignore = !ignore;
                        break;
                }

                if (quote)
                    sb.Append(ch);
                else
                {
                    switch (ch)
                    {
                        case '{':
                        case '[':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', ++offset * indentLength));
                            break;
                        case '}':
                        case ']':
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', --offset * indentLength));
                            sb.Append(ch);
                            break;
                        case ',':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', offset * indentLength));
                            break;
                        case ':':
                            sb.Append(ch);
                            sb.Append(' ');
                            break;
                        default:
                            if (ch != ' ') sb.Append(ch);
                            break;
                    }
                }
            }

            return sb.ToString().Trim();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            opf.Title = "Select a picture";
            opf.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
           "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
           "Portable Network Graphic (*.png)|*.png";
            if (opf.ShowDialog() == true)
            {
                NewPic.Source = new BitmapImage(new Uri(opf.FileName));
                imageFilePath = opf.FileName;
            }
        }

XAML Code:

<Window x:Class="WPF_AzureAI.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_AzureAI"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="966.25" Background="#FF6A6969" MaxWidth="966.25" MaxHeight="600">
    <TabControl HorizontalAlignment="Left" Height="580" Margin="0,0,0,0" VerticalAlignment="Top" Width="950">
        <TabItem Header="Azure API">
            <Grid Background="#FF554F4F" Margin="0,0,-11,0">

                <Image Name="NewPic" HorizontalAlignment="Left" Height="203" Margin="42,22,0,0" VerticalAlignment="Top" Width="332">
                    <Image.OpacityMask>
                        <RadialGradientBrush>
                            <GradientStop Color="Black" Offset="0"/>
                            <GradientStop Color="#FF642424" Offset="1"/>
                        </RadialGradientBrush>
                    </Image.OpacityMask>
                </Image>
                <Button Content="Upload" HorizontalAlignment="Left" Margin="270,230,0,0" VerticalAlignment="Top" Width="104" RenderTransformOrigin="1.55,-1.54" Click="Button_Click_1"/>


                <Button Content="Computer Vesion API" HorizontalAlignment="Left" Margin="42,287,0,0" VerticalAlignment="Top" Width="332" Height="30" Click="Button_Click"/>
                <RichTextBox Name="RichTextBox"  HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" HorizontalAlignment="Left" Height="500" Margin="462,22,0,0"   VerticalAlignment="Top" Width="448" Foreground="#FF063A64">

                </RichTextBox>
                            </Grid>
        </TabItem>
      
    </TabControl>
</Window>

Next click to the play button, we can see the output.

You can monitor this API calls & Latency in this azure portal.

Source Download GitHub

Conclusion:

In this article, we have seen learned how to create Azure computer vision API & using C# code with WPF application.

Happy Coding!