Browse Images By Tag Using C# And Azure Cognitive Services

In the following article, we'll see how to develop a program that uses the powerful Azure Cognitive Services to get a list of tags from an image, storing them to further create an application capable of searching images through keywords.

Introduction

In the following article, we'll see how to develop a program that uses the powerful Azure Cognitive Services to get a list of tags from an image, and stores them to further create an application capable of searching images through keywords. The presented source code will be written in C#, and split in two applications: The first one will process a directory, searching for JPEG files and analyzing them through Azure. Cognitive Services results will be saved to an XML file. The second program will simply allow the user to enter a keyword, and scan the XML file to find matches. When a match is found, the images will be shown in a WPF DataGrid.

Before we begin, we must create a Cognitive Service resource on Azure. The following section will cover how to do that.

Create an Azure Computer Vision API resource

Log in to the Azure portal, then click the "Create a resource" link. In the search bar, enter "Computer Vision API", and confirm. Now our browser will show something like the following screenshot. Click "Create" to proceed.

 Azure

Now we can assign a name, a geographic location (select the nearest for less latency), and a pricing tier. For the purposes of the article, the free F0 tier will be a good choice.

In creation confirming, Azure will assign two API keys, which applications need to know and use to access the services functions.

To get the keys, click on the newly created resource, then "Keys" link under "Resource Management"

 Azure

Save one of those keys (a single key will be required) for the following steps.

Write a C# class to use Azure resource

As stated in the Introduction, our source code will be composed of two parts. Here we'll see how to write a simple console app to query Azure Cognitive Services, feeding them with single images we wish to be "seen". The Azure AI will return a set of tags, that will be saved in an XML file for future reference, like a catalog of images along with their descriptive texts.

To achieve that feature, we need first of all a class to communicate with Azure, and some prerequisites.

Let's open Visual Studio, and create a new solution. Add a first project, which will be a Console App. Then, save it and go to Nuget Manager, where two additional packages need to be installed, being them Microsoft.ProjectOxford.Visionand Newtonsoft.Json

 Azure

The following class is used to send a Stream to Azure Computer Vision, and to read the returned values:

  1. using Microsoft.ProjectOxford.Vision;  
  2. using Microsoft.ProjectOxford.Vision.Contract;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7. namespace ivDataGather {  
  8.     class MicrosoftCognitiveCaptionService {  
  9.         private static readonly string ApiKey = "<INSERT YOUR API KEY HERE>";  
  10.         private static readonly string ApiEndpoint = "https://westus.api.cognitive.microsoft.com/vision/v1.0";  
  11.         private static readonly VisualFeature[] VisualFeatures = {  
  12.             VisualFeature.Description,  
  13.             VisualFeature.Tags  
  14.         };  
  15.         public async Task < string > GetTagsAsync(Stream stream) {  
  16.             var client = new VisionServiceClient(ApiKey, ApiEndpoint);  
  17.             var result = await client.AnalyzeImageAsync(stream, VisualFeatures);  
  18.             return ProcessAnalysisResult(result);  
  19.         }  
  20.         private static string ProcessAnalysisResult(AnalysisResult result) {  
  21.             string message = result ? .Description ? .Captions.Count() > 0 ? string.Join(", ", result ? .Description ? .Captions.Select(x => x.Text)) : "";  
  22.             string tags = result ? .Tags ? .Count() > 0 ? string.Join(", ", result ? .Tags ? .Select(x => x.Name)) : "";  
  23.             var list = new List < string > ();  
  24.             message.Split(' ').ToList().ForEach(x => {  
  25.                 list.Add(x.Trim());  
  26.             });  
  27.             tags.Split(',').ToList().ForEach(x => {  
  28.                 list.Add(x.Trim());  
  29.             });  
  30.             return string.Join(",", list.Distinct().ToList());  
  31.         }  
  32.     }  
  33. }  

