Пример #1
0
        public async Task <IList <PredictionViewModel> > Predict(byte[] image)
        {
            var trainingCredentials = new TrainingApiCredentials(APIKeys.TrainingAPIKey);
            var trainingApi         = new TrainingApi(trainingCredentials);

            var predictionEndpointCredentials = new PredictionEndpointCredentials(APIKeys.PredictionAPIKey);
            var predictionEndpoint            = new PredictionEndpoint(predictionEndpointCredentials);

            var projects = await trainingApi.GetProjectsAsync();

            var stream  = new System.IO.MemoryStream(image);
            var results = await predictionEndpoint.PredictImageAsync(projects[0].Id, stream);

            var predictions = new List <PredictionViewModel>();

            foreach (var result in results.Predictions)
            {
                predictions.Add(new PredictionViewModel()
                {
                    Tag = result.Tag, Prediction = result.Probability
                });
            }

            return(predictions);
        }
Пример #2
0
        private static async Task ListProjects(TrainingApi trainingApi)
        {
            var projects = await trainingApi.GetProjectsAsync();

            if (projects.Any())
            {
                Console.WriteLine($"Existing projects: {Environment.NewLine}{string.Join(Environment.NewLine, projects.Select(p => p.Name))}{Environment.NewLine}");
            }
        }
Пример #3
0
        private static async Task <Project> GetOrCreateProject(TrainingApi trainingApi, string name)
        {
            var projects = await trainingApi.GetProjectsAsync();

            var project = projects.Where(p => p.Name.ToUpper() == name.ToUpper()).SingleOrDefault();

            if (project == null)
            {
                project = await trainingApi.CreateProjectAsync(name);
            }

            return(project);
        }
        private async Task ListProjects(TrainingApi trainingApi)
        {
            ObservableCollection <string> completeProjectList = new ObservableCollection <string>();
            var projects = await trainingApi.GetProjectsAsync();

            foreach (var project in projects)
            {
                completeProjectList.Add(project.Name);
            }

            _projectList = completeProjectList;
            RaisePropertyChanged("ProjectList");

            if (_projectList.Count > 0)
            {
                _isTagPickerVisible = false;
                RaisePropertyChanged("IsTagPickerVisible");
            }
        }
Пример #5
0
        public async Task <PredictImageResult> PredictImage(Stream testImage)
        {
            string trainingKey   = "6308b3b62b344e3f8e4170c4728deed2";
            string predictionKey = "afdffbaa498445c1830aa18ee9216e0b";

            // Create a prediction endpoint, passing in obtained prediction key
            PredictionEndpoint endpoint = new PredictionEndpoint()
            {
                ApiKey = predictionKey
            };

            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };
            var projects = await trainingApi.GetProjectsAsync();

            var project = projects.First(f => f.Name == "WA-SE-AI");

            try
            {
                var result = await endpoint.PredictImageAsync(project.Id, testImage);

                var tags = await trainingApi.GetTagsAsync(project.Id);

                // Loop over each prediction and write out the results
                foreach (var c in result.Predictions)
                {
                    Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}");
                }
                var topPrediction = result.Predictions.OrderByDescending(m => m.Probability).First();
                PredictImageResult predictImageResult = new PredictImageResult
                {
                    PredictionModel = topPrediction,
                    Tag             = tags.FirstOrDefault(f => f.Id == topPrediction.TagId)
                };
                return(predictImageResult);
            }
            catch (Exception e)
            {
                throw new Exception("PredictImage failed");
            }
        }
        private async Task LoadProjectsFromService()
        {
            this.progressControl.IsActive = true;

            try
            {
                this.Projects.Clear();
                IEnumerable <Project> projects = await trainingApi.GetProjectsAsync();

                this.Projects.AddRange(projects.OrderBy(p => p.Name));

                if (this.projectsListView.Items.Any())
                {
                    this.projectsListView.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure loading projects");
            }

            this.progressControl.IsActive = false;
        }
        private static async Task <bool> MainAsync(string[] args)
        {
            try
            {
                trainingApi.ApiKey = CustomVisionTrainingApiKey;

                // Create project
                var projects = await trainingApi.GetProjectsAsync();

                var project = projects.Where(x => x.Name == projectName).FirstOrDefault();

                if (project == null)
                {
                    Console.WriteLine($"\nCreating project '{projectName}'");
                    project = await trainingApi.CreateProjectAsync(projectName);
                }

                // Retrieve all tags
                var tagsList = await trainingApi.GetTagsAsync(project.Id);

                #region Create Object tag
                var objectTag = tagsList.Tags.Where(x => x.Name == objectTagName).FirstOrDefault();

                if (objectTag == null)
                {
                    Console.WriteLine($"\nCreating tag '{objectTagName}'");
                    objectTag = await trainingApi.CreateTagAsync(project.Id, objectTagName);
                }

                // add images to tag
                Console.WriteLine($"\nAdding images to tag '{objectTagName}'");
                List <ImageFileCreateEntry> imageFiles = (Directory.GetFiles(objectTrainImagesPath)).Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList();
                await trainingApi.CreateImagesFromFilesAsync(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>()
                {
                    objectTag.Id
                }));

                #endregion

                #region Create Ocean tag
                var oceanTag = tagsList.Tags.Where(x => x.Name == oceanTagName).FirstOrDefault();

                if (oceanTag == null)
                {
                    Console.WriteLine($"\nCreating tag '{oceanTagName}'");
                    oceanTag = await trainingApi.CreateTagAsync(project.Id, oceanTagName);
                }

                // add images
                Console.WriteLine($"\nAdding images to tag '{oceanTagName}'");
                imageFiles = (Directory.GetFiles(noObjectTrainImagesPath)).Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList();
                await trainingApi.CreateImagesFromFilesAsync(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>()
                {
                    oceanTag.Id
                }));

                #endregion

                #region Train the classifier
                Console.WriteLine("\nTraining");
                var iteration = await trainingApi.TrainProjectAsync(project.Id);

                do
                {
                    Thread.Sleep(1000);
                    iteration = await trainingApi.GetIterationAsync(project.Id, iteration.Id);
                }while (string.Equals("training", iteration.Status, StringComparison.OrdinalIgnoreCase));

                if (!string.Equals(iteration.Status, "completed", StringComparison.OrdinalIgnoreCase))
                {
                    throw new Exception($"An error occurred training the classifier. Iteration status is {iteration.Status}");
                }

                iteration.IsDefault = true;
                await trainingApi.UpdateIterationAsync(project.Id, iteration.Id, iteration);

                #endregion

                Console.WriteLine(
                    $@"\n
Your custom vision project ID is {project.Id.ToString()}.

Copy this Guid and add it to your application settings under the name 'CustomVisionProjectId'
"
                    );

                Console.WriteLine("\nFinished. Press Enter to exit");
                Console.Read();

                return(true);
            }
            catch (Exception e)
            {
                Console.Write(e);
                Console.WriteLine("\nPress Enter to exit");
                Console.Read();

                return(false);
            }
        }