private Boolean ClassificationTest(CustomVisionPredictionClient predictionApi) { Console.WriteLine("Making a prediction:"); String filename = "C:\\Users\\User\\Desktop\\TestRec\\Pic\\KinectCapture"; filename = filename + this.skeletonDetectedCount.ToString(); filename = filename + ".png"; using (var stream = File.OpenRead(filename)) { System.Guid projectID = new Guid("8267e789-cff6-4c76-a901-782c6dfc3f04"); //เอาจากlinkของ Project ใน customvision.ai/projects/<ProjectID>#/manage Console.WriteLine("Making a prediction:"); var result = predictionApi.ClassifyImage(projectID, "lightdark", stream); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); if (c.Probability > 0.6 && c.TagName == "dark") { return(true); } } return(false); } }
static void Main(string[] args) { string apiKey = "fe3cedd23a9a480fb25bd91184ebb681"; string endpoint = "https://westeurope.api.cognitive.microsoft.com"; var client = new CustomVisionPredictionClient(); client.ApiKey = apiKey; client.Endpoint = endpoint; var files = Directory.GetFiles(Environment.CurrentDirectory, "*.jpg"); foreach (var file in files) { using (var stream = File.OpenRead(file)) { var result = client.ClassifyImage(Guid.Parse("5da6478e-b413-4512-be92-1c4bb502893f"), "Iteration2", stream); foreach (var p in result.Predictions) { System.Console.WriteLine($"{p.TagName} {p.Probability:P4}"); } } } }
public void MakePredictionRequest(string imageFilePath, IConfiguration configuration) { CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = configuration.GetSection("AzureKeys:PredictionKey").Value, Endpoint = "https://centralindia.api.cognitive.microsoft.com" }; using (var stream = System.IO.File.OpenRead(imageFilePath)) { var result = endpoint.ClassifyImage(Guid.Parse(System.IO.File.ReadAllText(@"./ProjectId.txt")), System.IO.File.ReadAllText(@"./PublishedModelName.txt"), System.IO.File.OpenRead(imageFilePath)); //Loop over each prediction and write out the results foreach (var c in result.Predictions) { if (c.Probability > 0.80) { tag_name = c.TagName; } //Console.WriteLine($"\t{c.TagName}: {c.Probability:P1} [ {c.BoundingBox.Left}, {c.BoundingBox.Top}, {c.BoundingBox.Width}, {c.BoundingBox.Height} ]"); } } }
public async Task <string> Analyze(string imageUrl) { var image = await Client.GetByteArrayAsync(imageUrl); var result = _predictionClient.ClassifyImage( projectId: new Guid("<guid>"), publishedName: "Iteration1", imageData: new MemoryStream(image)); return(result.Predictions.OrderByDescending(x => x.Probability).First().TagName); }
public async Task <string> Analyze(string imageUrl) { var image = await Client.GetByteArrayAsync(imageUrl); var result = _predictionClient.ClassifyImage( projectId: new Guid("efdba214-6789-43ed-aece-098e8d0bb54a"), publishedName: "minilitwareLab", imageData: new MemoryStream(image)); return(result.Predictions.OrderByDescending(x => x.Probability).First().TagName); }
// </snippet_publish> // <snippet_test> private static void TestIteration(CustomVisionPredictionClient predictionApi, Project project) { // Make a prediction against the new project Console.WriteLine("Making a prediction:"); var result = predictionApi.ClassifyImage(project.Id, publishedModelName, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); } }
static async Task <Dictionary <string, double> > ClassifyImage(CustomVisionPredictionClient endpoint, Project project, string publishedModelName, Dictionary <string, double> classificationResults) { // Make a prediction with given image var result = endpoint.ClassifyImage(project.Id, publishedModelName, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { classificationResults.Add(c.TagName, c.Probability); } return(classificationResults); }
public ImagePrediction MakePrediction(string localfile) { CustomVisionPredictionClient client = new CustomVisionPredictionClient() { ApiKey = "key", Endpoint = "prediction url from admin console" }; Guid projectId = new Guid("project GUID"); ImagePrediction imagePrediction = null; MemoryStream testImage = new MemoryStream(File.ReadAllBytes(localfile)); client.ClassifyImage(projectId, "DataEventProject", testImage); return(imagePrediction); }
public bool Predict() { bool trueForDrinking = false; // Create a prediction endpoint, passing in obtained prediction key CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = SouthCentralUsEndpoint }; // Make a prediction against the new project ConcurrentLogger.WriteLine("Making a prediction:"); try { var toPredict = Directory.GetFiles(Path.Combine("Picture", "Prediction")).ToList(); var testImage = new MemoryStream(File.ReadAllBytes(toPredict[0])); var result = endpoint.ClassifyImage(project.Id, publishedModelName, testImage); foreach (var c in result.Predictions) { ConcurrentLogger.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); if ((c.TagName == "Drinking") && (c.Probability > 0.5)) { trueForDrinking = true; } } Thread.Sleep(3000); toPredict = Directory.GetFiles(Path.Combine("Picture", "Prediction")).ToList(); foreach (string file in toPredict) { File.Delete(file); ConcurrentLogger.WriteLine($"\tDeleted file: {file}"); } } catch (Exception) { } return(trueForDrinking); }
static void Main(string[] args) { // Create a CustomVisionPredictionClient, initialize it with the settings of your // Custom Vision project and send a file over to classify. var client = new CustomVisionPredictionClient(new ApiKeyServiceClientCredentials(Constants.CV_KEY)) { Endpoint = Constants.ENDPOINT }; using var stream = File.Open("<YOUR_TESTFILE_NAME>", FileMode.Open); var prediction = client.ClassifyImage(Constants.PROJECT_ID, Constants.PUBLISHED_NAME, stream); foreach (var pred in prediction.Predictions) { Console.WriteLine($"{pred.TagName}: {pred.Probability}"); } Console.ReadLine(); }
static void Main(string[] args) { try { // Get Configuration Settings IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); IConfigurationRoot configuration = builder.Build(); string prediction_endpoint = configuration["PredictionEndpoint"]; string prediction_key = configuration["PredictionKey"]; Guid project_id = Guid.Parse(configuration["ProjectID"]); string model_name = configuration["ModelName"]; // Authenticate a client for the prediction API prediction_client = new CustomVisionPredictionClient(new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.ApiKeyServiceClientCredentials(prediction_key)) { Endpoint = prediction_endpoint }; // Classify test images String[] images = Directory.GetFiles("test-images"); foreach (var image in images) { Console.Write(image + ": "); MemoryStream image_data = new MemoryStream(File.ReadAllBytes(image)); var result = prediction_client.ClassifyImage(project_id, model_name, image_data); // Loop over each label prediction and print any with probability > 50% foreach (var prediction in result.Predictions) { if (prediction.Probability > 0.5) { Console.WriteLine($"{prediction.TagName} ({prediction.Probability:P1})"); } } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
protected List <TagPrediction> CheckImageData(byte[] imgBytes) { // Create a prediction endpoint, passing in obtained prediction key CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = endpointUrl }; CustomVisionTrainingClient trainingApi = new CustomVisionTrainingClient() { ApiKey = trainingKey, Endpoint = endpointUrl }; var allTags = trainingApi.GetTags(PROJECT_ID); using (MemoryStream mem = new MemoryStream(imgBytes)) { // Make a prediction against the new project var result = endpoint.ClassifyImage(PROJECT_ID, PUBLISHED_MODEL_NAME, mem); List <TagPrediction> predicts = new List <TagPrediction>(); foreach (var entry in result.Predictions) { Tag tag = allTags.Where(k => k.Id == entry.TagId).First(); predicts.Add(new TagPrediction() { TagDesc = tag.Description, TagId = entry.TagId, TagName = entry.TagName, TagProbability = entry.Probability }); } return(predicts); } }
static void Main(string[] args) { CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = endPoint }; IDictionary <string, string> dadosImagens = JsonConvert.DeserializeObject <IDictionary <string, string> >(File.ReadAllText("opcoes.json")); Console.WriteLine("Selecione a imagem de teste."); string opcao = Console.ReadLine(); var imagemTeste = new MemoryStream(File.ReadAllBytes(dadosImagens[opcao])); var result = endpoint.ClassifyImage(new Guid("80b63914-a25c-4bcb-a483-4c8e261357a0"), "treeClassModel", imagemTeste); foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); } }
static void Main(string[] args) { // Add your training & prediction key from the settings page of the portal string trainingKey = "16e883656e9746e0a9dc2744bc5d511a"; string predictionKey = "3b069625032d4d6686f7de3cb62e1c4a"; // Create the Api, passing in the training key CustomVisionTrainingClient trainingApi = new CustomVisionTrainingClient() { ApiKey = trainingKey, Endpoint = SouthCentralUsEndpoint }; // Create a new project Console.WriteLine("Creating new project:"); Project project = null; if (!IsSurfaceClassification) { project = trainingApi.CreateProject("Flowers"); // Make two tags in the new project var hemlockTag = trainingApi.CreateTag(project.Id, "Hemlock"); var japaneseCherryTag = trainingApi.CreateTag(project.Id, "Japanese Cherry"); // Add some images to the tags Console.WriteLine("\tUploading images"); LoadFlowerImagesFromDisk(); // Images can be uploaded one at a time foreach (var image in hemlockImages) { using (var stream = new MemoryStream(File.ReadAllBytes(image))) { trainingApi.CreateImagesFromData(project.Id, stream, new List <Guid>() { hemlockTag.Id }); } } // Or uploaded in a single batch var imageFiles = japaneseCherryImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>() { japaneseCherryTag.Id })); } else { project = trainingApi.CreateProject("Surface"); // Make two tags in the new project var surfaceProTag = trainingApi.CreateTag(project.Id, "surface-pro"); var surfaceStudioTag = trainingApi.CreateTag(project.Id, "surface-studio"); // Add some images to the tags Console.WriteLine("\tUploading images"); LoadSurfaceImagesFromDisk(); // Images can be uploaded one at a time foreach (var image in surfaceProImages) { using (var stream = new MemoryStream(File.ReadAllBytes(image))) { trainingApi.CreateImagesFromData(project.Id, stream, new List <Guid>() { surfaceProTag.Id }); } } // Or uploaded in a single batch var imageFiles = surfaceStudioImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>() { surfaceStudioTag.Id })); } // Now there are images with tags start training the project Console.WriteLine("\tTraining"); var iteration = trainingApi.TrainProject(project.Id); // The returned iteration will be in progress, and can be queried periodically to see when it has completed while (iteration.Status == "Training") { Thread.Sleep(1000); // Re-query the iteration to get it's updated status iteration = trainingApi.GetIteration(project.Id, iteration.Id); } // The iteration is now trained. Publish it to the prediction end point. var publishedModelName = PublishedModelName; var predictionResourceId = PredictionResourceId; trainingApi.PublishIteration(project.Id, iteration.Id, publishedModelName, predictionResourceId); Console.WriteLine("Done!\n"); // Now there is a trained endpoint, it can be used to make a prediction // Create a prediction endpoint, passing in obtained prediction key CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = SouthCentralUsEndpoint }; // Make a prediction against the new project Console.WriteLine("Making a prediction:"); var result = endpoint.ClassifyImage(project.Id, publishedModelName, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); } Console.ReadKey(); }
static void Main(string[] args) { // Add your Azure Custom Vision subscription key and endpoint to your environment variables. // <snippet_endpoint> string ENDPOINT = Environment.GetEnvironmentVariable("CUSTOM_VISION_ENDPOINT"); // </snippet_endpoint> // <snippet_keys> // Add your training & prediction key from the settings page of the portal string trainingKey = Environment.GetEnvironmentVariable("CUSTOM_VISION_TRAINING_KEY"); string predictionKey = Environment.GetEnvironmentVariable("CUSTOM_VISION_PREDICTION_KEY"); // </snippet_keys> // <snippet_create> // Create the Api, passing in the training key CustomVisionTrainingClient trainingApi = new CustomVisionTrainingClient() { ApiKey = trainingKey, Endpoint = ENDPOINT }; // Create a new project Console.WriteLine("Creating new project:"); var project = trainingApi.CreateProject("My New Project"); // </snippet_create> // <snippet_tags> // Make two tags in the new project var hemlockTag = trainingApi.CreateTag(project.Id, "Hemlock"); var japaneseCherryTag = trainingApi.CreateTag(project.Id, "Japanese Cherry"); // </snippet_tags> // <snippet_upload> // Add some images to the tags Console.WriteLine("\tUploading images"); LoadImagesFromDisk(); // Images can be uploaded one at a time foreach (var image in hemlockImages) { using (var stream = new MemoryStream(File.ReadAllBytes(image))) { trainingApi.CreateImagesFromData(project.Id, stream, new List <Guid>() { hemlockTag.Id }); } } // </snippet_upload> // Or uploaded in a single batch var imageFiles = japaneseCherryImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>() { japaneseCherryTag.Id })); // <snippet_train> // Now there are images with tags start training the project Console.WriteLine("\tTraining"); var iteration = trainingApi.TrainProject(project.Id); // The returned iteration will be in progress, and can be queried periodically to see when it has completed while (iteration.Status == "Training") { Thread.Sleep(1000); // Re-query the iteration to get it's updated status iteration = trainingApi.GetIteration(project.Id, iteration.Id); } // The iteration is now trained. Publish it to the prediction end point. var publishedModelName = "treeClassModel"; var predictionResourceId = "<target prediction resource ID>"; trainingApi.PublishIteration(project.Id, iteration.Id, publishedModelName, predictionResourceId); Console.WriteLine("Done!\n"); // </snippet_train> // Now there is a trained endpoint, it can be used to make a prediction // <snippet_prediction_endpoint> // Create a prediction endpoint, passing in obtained prediction key CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = ENDPOINT }; // </snippet_prediction_endpoint> // <snippet_prediction> // Make a prediction against the new project Console.WriteLine("Making a prediction:"); var result = endpoint.ClassifyImage(project.Id, publishedModelName, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); } Console.ReadKey(); // </snippet_prediction> }
static void Main(string[] args) { //don't forget the other project //don't forget the custom vision portal https://www.customvision.ai/projects //use the custom vision portal to navigate to a project and unpublish // Add your Azure Custom Vision subscription key and endpoint to your environment variables. // <snippet_endpoint> string ENDPOINT = "https://stcustomvision-prediction.cognitiveservices.azure.com/"; // </snippet_endpoint> // <snippet_keys> // Add your training & prediction key from the settings page of the portal string trainingKey = "76fdb20ae1eb49e28733221e202909a5"; string predictionKey = "74ad2b8d75fa4e4db72f23149516bcdd"; // </snippet_keys> // <snippet_create> // Create the Api, passing in the training key CustomVisionTrainingClient trainingApi = new CustomVisionTrainingClient() { ApiKey = trainingKey, Endpoint = ENDPOINT }; // Create a new project Console.WriteLine("Creating new project:"); var project = trainingApi.CreateProject("My New ImageClassification Project"); // </snippet_create> // <snippet_tags> // Make two tags in the new project var hemlockTag = trainingApi.CreateTag(project.Id, "Hemlock"); var japaneseCherryTag = trainingApi.CreateTag(project.Id, "Japanese Cherry"); // </snippet_tags> // <snippet_upload> // Add some images to the tags Console.WriteLine("\tUploading images"); LoadImagesFromDisk(); // Images can be uploaded one at a time foreach (var image in hemlockImages) { using (var stream = new MemoryStream(File.ReadAllBytes(image))) { trainingApi.CreateImagesFromData(project.Id, stream, new List <Guid>() { hemlockTag.Id }); } } // </snippet_upload> // Or uploaded in a single batch var imageFiles = japaneseCherryImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>() { japaneseCherryTag.Id })); // <snippet_train> // Now there are images with tags start training the project Console.WriteLine("\tTraining"); var iteration = trainingApi.TrainProject(project.Id); // The returned iteration will be in progress, and can be queried periodically to see when it has completed while (iteration.Status == "Training") { Thread.Sleep(1000); // Re-query the iteration to get it's updated status iteration = trainingApi.GetIteration(project.Id, iteration.Id); } // The iteration is now trained. Publish it to the prediction end point. var publishedModelName = "treeClassModel"; var predictionResourceId = "/subscriptions/a0980536-0ea6-4373-9e3a-abdce75f3c47/resourceGroups/SaftTechnologies/providers/Microsoft.CognitiveServices/accounts/stCustomVision-Prediction"; trainingApi.PublishIteration(project.Id, iteration.Id, publishedModelName, predictionResourceId); Console.WriteLine("Done!\n"); // </snippet_train> // Now there is a trained endpoint, it can be used to make a prediction // <snippet_prediction_endpoint> // Create a prediction endpoint, passing in obtained prediction key CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = ENDPOINT }; // </snippet_prediction_endpoint> // <snippet_prediction> // Make a prediction against the new project Console.WriteLine("Making a prediction:"); var result = endpoint.ClassifyImage(project.Id, publishedModelName, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); } Console.ReadKey(); // </snippet_prediction> }
static void Main(string[] args) { var trainingClient = new CustomVisionTrainingClient() { ApiKey = TrainingKey, Endpoint = Endpoint }; Console.WriteLine("Creating new project:"); var project = trainingClient.CreateProject("Face-Detect"); Console.WriteLine("Uploading Prayut images."); var prayutTag = trainingClient.CreateTag(project.Id, "Prayut"); var prayutImages = Directory.GetFiles(Path.Combine("Images", "Prayut")); var prayutFiles = prayutImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingClient.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(prayutFiles, new List <Guid>() { prayutTag.Id })); Console.WriteLine("-> Done."); Console.WriteLine("Uploading Thaksin images."); var thaksinTag = trainingClient.CreateTag(project.Id, "Thaksin"); var thaksinImages = Directory.GetFiles(Path.Combine("Images", "thaksin")); var thaksinFiles = thaksinImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingClient.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(thaksinFiles, new List <Guid>() { thaksinTag.Id })); Console.WriteLine("-> Done."); Console.WriteLine("Training."); var iteration = trainingClient.TrainProject(project.Id); while (iteration.Status == "Training") { Thread.Sleep(1000); iteration = trainingClient.GetIteration(project.Id, iteration.Id); } Console.WriteLine("-> Done."); Console.WriteLine("Publishing."); var publishedName = "GuessWho"; trainingClient.PublishIteration(project.Id, iteration.Id, publishedName, PredictionResourceId); Console.WriteLine("-> Done."); Console.WriteLine("Making a prediction."); var predictionClient = new CustomVisionPredictionClient() { ApiKey = PredictionKey, Endpoint = Endpoint }; var testImage = new MemoryStream(File.ReadAllBytes(Path.Combine("Images", @"Test\Test.jpg"))); var result = predictionClient.ClassifyImage(project.Id, publishedName, testImage); foreach (var prediction in result.Predictions) { Console.WriteLine($"-> {prediction.TagName}: {prediction.Probability:P1}"); } Console.WriteLine("-> Done."); Console.WriteLine("Deleting your project."); trainingClient.UnpublishIteration(project.Id, iteration.Id); trainingClient.DeleteIteration(project.Id, iteration.Id); trainingClient.DeleteProject(project.Id); Console.WriteLine("-> Done."); }
private async void TakePicture() { AppState = States.Processing; CountDown.Text = "Calculation..."; CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = CustomVisionEndpoint }; StringBuilder sb = new StringBuilder(); using (var captureStream = new InMemoryRandomAccessStream()) { await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream); captureStream.Seek(0); StorageFile destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync($@"{Guid.NewGuid()}.jpg"); try { using (var destinationStream = (await destinationFile.OpenAsync(FileAccessMode.ReadWrite)).GetOutputStreamAt(0)) { await RandomAccessStream.CopyAndCloseAsync(captureStream, destinationStream); } } finally { await destinationFile.DeleteAsync(); } var stream = captureStream.AsStream(); stream.Seek(0, SeekOrigin.Begin); // Make a prediction against the new project sb.Append("Prediction:\n"); var predictions = new List <Prediction>(); try { Stopwatch sp = new Stopwatch(); sp.Start(); var result = endpoint.ClassifyImage(new System.Guid(projectId), iterationName, stream); foreach (var c in result.Predictions) { predictions.Add(new Prediction(c)); sb.AppendFormat($"{c.TagName}: {c.Probability:P1}\n"); } sb.AppendFormat($"Prediction took {sp.ElapsedMilliseconds}ms\n"); sp.Stop(); } catch (Exception ex) { sb.Append(ex.Message); } Output.Text = sb.ToString(); if (predictions.Count > 0) { var highestPrediction = (from p in predictions orderby p.Probability descending select p).First(); try { ImageColor.Fill = highestPrediction.GetColorCode(); } catch (Exception) { } try { ImagePreview.Source = highestPrediction.GetPicture(); } catch (Exception) { } } else { Output.Text = "No prediction possible"; } CountDown.Text = countDown.ToString(); } AppState = States.Waiting; }
static void Main(string[] args) { // Add your Azure Custom Vision subscription key and endpoint to your environment variables. // <snippet_endpoint> string ENDPOINT = "https://southeastasia.api.cognitive.microsoft.com/"; // </snippet_endpoint> // <snippet_keys> // Add your training & prediction key from the settings page of the portal string trainingKey = "c48ec2b81a534659a5929f8688a3b169"; string predictionKey = "c48ec2b81a534659a5929f8688a3b169"; // </snippet_keys> // <snippet_create> // Create the Api, passing in the training key CustomVisionTrainingClient trainingApi = new CustomVisionTrainingClient() { ApiKey = trainingKey, Endpoint = ENDPOINT }; // Create a new project Console.WriteLine("Creating new project:"); var project = trainingApi.CreateProject("My New Project"); // </snippet_create> // <snippet_tags> // Make two tags in the new project var hemlockTag = trainingApi.CreateTag(project.Id, "Hemlock"); var japaneseCherryTag = trainingApi.CreateTag(project.Id, "Japanese Cherry"); var butterflyTag = trainingApi.CreateTag(project.Id, "butterfly"); var catTag = trainingApi.CreateTag(project.Id, "cat"); // </snippet_tags> // <snippet_upload> // Add some images to the tags Console.WriteLine("\tUploading images"); LoadImagesFromDisk(); // Images can be uploaded one at a time foreach (var image in hemlockImages) { using (var stream = new MemoryStream(File.ReadAllBytes(image))) { trainingApi.CreateImagesFromData(project.Id, stream, new List <Guid>() { hemlockTag.Id }); } } // </snippet_upload> // Or uploaded in a single batch var imageFiles = japaneseCherryImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>() { japaneseCherryTag.Id })); var imageFiles1 = butterflyImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles1, new List <Guid>() { butterflyTag.Id })); var imageFiles2 = catImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles2, new List <Guid>() { catTag.Id })); // <snippet_train> // Now there are images with tags start training the project Console.WriteLine("\tTraining"); var iteration = trainingApi.TrainProject(project.Id); // The returned iteration will be in progress, and can be queried periodically to see when it has completed while (iteration.Status == "Training") { Thread.Sleep(1000); // Re-query the iteration to get it's updated status iteration = trainingApi.GetIteration(project.Id, iteration.Id); } // The iteration is now trained. Publish it to the prediction end point. var publishedModelName = "treeClassModel"; var predictionResourceId = "/subscriptions/453950b1-2d8e-4526-a905-6e7cfd88bae3/resourceGroups/EGCO313Lab/providers/Microsoft.CognitiveServices/accounts/egco313"; trainingApi.PublishIteration(project.Id, iteration.Id, publishedModelName, predictionResourceId); Console.WriteLine("Done!\n"); // </snippet_train> // Now there is a trained endpoint, it can be used to make a prediction // <snippet_prediction_endpoint> // Create a prediction endpoint, passing in obtained prediction key CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient() { ApiKey = predictionKey, Endpoint = ENDPOINT }; // </snippet_prediction_endpoint> // <snippet_prediction> // Make a prediction against the new project Console.WriteLine("Making a prediction:"); var result = endpoint.ClassifyImage(project.Id, publishedModelName, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}"); } Console.ReadKey(); // </snippet_prediction> }