-
Notifications
You must be signed in to change notification settings - Fork 90
/
ImageAnalyzer.cs
284 lines (235 loc) · 10.6 KB
/
ImageAnalyzer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.Psi.CognitiveServices.Vision
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using Microsoft.Psi;
using Microsoft.Psi.Imaging;
/// <summary>
/// Component that performs image analysis via <a href="https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/">Microsoft Cognitive Services Vision API</a>.
/// </summary>
/// <remarks>A <a href="https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/">Microsoft Cognitive Services Vision API</a>
/// subscription key is required to use this component. For more information, see the full direct API for.
/// <a href="https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/">Microsoft Cognitive Services Vision API</a></remarks>
public sealed class ImageAnalyzer : IConsumer<Shared<Image>>, IProducer<ImageAnalysis>
{
private readonly ComputerVisionClient computerVisionClient;
private readonly ImageAnalyzerConfiguration configuration;
/// <summary>
/// Initializes a new instance of the <see cref="ImageAnalyzer"/> class.
/// </summary>
/// <param name="pipeline">The pipeline to add the component to.</param>
/// <param name="configuration">The image analyzer configuration.</param>
public ImageAnalyzer(Pipeline pipeline, ImageAnalyzerConfiguration configuration = null)
{
this.configuration = configuration ?? new ImageAnalyzerConfiguration();
this.Out = pipeline.CreateEmitter<ImageAnalysis>(this, nameof(this.Out));
this.In = pipeline.CreateAsyncReceiver<Shared<Image>>(this, this.ReceiveAsync, nameof(this.In));
this.computerVisionClient = this.CreateClient();
}
/// <summary>
/// Gets the input stream of images.
/// </summary>
public Receiver<Shared<Image>> In { get; }
/// <summary>
/// Gets the output stream of analysis results.
/// </summary>
public Emitter<ImageAnalysis> Out { get; }
#region Static methods for parsing results to strings
/// <summary>
/// Parse Analysis Result into a string.
/// </summary>
/// <param name="result">Analysis Result.</param>
/// <returns>Returns a string corresponding to the analysis result.</returns>
internal static string AnalysisResultToString(ImageAnalysis result)
{
string resultString = string.Empty;
if (result == null)
{
return resultString;
}
if (result.Metadata != null)
{
resultString = $"Image Format : {result.Metadata.Format}\nImage Dimensions : {result.Metadata.Width} x {result.Metadata.Height}\n";
}
resultString = $"{resultString}{DescriptionToString(result.Description)}{FacesToString(result.Faces)}{TagsToString(result.Tags)}{CategoriesToString(result.Categories)}" +
$"{ColorToString(result.Color)}{AdultToString(result.Adult)}{ImageTypeToString(result.ImageType)}";
return resultString;
}
private static string FacesToString(IList<FaceDescription> faces)
{
string resultString = string.Empty;
if (faces != null && faces.Count > 0)
{
resultString = "Faces : \n";
foreach (var face in faces)
{
resultString = $"{resultString}\tAge : {face.Age}; Gender : {face.Gender}\n";
}
}
return resultString;
}
private static string TagsToString(IList<ImageTag> tags)
{
string resultString = string.Empty;
if (tags != null)
{
resultString = "Tags : \n";
foreach (var tag in tags)
{
resultString = $"{resultString}\tName : {tag.Name}; Confidence : {tag.Confidence}; Hint : {tag.Hint}\n";
}
}
return resultString;
}
private static string CategoriesToString(IList<Category> categories)
{
string resultString = string.Empty;
if (categories != null && categories.Count > 0)
{
resultString = $"Categories : \n";
foreach (var category in categories)
{
resultString = $"{resultString}\tName : {category.Name}; Score : {category.Score}\n";
}
}
return resultString;
}
private static string ImageTypeToString(ImageType imageType)
{
string resultString = string.Empty;
if (imageType != null)
{
string clipArtType;
switch (imageType.ClipArtType)
{
case 0:
clipArtType = "0 Non-clipart";
break;
case 1:
clipArtType = "1 ambiguous";
break;
case 2:
clipArtType = "2 normal-clipart";
break;
case 3:
clipArtType = "3 good-clipart";
break;
default:
clipArtType = "Unknown";
break;
}
resultString = $"Clip Art Type : {clipArtType}\n";
string lineDrawingType;
switch (imageType.LineDrawingType)
{
case 0:
lineDrawingType = "0 Non-LineDrawing";
break;
case 1:
lineDrawingType = "1 LineDrawing";
break;
default:
lineDrawingType = "Unknown";
break;
}
resultString = $"{resultString}Line Drawing Type : {lineDrawingType}\n";
}
return resultString;
}
private static string AdultToString(AdultInfo adult)
{
string resultString = string.Empty;
if (adult != null)
{
resultString = $"Is Adult Content : {adult.IsAdultContent}\nAdult Score : {adult.AdultScore}\n" +
$"Is Racy Content : {adult.IsRacyContent}\nRacy Score : {adult.RacyScore}\n";
}
return resultString;
}
private static string DescriptionToString(ImageDescriptionDetails description)
{
string resultString = string.Empty;
if (description != null)
{
resultString = "Description : \n";
foreach (var caption in description.Captions)
{
resultString = $"{resultString}\tCaption : {caption.Text}; Confidence : {caption.Confidence}\n";
}
string tags = "\tTags : ";
foreach (var tag in description.Tags)
{
tags += tag + ", ";
}
resultString = $"{resultString}{tags}\n";
}
return resultString;
}
private static string ColorToString(ColorInfo color)
{
string resultString = string.Empty;
if (color != null)
{
resultString = $"AccentColor : {color.AccentColor}\n";
resultString = $"{resultString}Dominant Color Background : {color.DominantColorBackground}\n";
resultString = $"{resultString}Dominant Color Foreground : {color.DominantColorForeground}\n";
if (color.DominantColors != null && color.DominantColors.Count > 0)
{
string colors = "Dominant Colors : ";
foreach (var c in color.DominantColors)
{
colors += c + " ";
}
resultString = $"{resultString}{colors}\n";
}
}
return resultString;
}
#endregion
private async Task ReceiveAsync(Shared<Image> data, Envelope e)
{
var analysisResult = default(ImageAnalysis);
if (data != null && data.Resource != null)
{
using Stream imageFileStream = new MemoryStream();
// convert image to a stream and send to service
data.Resource.ToBitmap(false).Save(imageFileStream, System.Drawing.Imaging.ImageFormat.Jpeg);
imageFileStream.Seek(0, SeekOrigin.Begin);
try
{
analysisResult = await this.computerVisionClient?.AnalyzeImageInStreamAsync(imageFileStream, this.configuration.VisualFeatures);
}
catch
{
// automatically swallow exceptions
}
}
this.Out.Post(analysisResult, e.OriginatingTime);
}
private ComputerVisionClient CreateClient()
{
if (string.IsNullOrEmpty(this.configuration.SubscriptionKey))
{
throw new InvalidOperationException(
$"In order to use this component, you must specify a valid Azure ComputerVision subscription key in the {nameof(ImageAnalyzerConfiguration.SubscriptionKey)} property of the {nameof(ImageAnalyzerConfiguration)} object used to initialize this component.");
}
if (string.IsNullOrEmpty(this.configuration.Region))
{
throw new InvalidOperationException(
$"In order to use this component, you must set the {nameof(ImageAnalyzerConfiguration.Region)} property of the {nameof(ImageAnalyzerConfiguration)} object used to initialize this component to the location of the ComputerVision resource in your Azure subscription, (e.g. westus, westus2, etc.).");
}
return new ComputerVisionClient(
new ApiKeyServiceClientCredentials(this.configuration.SubscriptionKey),
new System.Net.Http.DelegatingHandler[] { })
{
Endpoint = string.Format("https://{0}.api.cognitive.microsoft.com/", this.configuration.Region),
};
}
}
}