-
Notifications
You must be signed in to change notification settings - Fork 9
/
CustomVisionClassification.cshtml.cs
83 lines (71 loc) · 2.74 KB
/
CustomVisionClassification.cshtml.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction;
using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models;
namespace CogServicesVisionSamples_202107.Pages
{
public class CustomVisionClassificationModel : PageModel
{
// Input from web page
[BindProperty]
public IFormFile ImageFile { get; set; }
// Output to web page
public string ImageFileUrl { get; set; }
public string Result { get; set; }
public IList<PredictionModel> Predictions { get; set; }
// Setting for using Custom Vision
private const string cvPredictionKey = "YOUR_CUSTOMVISION_PREDICTION_KEY";
private const string cvEndpoint = "https://YOUR_SERVICE_NAME.cognitiveservices.azure.com/";
private const string cvProjectId = "YOUR_CUSTOMVISION_PROJECTID";
private const string cvPublishName = "YOUR_CUSTOMVISION_PROJECT_PUBLISHNAME";//"Iteration1"
// Setting for FileIO
private readonly IHostingEnvironment _host;
public CustomVisionClassificationModel(IHostingEnvironment host)
{
_host = host;
}
//public void OnGet()
//{
//}
public async Task<IActionResult> OnPostAsync()
{
// Show image on web page
var imageFilePath = Path.Combine(_host.WebRootPath, "images\\uploadedImage.png");
using (var fileStream = new FileStream(imageFilePath, FileMode.OpenOrCreate))
{
await ImageFile.CopyToAsync(fileStream);
}
ImageFileUrl = "/images/uploadedImage.png";
// Post image to Custom Vision, get resut and show on web page
var cvClient = new CustomVisionPredictionClient(new ApiKeyServiceClientCredentials(cvPredictionKey))
{
Endpoint = cvEndpoint
};
try
{
var cvResult = await cvClient.ClassifyImageAsync(
Guid.Parse(cvProjectId), cvPublishName, ImageFile.OpenReadStream());
if (cvResult.Predictions.Count > 0)
{
Result = "結果:";
Predictions = cvResult.Predictions;
}
else
{
Result = "判定できませんでした";
}
}
catch (CustomVisionErrorException e)
{
Result = "エラー: " + e.Message;
}
return Page();
}
}
}