Пример #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
        /// <summary>
        /// Initialize Model from preloaded Data
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public void InitializeModel()
        {
            if (string.IsNullOrWhiteSpace(_trainingKey))
            {
                throw new Exception("Call SetTrainingKey before training the Model");
            }

            var trainingCredentials = new TrainingApiCredentials(_trainingKey);

            TrainingApi = new TrainingApi(trainingCredentials);

            // Check if project already exists
            var projects  = TrainingApi.GetProjects();
            var duplicate = projects.FirstOrDefault(p => p.Name == _projectName);

            if (duplicate != null)
            {
                TrainingApi.DeleteProject(duplicate.Id);
            }

            // Create a new CV Project
            var project = TrainingApi.CreateProject(_projectName);

            // Save Project Guid
            ProjectGuid = project.Id;

            // Retrieve Model Initialization Data from Folder "Training"
            var trainings = RetrieveTrainings();

            TrainModel(ref project, trainings);
        }
        public void CreateNewProject()
        {
            var credentials = new TrainingApiCredentials(Key);
            var trainingApi = new TrainingApi(credentials);

            // Create the Api, passing in a credentials object that contains the training key
            var project = CreateProject(trainingApi);

            TrainProject(trainingApi, project);
        }
Пример #4
0
        public static bool IsValidCard(string url)
        {
            try
            {
                string trainingKey = Constants.CustomVisionTrainingAPIKey;

                // Create the Api, passing in a credentials object that contains the training key
                TrainingApiCredentials trainingCredentials = new TrainingApiCredentials(trainingKey);
                TrainingApi            trainingApi         = new TrainingApi(trainingCredentials);

                var          projects = trainingApi.GetProjects();
                ProjectModel project  = projects.FirstOrDefault(e => e.Name == "IDVision");

                // Get the prediction key, which is used in place of the training key when making predictions
                var account       = trainingApi.GetAccountInfo();
                var predictionKey = account.Keys.PredictionKeys.PrimaryKey;

                // Create a prediction endpoint, passing in a prediction credentials object that contains the obtained prediction key
                PredictionEndpointCredentials predictionEndpointCredentials = new PredictionEndpointCredentials(predictionKey);
                PredictionEndpoint            endpoint = new PredictionEndpoint(predictionEndpointCredentials);

                byte[] byteData = Utilities.Utilities.GetImagesAsByteArrayFromUri(url);

                MemoryStream stream = new MemoryStream(byteData);
                // Make a prediction against the new project
                var predictionResult = endpoint.PredictImage(project.Id, stream);

                // Loop over each prediction and write out the results
                foreach (var c in predictionResult.Predictions)
                {
                    if ((c.Probability * 100) > 80)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(false);
        }
Пример #5
0
        static int Main(string[] args)
        {
            Console.WriteLine("Custom Vision Image Trainer V1.0");
            if (args.Length < 4 || args.Contains("-?"))
            {
                Console.WriteLine("Usage: customvisiontrainer.exe {custom vision account key} {custom vision project} {source image uri} {image tag(s)}");
                return(1);
            }
            // Create the Api, passing in a credentials object that contains the training key
            TrainingApiCredentials trainingCredentials = new TrainingApiCredentials(args[0]);
            TrainingApi            trainingApi         = new TrainingApi(trainingCredentials);

            // Get a reference to the project and create a tag
            var project = trainingApi.GetProjects().First(proj => String.Equals(proj.Name, args[1], StringComparison.OrdinalIgnoreCase));

            // Create the specified tag(s), if it doesn't already exist
            var tags = args[3].Split(';')
                       .Select(tag =>
            {
                var tagObject = trainingApi.GetTags(project.Id).Tags.FirstOrDefault(projTag => String.Equals(projTag.Name, tag, StringComparison.OrdinalIgnoreCase));
                if (tagObject == null)
                {
                    tagObject = trainingApi.CreateTag(project.Id, tag);
                }
                return(tagObject);
            })
                       .ToList();

            // Enumerate the list of images from the specified root uri
            var storageUri = new UriBuilder(args[2]);
            var path       = storageUri.Path;

            storageUri.Path = "";
            var blobClient   = new CloudBlobClient(storageUri.Uri);
            var pathSegments = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var container    = blobClient.GetContainerReference(pathSegments[0]);
            var blobUris     = container.ListBlobs(String.Join("/", pathSegments.Skip(1)))
                               .Select(blobItem => blobItem.Uri)
                               .ToList();

            // Upload the images directly to the custom vision project
            var images = new ImageUrlCreateBatch(tags.Select(tag => tag.Id).ToList(),
                                                 blobUris.Select(blobUri => blobUri.ToString()).ToList());

            trainingApi.CreateImagesFromUrlsAsync(project.Id, images, new CancellationTokenSource(60000).Token).Wait();
            return(0);
        }
Пример #6
0
        static void Main()
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            TrainingApiCredentials trainingCredentials = new TrainingApiCredentials("API_KEY_HERE");
            TrainingApi            trainingApi         = new TrainingApi(trainingCredentials);
            var project = trainingApi.GetProjects()[1];

            foreach (string f in food)
            {
                FoodClassifier          g = new FoodClassifier(f, trainingApi, project);
                System.Threading.Thread t = new System.Threading.Thread(g.Classify);
                t.Start();
                System.Threading.Thread.Sleep(10000);
            }

            Console.Write("\nPress Enter to exit ");
            Console.ReadLine();
        }
Пример #7
0
        private static void Train()
        {
            string trainingKey = "fdf8998652a44b5ea1380439f25d71ca";
            string projectKey  = "INat-ImageClassifier";
            string trainPath   = @"c:\data\Images\train\";

            TrainingApiCredentials trainingCredentials = new TrainingApiCredentials(trainingKey);
            TrainingApi            trainingApi         = new TrainingApi(trainingCredentials);

            var project = trainingApi.CreateProject(projectKey);
            var files   = new DirectoryInfo(trainPath).GetFiles("*", SearchOption.AllDirectories);

            foreach (var image in files)
            {
                if (tagCount >= 50)
                {
                    break;
                }
                List <string> tags = new List <string>();

                string tagName = image.Directory.Name.Replace("_", " ");
                var    tagdata = trainingApi.GetTags(project.Id);
                CreateTags(trainingApi, project, tags, tagName, tagdata);
                var imagestream = new MemoryStream(File.ReadAllBytes(image.FullName));

                Console.WriteLine("Sending image " + image.Name + " To Custom Vision AI for training...");
                trainingApi.CreateImagesFromData(project.Id, imagestream, tags);
            }

            var iteration = trainingApi.TrainProject(project.Id);

            while (iteration.Status == "Training")
            {
                Thread.Sleep(100);
                iteration = trainingApi.GetIteration(project.Id, iteration.Id);
                Console.WriteLine("Training...");
            }

            iteration.IsDefault = true;
            trainingApi.UpdateIteration(project.Id, iteration.Id, iteration);
        }
 private void ConfirmButton_Click(object sender, RoutedEventArgs e)
 {
     if (String.IsNullOrEmpty(TrainingKeyTextBox.Text))
     {
         tipTextBlock.Text = "请输入Training Key";
         return;
     }
     else
     {
         try
         {
             TrainingApiCredentials trainingCredentials = new TrainingApiCredentials(TrainingKeyTextBox.Text.Trim());
             TrainingApi            trainingApi         = new TrainingApi(trainingCredentials);
             MainWindow.currentWindow.SetTrainingAPi(trainingApi);
             MainWindow.currentWindow.GetProjects();
             MainWindow.currentWindow.StartMainPage();
         }
         catch
         {
             tipTextBlock.Text = "Training Key验证失败";
             return;
         }
     }
 }
Пример #9
0
        static void Main(string[] args)
        {
            // You can either add your training key here, pass it on the command line, or type it in when the program runs
            string trainingKey = GetTrainingKey(trainingKeyString, args);

            // Create the Api, passing in a credentials object that contains the training key
            TrainingApiCredentials trainingCredentials = new TrainingApiCredentials(trainingKey);
            TrainingApi            trainingApi         = new TrainingApi(trainingCredentials);

            // Create a new project
            Console.WriteLine("Creating new project:");
            var project = trainingApi.CreateProject(projectName);

            // Create some tags, you need at least two
            var tag1 = trainingApi.CreateTag(project.Id, "tag1");
            var tag2 = trainingApi.CreateTag(project.Id, "tag2");

            // Add some images to the tags
            Console.Write("\n\tProcessing images");

            // Upload using the path to the images, a reference to the training API, a ference to your project and a tag
            UploadImages(@"..\..\..\Images\1", trainingApi, project, new List <string>()
            {
                tag1.Id.ToString()
            });
            UploadImages(@"..\..\..\Images\1", trainingApi, project, new List <string>()
            {
                tag2.Id.ToString()
            });

            // Or uploaded in a single batch
            //trainingApi.CreateImagesFromData(project.Id, japaneseCherryImages, new List<Guid>() { japaneseCherryTag.Id });

            // Now there are images with tags start training the project
            Console.WriteLine("\tStarting training");

            IterationModel iteration = null;

            try
            {
                iteration = trainingApi.TrainProject(project.Id);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Trainig could not be completed. Error: {e.Message}");
            }

            if (iteration != null)
            {
                // 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);
                }

                Console.WriteLine($"\tFinished training iteration {iteration.Id}");

                // The iteration is now trained. Make it the default project endpoint
                iteration.IsDefault = true;
                trainingApi.UpdateIteration(project.Id, iteration.Id, iteration);
                Console.WriteLine("Done!\n");

                // Now there is a trained endpoint, it can be used to make a prediction

                // Get the prediction key, which is used in place of the training key when making predictions
                //var account = trainingApi.GetAccountInfo();
                //var predictionKey = account.Keys.PredictionKeys.PrimaryKey;

                //// Create a prediction endpoint, passing in a prediction credentials object that contains the obtained prediction key
                //PredictionEndpointCredentials predictionEndpointCredentials = new PredictionEndpointCredentials(predictionKey);
                //PredictionEndpoint endpoint = new PredictionEndpoint(predictionEndpointCredentials);

                //// Make a prediction against the new project
                //Console.WriteLine("Making a prediction:");
                //var result = endpoint.PredictImage(project.Id, testImage);

                //// Loop over each prediction and write out the results
                //foreach (var c in result.Predictions)
                //{
                //    Console.WriteLine($"\t{c.Tag}: {c.Probability:P1}");
                //}
            }

            Console.ReadKey();
        }