The first async method, GetTagsAsync, will create a new VisionServiceClient object, given the service API key and the endpoint to use (which is the URL of the service, which could be extracted from Azure, and its based on the chosen geographical location). Here we will query Azure on two features: VisualFeature.Description and VisualFeature.Tags. Those enum values will inform the service we are interested in, reading back only that information.

Once we have received a result, GetTagsAsync will call on a second method, ProcessAnalysisResult. The method will return a string object, based on the Description and Tags properties, which will be parsed and taken as a distinct list, comma separated, transformed in a one-line response.

Develop a console app to process an images folder

With those premises, developing the further steps is trivial. Here follows the console part, which simply parse a given directory for JPEG files, sending them to Azure and awaiting results. When they come back to us, those results will be stored in a TaggedImage list (a custom class we'll see in a moment), to be saved in a serialized XML at the end of the procedure.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Xml.Serialization;  
  6. namespace ivDataGather {  
  7.     class Program {  
  8.         static async void ParseDirectory(string directory, string catalogOutp) {  
  9.             var itemList = new List < TaggedImage > ();  
  10.             var cc = new MicrosoftCognitiveCaptionService();  
  11.             foreach(var f in Directory.GetFiles(directory, "*.jpg")) {  
  12.                 var r = "";  
  13.                 var ms = new FileStream(f, FileMode.Open);  
  14.                 r = await cc.GetTagsAsync(ms);  
  15.                 itemList.Add(new TaggedImage() {  
  16.                     FilePath = f,  
  17.                         Tags = r.Split(',').ToList()  
  18.                 });  
  19.                 Console.WriteLine(f + "\n" + r + "\n");  
  20.                 ms.Dispose();  
  21.             }  
  22.             cc = null;  
  23.             XmlSerializer serialiser = new XmlSerializer(typeof(List < TaggedImage > ));  
  24.             TextWriter fileStream = new StreamWriter(catalogOutp);  
  25.             serialiser.Serialize(fileStream, itemList);  
  26.             fileStream.Close();  
  27.         }  
  28.         static void Main(string[] args) {  
  29.             ParseDirectory(@ "C:\<input_folder>\images", @ "C:\<any_output_folder>\ivcatalog.xml");  
  30.             Console.ReadLine();  
  31.         }  
  32.     }  
  33. }  
  34. using System.Collections.Generic;  
  35. using System.IO;  
  36. using System.Windows.Media.Imaging;  
  37. namespace ivDataGather {  
  38.     public class TaggedImage {  
  39.         public string FilePath {  
  40.             get;  
  41.             set;  
  42.         }  
  43.         public string FileName {  
  44.             get {  
  45.                 return GetFileAttributes() ? .Name;  
  46.             }  
  47.         }  
  48.         public string FileExtension {  
  49.             get {  
  50.                 return GetFileAttributes() ? .Extension;  
  51.             }  
  52.         }  
  53.         public string FileDirectory {  
  54.             get {  
  55.                 return GetFileAttributes() ? .DirectoryName;  
  56.             }  
  57.         }  
  58.         public List < string > Tags {  
  59.             get;  
  60.             set;  
  61.         }  
  62.         public BitmapImage Image {  
  63.             get {  
  64.                 return new BitmapImage(new System.Uri(this.FilePath));  
  65.             }  
  66.         }  
  67.         private FileInfo GetFileAttributes() {  
  68.             return new FileInfo(this.FilePath);  
  69.         }  
  70.     }  
  71. }  

As it can be seen, the TaggedImage class simply contains the found file name and path reference and tags (returned by Azure), plus an Image property which returns a BitmapImage object, i.e. the graphical format for the file. That property will be useful for the second part of the program.

Executing the console app

Let's create a sample folder with some images in it.

 Azure

Running our console app with the path containing the above image will result in something like the following screenshot:

 Azure

In other words, for every found JPG file, the method GetTagsAsync will return a list of words from Azure image analysis. The console app receives that list, then proceed in saving them to an XML file through an XMLSerializer object. The saved file, from the above analysis, will be as follows:

 Azure

That file will be used as a catalog by the WPF application, which will be covered in the next section

Develop a WPF app to search tags and show results

The idea behind that part of the solution is really simple: a TextBox in which to write our search term, a button to start searching, and a DataGrid to show all the found results. Obviously, the search involves the deserialization of our XML catalog. Here we will develop using WPF, to quickly implement - through XAML - an image column for our Datagrid.

The XAML code of our MainWindow will be

  1. <Window x:Class="ivImageFinder.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:ivImageFinder" mc:Ignorable="d" Title="Image finder" Height="350" Width="525">  
  2.     <Grid>  
  3.         <DockPanel HorizontalAlignment="Stretch" LastChildFill="true" VerticalAlignment="Stretch" Background="LightGray">  
  4.             <DockPanel Height="50" LastChildFill="True" VerticalAlignment="Top" DockPanel.Dock="Top" Background="WhiteSmoke">  
  5.                 <Button x:Name="button" Content="Search" Width="75" DockPanel.Dock="Right" FontSize="16" Click="button_Click" />  
  6.                 <TextBox x:Name="searchBox" TextAlignment="Center" VerticalContentAlignment="Center" HorizontalAlignment="Stretch" Text="TextBox" DockPanel.Dock="Left" FontSize="16" /> </DockPanel>  
  7.             <DataGrid x:Name="dataGrid" DockPanel.Dock="Bottom">  
  8.                 <DataGrid.Columns>  
  9.                     <DataGridTemplateColumn Header="Image" Width="300" IsReadOnly="True">  
  10.                         <DataGridTemplateColumn.CellTemplate>  
  11.                             <DataTemplate>  
  12.                                 <Image Source="{Binding Image}" /> </DataTemplate>  
  13.                         </DataGridTemplateColumn.CellTemplate>  
  14.                     </DataGridTemplateColumn>  
  15.                 </DataGrid.Columns>  
  16.             </DataGrid>  
  17.         </DockPanel>  
  18.     </Grid>  
  19. </Window> 
As you can see, the image column is easily created by accessing the DataGrid Columns property, customizing a column to contain an Image control. Here we will bind its contents to a property named "Image" (the same property we saw above in TaggedImage class - so, the ItemSource property of the DataGrid will be a List<TaggedImage>).

That layout will result in the following window:

 Azure

The code behind is trivial and consists mainly of the button click handler:

  1. using ivDataGather;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Windows;  
  6. using System.Xml.Serialization;  
  7. namespace ivImageFinder {  
  8.     /// <summary>  
  9.     /// Interaction logic for MainWindow.xaml  
  10.     /// </summary>  
  11.     public partial class MainWindow: Window {  
  12.         private string catalogPath = @ "C:\<path_to_catalog_file>\ivcatalog.xml";  
  13.         public MainWindow() {  
  14.             InitializeComponent();  
  15.         }  
  16.         private void button_Click(object sender, RoutedEventArgs e) {  
  17.             List < TaggedImage > itemList;  
  18.             using(var reader = new StreamReader(catalogPath)) {  
  19.                 XmlSerializer deserializer = new XmlSerializer(typeof(List < TaggedImage > ));  
  20.                 itemList = (List < TaggedImage > ) deserializer.Deserialize(reader);  
  21.             }  
  22.             dataGrid.ItemsSource = itemList.Where(x => x.Tags.Contains(searchBox.Text));  
  23.         }  
  24.     }  
  25. }  

We have a private variable which specifies the path to our XML catalog. At each button click, the program deserializes the XML content to a List<TaggedImage>, using it as the ItemSource of DataGrid. LINQ is here used to filter only those items which corresponds to the digited text. The Image property will be bound to the Image control of the DataGrid column, showing the desired results.

Here are some examples of searching for keywords

 Azure
Source code

The source code used in the article is freely downloadable  here.

Bibliography