Skip to content

Commit 6b7af2e

Browse files
harishkrishnavChrisHMSFT
authored andcommitted
Added Computer Vision sample quickstarts (#36)
* Added quickstarts * Removed TextRecognitionMode in BatchRead * minor corrections * Changed BatchReadText to BatchReadFile * formatting changes * Fixed bug and updated readme * Formatting changes
1 parent 3ba18b4 commit 6b7af2e

17 files changed

+753
-32
lines changed

dotnet/ComputerVision/AnalyzeImage/Program.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,7 @@ static async Task AnalyzeFromStreamAsync(string imageFilePath, string endpoint,
6464
;
6565

6666
// Assemble the URI for the REST API method.
67-
string uriBase = endpoint+@"/vision/v2.0/analyze";
68-
string uri = uriBase + "?" + requestParameters;
67+
string uri = $"{endpoint}/vision/v2.0/analyze?{requestParameters}";
6968

7069
// Read the contents of the specified local image
7170
// into a byte array.
@@ -133,8 +132,7 @@ static async Task AnalyzeFromUrlAsync(string imageUrl, string endpoint, string s
133132
;
134133

135134
//Assemble the URI and content header for the REST API request
136-
string uriBase = endpoint + @"/vision/v2.0/analyze";
137-
string uri = uriBase + "?" + requestParameters;
135+
string uri = $"{endpoint}/vision/v2.0/analyze?{requestParameters}";
138136

139137
string requestBody = " {\"url\":\"" + imageUrl + "\"}";
140138
var content = new StringContent(requestBody);

dotnet/ComputerVision/ExtractText/Microsoft.Azure.CognitiveServices.Samples.ComputerVision.ExtractText.csproj renamed to dotnet/ComputerVision/BatchReadFile/Microsoft.Azure.CognitiveServices.Samples.ComputerVision.BatchReadFile.csproj

File renamed without changes.

dotnet/ComputerVision/ExtractText/Program.cs renamed to dotnet/ComputerVision/BatchReadFile/Program.cs

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
using System.Net.Http.Headers;
66
using System.Threading.Tasks;
77

8-
namespace Microsoft.Azure.CognitiveServices.Samples.ComputerVision.ExtractText
8+
namespace Microsoft.Azure.CognitiveServices.Samples.ComputerVision.BatchReadFile
99
{
1010
using Newtonsoft.Json.Linq;
1111

@@ -16,14 +16,14 @@ public class Program
1616

1717
static void Main(string[] args)
1818
{
19-
ExtractTextSample.RunAsync(endpoint, subscriptionKey).Wait(5000);
19+
BatchReadFileSample.RunAsync(endpoint, subscriptionKey).Wait(5000);
2020

2121
Console.WriteLine("\nPress ENTER to exit.");
2222
Console.ReadLine();
2323
}
2424
}
2525

26-
public class ExtractTextSample
26+
public class BatchReadFileSample
2727
{
2828
public static async Task RunAsync(string endpoint, string key)
2929
{
@@ -32,12 +32,12 @@ public static async Task RunAsync(string endpoint, string key)
3232
string imageFilePath = @"Images\handwritten_text.jpg"; // See this repo's readme.md for info on how to get these images. Alternatively, you can just set the path to any appropriate image on your machine.
3333
string remoteImageUrl = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/printed_text.jpg";
3434

35-
await ExtractTextFromStreamAsync(imageFilePath, endpoint, key, "Handwritten"); //the last parameter is whether the text that has to be extracted is printed or handwritten
36-
await ExtractTextFromUrlAsync(remoteImageUrl, endpoint, key, "Printed"); //This textRecognitionMode can only be either Handwritten or Printed
35+
await BatchReadFileFromStreamAsync(imageFilePath, endpoint, key);
36+
await BatchReadFileFromUrlAsync(remoteImageUrl, endpoint, key);
3737
}
3838

3939

40-
static async Task ExtractTextFromStreamAsync(string imageFilePath, string endpoint, string subscriptionKey, string textRecognitionMode)
40+
static async Task BatchReadFileFromStreamAsync(string imageFilePath, string endpoint, string subscriptionKey)
4141
{
4242
if (!File.Exists(imageFilePath))
4343
{
@@ -55,13 +55,9 @@ static async Task ExtractTextFromStreamAsync(string imageFilePath, string endpoi
5555

5656
// Request headers.
5757
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
58-
59-
// Request parameter indicating whether printed or handwritten text
60-
string requestParameters = @"mode=" + textRecognitionMode;
61-
58+
6259
//Assemble the URI and content header for the REST API request
63-
string uriBase = endpoint+@"/vision/v2.0/read/core/asyncBatchAnalyze";
64-
string uri = uriBase + "?" + requestParameters;
60+
string uri = $"{endpoint}/vision/v2.0/read/core/asyncBatchAnalyze";
6561

6662
// Reads the contents of the specified local image into a byte array.
6763
byte[] byteData = GetImageAsByteArray(imageFilePath);
@@ -144,7 +140,7 @@ static async Task WaitForExtractTextOperationResultAsync(HttpClient client, Http
144140
/// <summary>
145141
/// Gets the text from the specified image URL by using the Computer Vision REST API.
146142
/// </summary>
147-
static async Task ExtractTextFromUrlAsync(string remoteImgUrl, string endpoint, string subscriptionKey, string textRecognitionMode)
143+
static async Task BatchReadFileFromUrlAsync(string remoteImgUrl, string endpoint, string subscriptionKey)
148144
{
149145
if (!Uri.IsWellFormedUriString(remoteImgUrl, UriKind.Absolute))
150146
{
@@ -157,9 +153,7 @@ static async Task ExtractTextFromUrlAsync(string remoteImgUrl, string endpoint,
157153
//Assemble the URI and content header for the REST API request
158154
HttpClient client = new HttpClient();
159155
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
160-
string requestParameters = @"mode=" + textRecognitionMode; //The request parameter textRecognitionMode has to be either "Handwritten" or "Printed"
161-
string uriBase = endpoint + @"/vision/v2.0/read/core/asyncBatchAnalyze";
162-
string uri = uriBase + "?" + requestParameters;
156+
string uri = $"{endpoint}/vision/v2.0/read/core/asyncBatchAnalyze";
163157
string requestBody = " {\"url\":\"" + remoteImgUrl + "\"}";
164158
var content = new StringContent(requestBody);
165159
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

dotnet/ComputerVision/ComputerVision.sln

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,23 @@ Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio 15
44
VisualStudioVersion = 15.0.28307.539
55
MinimumVisualStudioVersion = 10.0.40219.1
6-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnalyzeImage", "AnalyzeImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.AnalyzeImage.csproj", "{D80D48F2-F52C-4649-A298-FB9F22668B19}"
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.AnalyzeImage", "AnalyzeImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.AnalyzeImage.csproj", "{D80D48F2-F52C-4649-A298-FB9F22668B19}"
77
EndProject
8-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DetectObjects", "DetectObjects\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DetectObjects.csproj", "{ECC75ECA-5F9E-49FA-8480-B94A8A5DBB97}"
8+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DetectObjects", "DetectObjects\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DetectObjects.csproj", "{ECC75ECA-5F9E-49FA-8480-B94A8A5DBB97}"
99
EndProject
10-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExtractText", "ExtractText\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.ExtractText.csproj", "{C813CB28-39BD-4383-A59B-99020576057F}"
10+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.BatchReadFile", "BatchReadFile\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.BatchReadFile.csproj", "{C813CB28-39BD-4383-A59B-99020576057F}"
1111
EndProject
12-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OCR", "OCR\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.OCR.csproj", "{F3F98FCD-728E-424C-A66E-64F5F0870298}"
12+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.OCR", "OCR\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.OCR.csproj", "{F3F98FCD-728E-424C-A66E-64F5F0870298}"
13+
EndProject
14+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DescribeImage", "DescribeImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DescribeImage.csproj", "{236A621F-1422-4F11-A1DB-63A98FA81964}"
15+
EndProject
16+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetAreaOfInterest", "GetAreaOfInterest\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetAreaOfInterest.csproj", "{13CD735C-6C88-4C7D-9084-13924F9012DF}"
17+
EndProject
18+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.TagImage", "TagImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.TagImage.csproj", "{6F9E7415-FD2A-475C-A668-DB83D29DCBAE}"
19+
EndProject
20+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeDomainSpecificContent", "RecognizeDomainSpecificContent\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeDomainSpecificContent.csproj", "{AFDFD5AC-2E2D-46C0-A25D-0AF09C6A89D8}"
21+
EndProject
22+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeText", "RecognizeText\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeText.csproj", "{C024B030-8CA9-4239-9C89-371B24E029CE}"
1323
EndProject
1424
Global
1525
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -33,6 +43,26 @@ Global
3343
{F3F98FCD-728E-424C-A66E-64F5F0870298}.Debug|Any CPU.Build.0 = Debug|Any CPU
3444
{F3F98FCD-728E-424C-A66E-64F5F0870298}.Release|Any CPU.ActiveCfg = Release|Any CPU
3545
{F3F98FCD-728E-424C-A66E-64F5F0870298}.Release|Any CPU.Build.0 = Release|Any CPU
46+
{236A621F-1422-4F11-A1DB-63A98FA81964}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
47+
{236A621F-1422-4F11-A1DB-63A98FA81964}.Debug|Any CPU.Build.0 = Debug|Any CPU
48+
{236A621F-1422-4F11-A1DB-63A98FA81964}.Release|Any CPU.ActiveCfg = Release|Any CPU
49+
{236A621F-1422-4F11-A1DB-63A98FA81964}.Release|Any CPU.Build.0 = Release|Any CPU
50+
{13CD735C-6C88-4C7D-9084-13924F9012DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
51+
{13CD735C-6C88-4C7D-9084-13924F9012DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
52+
{13CD735C-6C88-4C7D-9084-13924F9012DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
53+
{13CD735C-6C88-4C7D-9084-13924F9012DF}.Release|Any CPU.Build.0 = Release|Any CPU
54+
{6F9E7415-FD2A-475C-A668-DB83D29DCBAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
55+
{6F9E7415-FD2A-475C-A668-DB83D29DCBAE}.Debug|Any CPU.Build.0 = Debug|Any CPU
56+
{6F9E7415-FD2A-475C-A668-DB83D29DCBAE}.Release|Any CPU.ActiveCfg = Release|Any CPU
57+
{6F9E7415-FD2A-475C-A668-DB83D29DCBAE}.Release|Any CPU.Build.0 = Release|Any CPU
58+
{AFDFD5AC-2E2D-46C0-A25D-0AF09C6A89D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
59+
{AFDFD5AC-2E2D-46C0-A25D-0AF09C6A89D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
60+
{AFDFD5AC-2E2D-46C0-A25D-0AF09C6A89D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
61+
{AFDFD5AC-2E2D-46C0-A25D-0AF09C6A89D8}.Release|Any CPU.Build.0 = Release|Any CPU
62+
{C024B030-8CA9-4239-9C89-371B24E029CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
63+
{C024B030-8CA9-4239-9C89-371B24E029CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
64+
{C024B030-8CA9-4239-9C89-371B24E029CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
65+
{C024B030-8CA9-4239-9C89-371B24E029CE}.Release|Any CPU.Build.0 = Release|Any CPU
3666
EndGlobalSection
3767
GlobalSection(SolutionProperties) = preSolution
3868
HideSolutionNode = FALSE
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFrameworks>netcoreapp2.0;net461;netstandard1.4</TargetFrameworks>
6+
</PropertyGroup>
7+
8+
<ItemGroup>
9+
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
10+
</ItemGroup>
11+
12+
</Project>
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
using System;
2+
using System.IO;
3+
using System.Net.Http;
4+
using System.Net.Http.Headers;
5+
using System.Threading.Tasks;
6+
7+
namespace Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DescribeImage
8+
{
9+
using Newtonsoft.Json.Linq;
10+
11+
class Program
12+
{
13+
public const string subscriptionKey = "<your training key here>"; //Insert your Cognitive Services subscription key here
14+
public const string endpoint = "https://westus.api.cognitive.microsoft.com"; // You must use the same Azure region that you generated your subscription keys for. Free trial subscription keys are generated in the westus region.
15+
16+
static void Main(string[] args)
17+
{
18+
DescribeImageSample.RunAsync(endpoint, subscriptionKey).Wait(5000);
19+
20+
Console.WriteLine("\nPress ENTER to exit.");
21+
Console.ReadLine();
22+
}
23+
}
24+
25+
public class DescribeImageSample
26+
{
27+
public static async Task RunAsync(string endpoint, string key)
28+
{
29+
Console.WriteLine("Describe an image:");
30+
31+
string imageFilePath = @"Images\objects.jpg"; // See this repo's readme.md for info on how to get these images. Alternatively, you can just set the path to any appropriate image on your machine.
32+
string remoteImageUrl = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/celebrities.jpg";
33+
34+
await DescribeImageFromStreamAsync(imageFilePath, endpoint, key);
35+
await DescribeImageFromUrlAsync(remoteImageUrl, endpoint, key);
36+
}
37+
38+
static async Task DescribeImageFromStreamAsync(string imageFilePath, string endpoint, string subscriptionKey)
39+
{
40+
if (!File.Exists(imageFilePath))
41+
{
42+
Console.WriteLine("\nInvalid file path");
43+
return;
44+
}
45+
try
46+
{
47+
HttpClient client = new HttpClient();
48+
49+
// Request headers.
50+
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
51+
string uri = $"{endpoint}/vision/v2.0/describe";
52+
// Read the contents of the specified local image into a byte array.
53+
byte[] byteData = GetImageAsByteArray(imageFilePath);
54+
// Add the byte array as an octet stream to the request body.
55+
using (ByteArrayContent content = new ByteArrayContent(byteData))
56+
{
57+
// This example uses the "application/octet-stream" content type.
58+
// The other content types you can use are "application/json" and "multipart/form-data".
59+
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
60+
61+
// Asynchronously call the REST API method.
62+
HttpResponseMessage response = await client.PostAsync(uri, content);
63+
// Asynchronously get the JSON response.
64+
string contentString = await response.Content.ReadAsStringAsync();
65+
// Display the JSON response.
66+
Console.WriteLine("\nResponse:\n\n{0}\n", JToken.Parse(contentString).ToString());
67+
}
68+
}
69+
catch (Exception e)
70+
{
71+
Console.WriteLine("\n" + e.Message);
72+
}
73+
}
74+
75+
static byte[] GetImageAsByteArray(string imageFilePath)
76+
{
77+
// Open a read-only file stream for the specified file.
78+
using (FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
79+
{
80+
// Read the file's contents into a byte array.
81+
BinaryReader binaryReader = new BinaryReader(fileStream);
82+
return binaryReader.ReadBytes((int)fileStream.Length);
83+
}
84+
}
85+
86+
static async Task DescribeImageFromUrlAsync(string imageUrl, string endpoint, string subscriptionKey)
87+
{
88+
if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
89+
{
90+
Console.WriteLine("\nInvalid remote image url:\n{0} \n", imageUrl);
91+
return;
92+
}
93+
try
94+
{
95+
HttpClient client = new HttpClient();
96+
// Request headers
97+
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
98+
string uri = $"{endpoint}/vision/v2.0/describe";
99+
100+
string requestBody = " {\"url\":\"" + imageUrl + "\"}";
101+
var content = new StringContent(requestBody);
102+
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
103+
104+
// Post the request and display the result
105+
HttpResponseMessage response = await client.PostAsync(uri, content);
106+
string contentString = await response.Content.ReadAsStringAsync();
107+
Console.WriteLine("\nResponse:\n\n{0}\n", JToken.Parse(contentString).ToString());
108+
}
109+
catch (Exception e)
110+
{
111+
Console.WriteLine("\n" + e.Message);
112+
}
113+
}
114+
}
115+
}

dotnet/ComputerVision/DetectObjects/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ static async Task DetectObjectsFromStreamAsync(string imageFilePath, string endp
4848

4949
// Request headers.
5050
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
51-
string uri = endpoint+@"/vision/v2.0/detect";
51+
string uri = $"{endpoint}/vision/v2.0/detect";
5252
// Read the contents of the specified local image into a byte array.
5353
byte[] byteData = GetImageAsByteArray(imageFilePath);
5454
// Add the byte array as an octet stream to the request body.
@@ -95,7 +95,7 @@ static async Task DetectObjectsFromUrlAsync(string imageUrl, string endpoint, st
9595
HttpClient client = new HttpClient();
9696
// Request headers
9797
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
98-
string uri = endpoint + @"/vision/v2.0/detect";
98+
string uri = $"{endpoint}/vision/v2.0/detect";
9999

100100
string requestBody = " {\"url\":\"" + imageUrl + "\"}";
101101
var content = new StringContent(requestBody);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFrameworks>netcoreapp2.0;net461;netstandard1.4</TargetFrameworks>
6+
</PropertyGroup>
7+
8+
<ItemGroup>
9+
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
10+
</ItemGroup>
11+
12+
</Project>

0 commit comments

Comments
 (0)