Azure Cognitive Services Computer Vision Demo using C#

Azure Cognitive Services are a set of cloud-based functions. There are many of these services. Some services are free and some services you have to pay for. One of the interesting services is the Computer Vision Service. You send an image to the service, and the service analyzes the image and sends the analysis results back to you.

Just for fun, I decided to do a minimal demo. How hard could it be? Unfortunately, the official documentation that I initially found is almost comically inept. But after a bit more searching, I found a very nice documentation example and scaled it down.

I sent an image of me giving a recent presentation (above). The Cognitive Services computer vision analysis result was quite good. The analysis-generated caption was, “a group of people standing in front of a crowd.” The analysis also spotted a “laptop” on a “table”, and a “woman” in the crowd.

So, good news, bad news. The good news is that the Computer Vision service is cool. The bad news is that the Computer Vision service documentation needs some help — there’s too much noise and it’s a little bit too hard to find useful information.


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

namespace CogServVisionDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      string image = "C:\\Data\\Junk\\CogServVisionDemo\\mid_room_small.jpg";
      Analyze(image);
      Console.ReadLine();
    }

    static async void Analyze(string image)
    {
      string key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // your key goes here
      HttpClient c = new HttpClient();
      c.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
      string reqParams = "visualFeatures=Categories,Description&language=en";
      string uriBase = "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze";
      string uri = uriBase + "?" + reqParams;

      FileStream fileStream = new FileStream(image, FileMode.Open, FileAccess.Read);
      BinaryReader bReader = new BinaryReader(fileStream);
      byte[] byteData = bReader.ReadBytes((int)fileStream.Length);
      ByteArrayContent content = new ByteArrayContent(byteData);

      content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
      HttpResponseMessage response = await c.PostAsync(uri, content);  // note async above
      string contentString = await response.Content.ReadAsStringAsync();
      Console.WriteLine("\nAnalysis:\n");
      Console.WriteLine(contentString);
    } // Analyze

  } // class Program
} // ns
This entry was posted in Machine Learning. Bookmark the permalink.