private static Project CreateProject(string projectName)
        {
            try
            {
                var trainingKey = ConfigurationManager.AppSettings["CustomVision_TrainingKey"];
                var trainingApi = new TrainingApi()
                {
                    ApiKey = trainingKey
                };

                // Create a new project

                IList <Project> projects = trainingApi.GetProjects();
                foreach (Project p in projects)
                {
                    if (p.Name == projectName)
                    {
                        Console.WriteLine("\tFound project: " + projectName);
                        return(p);
                    }
                }
                // A project isn't found with this name create it.
                Console.WriteLine("\tCreating new project:");
                return(trainingApi.CreateProject(projectName));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        /// <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);
        }
Exemple #3
0
        private static Guid GetProjectId()
        {
            var trainingApi = new TrainingApi();

            trainingApi.ApiKey = Properties.Settings.Default.Classifier_TrainingApiKey;

            var projectName = Properties.Settings.Default.Classifier_ProjectName;
            var project     = trainingApi.GetProjects().Single(p => p.Name == projectName);

            return(project.Id);
        }
Exemple #4
0
        private static Guid GetProjectId()
        {
            var trainingApi = new TrainingApi
            {
                ApiKey = ConfigurationManager.AppSettings["trainingKey"]
            };

            var projectName = ConfigurationManager.AppSettings["projectName"];
            var project     = trainingApi.GetProjects().Single(p => p.Name == projectName);

            return(project.Id);
        }
Exemple #5
0
        public static void Main(string[] args)
        {
            var trainingApi = new TrainingApi
            {
                ApiKey = ConfigurationManager.AppSettings["trainingKey"]
            };

            var projectName = ConfigurationManager.AppSettings["projectName"];
            var project     = trainingApi.GetProjects().Single(p => p.Name == projectName);

            UploadTrainingData(project.Id, trainingApi);
            TrainClassifier(project.Id, trainingApi);

            Console.ReadKey();
        }
        public async Task Procesar(Stream img)
        {
            Indicador.IsRunning = true;
            var sproject = trainingApi.GetProjects().ToArray();
            var project  = sproject[0];
            var result   = endpoint.PredictImage(project.Id, img);
            var c        = result.Predictions.ToArray();
            await Task.Delay(10000);

            for (int i = 0; i < c.Length; i++)
            {
                Informacion = Informacion + "Con: " + c[i].Tag + "," + String.Format(" Total: {0:P2}.", c[i].Probability) + "\n";
            }
            Indicador.IsRunning = false;
            Mensaje.Text        = "Listo";
        }
Exemple #7
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);
        }
Exemple #8
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);
        }
        static void Main(string[] args)
        {
            var keys = GetApiKeys();

            var trainingApi = new TrainingApi {
                ApiKey = keys.TrainingKey
            };
            var predictionEndpoint = new PredictionEndpoint {
                ApiKey = keys.PredictionKey
            };

            var projects    = trainingApi.GetProjects();
            var herbProject = projects.Where(p => p.Name == "Herbs").FirstOrDefault();

            Console.WriteLine("Input path to image to test:");
            var imagePath = Console.ReadLine();

            if (!File.Exists(imagePath))
            {
                Console.WriteLine("File does not exist. Press enter to exit.");
                Console.ReadLine();
                return;
            }

            Console.WriteLine("Image predictions:");

            var imageFile = File.OpenRead(imagePath);

            if (herbProject != null)
            {
                var result = predictionEndpoint.PredictImage(herbProject.Id, imageFile);

                foreach (var prediction in result.Predictions)
                {
                    Console.WriteLine($"Tag: {prediction.Tag} Probability: {String.Format("Value: {0:P2}.", prediction.Probability)}");
                }
            }
            else
            {
                Console.WriteLine("Project doesn't exist.");
            }

            Console.ReadLine();
        }
Exemple #10
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();
        }
        static void Main(string[] args)
        {
            Keys keys = null;

            using (var reader = new StreamReader("App.json"))
            {
                var json = reader.ReadToEnd();

                keys = JsonConvert.DeserializeObject <Keys>(json);
            }

            var trainingApi = new TrainingApi {
                ApiKey = keys.TrainingKey
            };
            var predictionEndpoint = new PredictionEndpoint {
                ApiKey = keys.PredictionKey
            };

            var projects    = trainingApi.GetProjects();
            var herbProject = projects.Where(p => p.Name == "Herbs").FirstOrDefault();

            Console.WriteLine("Predicting basil image");
            var imageFile = File.OpenRead("basil_test.jpg");

            if (herbProject != null)
            {
                var result = predictionEndpoint.PredictImage(herbProject.Id, imageFile);

                foreach (var prediction in result.Predictions)
                {
                    Console.WriteLine($"Tag: {prediction.Tag} Probability: {prediction.Probability}");
                }
            }
            else
            {
                Console.WriteLine("Project doesn't exist.");
            }

            Console.ReadLine();
        }
Exemple #12
0
        static void Main(string[] args)
        {
            var keys = GetApiKeys();

            var trainingApi = new TrainingApi {
                ApiKey = keys.TrainingKey
            };
            var predictionEndpoint = new PredictionEndpoint {
                ApiKey = keys.PredictionKey
            };

            var projects    = trainingApi.GetProjects();
            var herbProject = projects.FirstOrDefault(p => p.Name == "Herbs");

            Console.WriteLine("Press 1 to predict and 2 to train:");
            var pathChoice = Console.ReadLine();

            if ("1".Equals(pathChoice))
            {
                Console.WriteLine("Press 1 to predict on a URL or 2 to predict on a local file:");
                var predictType = Console.ReadLine();

                if ("1".Equals(predictType))
                {
                    Console.WriteLine("Input the URL to an image to test:");
                    var imageUrl = Console.ReadLine();

                    if (herbProject != null)
                    {
                        var result = predictionEndpoint.PredictImageUrl(herbProject.Id, new Microsoft.Cognitive.CustomVision.Prediction.Models.ImageUrl(imageUrl));

                        PrintResults(result);
                    }
                }
                else
                {
                    Console.WriteLine("Input path to image to test:");
                    var imagePath = Console.ReadLine();

                    if (!File.Exists(imagePath))
                    {
                        Console.WriteLine("File does not exist. Press enter to exit.");
                        Console.ReadLine();
                        return;
                    }

                    Console.WriteLine("Image predictions:");

                    var imageFile = File.OpenRead(imagePath);

                    if (herbProject != null)
                    {
                        var result = predictionEndpoint.PredictImage(herbProject.Id, imageFile);

                        PrintResults(result);
                    }
                    else
                    {
                        Console.WriteLine("Project doesn't exist.");
                    }
                }

                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Input path to image to train model with:");
                var imagePath = Console.ReadLine();

                Console.WriteLine("What tag would you give this image? Rosemary, cilantro, or basil?");
                var imageTag = Console.ReadLine();

                var capitilizedTag = char.ToUpper(imageTag.First()) + imageTag.Substring(1).ToLower();

                if (!File.Exists(imagePath))
                {
                    Console.WriteLine("File does not exist. Press enter to exit.");
                    Console.ReadLine();
                    return;
                }

                var imageFile = File.OpenRead(imagePath);

                var tags = trainingApi.GetTags(herbProject.Id);

                var matchedTag = tags.Tags.FirstOrDefault(t => t.Name == capitilizedTag);

                var memoryStream = new MemoryStream();
                imageFile.CopyTo(memoryStream);

                var fileCreateEntry = new ImageFileCreateEntry(imageFile.Name, memoryStream.ToArray());
                var fileCreateBatch = new ImageFileCreateBatch {
                    Images = new List <ImageFileCreateEntry> {
                        fileCreateEntry
                    }, TagIds = new List <Guid> {
                        matchedTag.Id
                    }
                };

                var result = trainingApi.CreateImagesFromFiles(herbProject.Id, fileCreateBatch);

                var resultImage = result.Images.FirstOrDefault();

                switch (resultImage.Status)
                {
                case "OKDuplicate":
                    Console.WriteLine("Image is already used for training. Please use another to train with");
                    Console.ReadLine();
                    break;

                default:
                    break;
                }

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

                while (iteration.Status != "Completed")
                {
                    System.Threading.Thread.Sleep(1000);

                    iteration = trainingApi.GetIteration(herbProject.Id, iteration.Id);
                }

                iteration.IsDefault = true;
                trainingApi.UpdateIteration(herbProject.Id, iteration.Id, iteration);
                Console.WriteLine("Done training!");

                Console.ReadLine();
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            // Create the Api, passing in the training key
            string trainingKey = "";

            if (String.IsNullOrEmpty(trainingKey))
            {
                Console.WriteLine("The custom vision training key needs to be set.");
                Environment.Exit(1);
            }

            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };

            // Find the object detection project
            var domains            = trainingApi.GetDomains();
            var objDetectionDomain = domains.FirstOrDefault(d => d.Type == "ObjectDetection");
            var project            = trainingApi.GetProjects().FirstOrDefault(p => p.Settings.DomainId == objDetectionDomain.Id);

            string modelPath  = Path.Combine(Environment.CurrentDirectory, "..", "model");
            string dataPath   = Path.Combine(modelPath, "dataset.json");
            string imagesPath = Path.Combine(modelPath, "images");

            var images = JsonConvert.DeserializeObject <IEnumerable <Image> >(File.ReadAllText(dataPath));

            // Create tags, unless they already exist
            var existingTags = trainingApi.GetTags(project.Id);
            var tagsToImport = images
                               .SelectMany(i => i.Tags
                                           .Select(t => t.TagName))
                               .Distinct()
                               .Where(t => !existingTags.Any(e => string.Compare(e.Name, t, ignoreCase: true)));

            if (tagsToImport.Any())
            {
                foreach (var tag in tagsToImport)
                {
                    Console.WriteLine($"Importing {tag}");
                    var newTag = trainingApi.CreateTag(project.Id, tag);
                    existingTags.Add(newTag);
                }
            }

            // Upload images with region data, in batches of 50
            while (images.Any())
            {
                var currentBatch = images.Take(BATCH_SIZE);

                var imageFileEntries = new List <ImageFileCreateEntry>();
                foreach (var imageRef in currentBatch)
                {
                    var regions = new List <Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models.Region>();
                    foreach (var region in imageRef.Regions)
                    {
                        regions.Add(new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models.Region()
                        {
                            Height = region.Height,
                            Width  = region.Width,
                            Top    = region.Top,
                            Left   = region.Left,
                            TagId  = existingTags.First(t => t.Name == region.TagName).Id
                        });
                    }

                    string imagePath = Path.Combine(imagesPath, string.Concat(imageRef.Id, ".png"));
                    imageFileEntries.Add(new ImageFileCreateEntry()
                    {
                        Name     = imagePath,
                        Contents = File.ReadAllBytes(imagePath),
                        Regions  = regions
                    });
                }

                trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFileEntries));

                images = images.Skip(BATCH_SIZE);
            }

            Console.WriteLine("Training data upload complete!");
        }
Exemple #14
0
 /// <summary>
 /// 获取Project列表
 /// </summary>
 /// <returns></returns>
 public List <ProjectModel> GetProjects()
 {
     projectlist = trainingApi.GetProjects().ToList();
     return(projectlist);
 }
Exemple #15
0
        public Boolean Train(string tagName, string description = null)
        {
            // Add your training & prediction key from the settings page of the portal
            string trainingKey = "6308b3b62b344e3f8e4170c4728deed2";

            // Create the Api, passing in the training key
            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };
            var project = trainingApi.GetProjects().First(f => f.Name == "WA-SE-AI");

            // Make two tags in the new project
            Tag trainTag;

            try
            {
                trainTag = trainingApi.GetTags(project.Id).First(f => f.Name == tagName);
            }
            catch (Exception)
            {
                trainTag = trainingApi.CreateTag(project.Id, tagName, description);
            }

            // Add some images to the tags
            Console.WriteLine("Start load image into memory");
            List <string> TrainImages = LoadImagesFromDisk(tagName);

            if (TrainImages != null)
            {
                Console.WriteLine("Uploading " + TrainImages.Count + "images");
                var trainImageFiles = TrainImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList();
                trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(trainImageFiles, new List <Guid>()
                {
                    trainTag.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. Make it the default project endpoint
                iteration.IsDefault = true;
                trainingApi.UpdateIteration(project.Id, iteration.Id, iteration);
                Console.WriteLine("Training Done!\n");
                return(true);
            }
            else
            {
                Console.WriteLine("No image found!\n");
                return(true);
            }
        }
Exemple #16
0
        public async Task Main()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = CustomVisionAPIKey
            };

            trainingApi.HttpClient.Timeout = TimeSpan.FromMinutes(TimeoutMins);

            if (!QuickTest)
            {
                Console.WriteLine($"Creating Custom Vision Project: {ProjectName}");
                var project = trainingApi.CreateProject(ProjectName);

                Console.WriteLine($"Scanning subfolders within: {ImagePath}");
                List <Tag> allTags = new List <Tag>();
                foreach (var folder in Directory.EnumerateDirectories(ImagePath))
                {
                    string folderName = Path.GetFileName(folder);
                    var    tagNames   = folderName.Contains(",") ? folderName.Split(',').Select(t => t.Trim()).ToArray() : new string[] { folderName };

                    // Create tag for each comma separated value in subfolder name
                    foreach (var tag in tagNames)
                    {
                        // Check we've not already created this tag from another subfolder
                        if (!allTags.Any(t => t.Name.Equals(tag)))
                        {
                            Console.WriteLine($"Creating Tag: {tag}");
                            var imageTag = trainingApi.CreateTag(project.Id, tag);
                            allTags.Add(imageTag);
                        }
                    }
                }

                foreach (var currentFolder in Directory.EnumerateDirectories(ImagePath))
                {
                    string folderName = Path.GetFileName(currentFolder);
                    var    tagNames   = folderName.Contains(",") ? folderName.Split(',').Select(t => t.Trim()).ToArray() : new string[] { folderName };

                    try
                    {
                        // Load the images to be uploaded from disk into memory
                        Console.WriteLine($"Uploading: {ImagePath}\\{folderName} images...");

                        var images     = Directory.GetFiles(currentFolder).ToList();
                        var folderTags = allTags.Where(t => tagNames.Contains(t.Name)).Select(t => t.Id).ToList();
                        var imageFiles = images.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img), folderTags)).ToList();
                        var imageBatch = new ImageFileCreateBatch(imageFiles);
                        var summary    = await trainingApi.CreateImagesFromFilesAsync(project.Id, new ImageFileCreateBatch(imageFiles));

                        // List any images that didn't make it
                        foreach (var imageResult in summary.Images.Where(i => !i.Status.Equals("OK")))
                        {
                            Console.WriteLine($"{ImagePath}\\{folderName}\\{imageResult.SourceUrl}: {imageResult.Status}");
                        }

                        Console.WriteLine($"Uploaded {summary.Images.Where(i => i.Status.Equals("OK")).Count()}/{images.Count()} images successfully from {ImagePath}\\{folderName}");
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine($"Error processing {currentFolder}: {exp.Source}:{exp.Message}");
                    }
                }

                try
                {
                    // Train CV model and set iteration to the default
                    Console.WriteLine($"Training model");
                    var iteration = trainingApi.TrainProject(project.Id);
                    while (iteration.Status.Equals("Training"))
                    {
                        Thread.Sleep(1000);
                        iteration = trainingApi.GetIteration(project.Id, iteration.Id);
                        Console.WriteLine($"Model status: {iteration.Status}");
                    }

                    if (iteration.Status.Equals("Completed"))
                    {
                        iteration.IsDefault = true;
                        trainingApi.UpdateIteration(project.Id, iteration.Id, iteration);
                        Console.WriteLine($"Iteration: {iteration.Id} set as default");
                    }
                    else
                    {
                        Console.WriteLine($"Iteration status: {iteration.Status}");
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine($"Error training model (check you have at least 5 images per tag and 2 tags)");
                    Console.WriteLine($"Error {exp.Source}: {exp.Message}");
                }
            }
            else
            {
                // Quick test existing (trained) model
                Console.WriteLine($"Custom Vision Quick test: {ProjectName} with image {ImagePath}");

                // Retrieve CV project
                var projects = trainingApi.GetProjects();
                var project  = projects.Where(p => p.Name.Equals(ProjectName)).FirstOrDefault();
                if (project == null)
                {
                    Console.WriteLine($"Can't find Custom Vision Project: {ProjectName}");
                    return;
                }

                // Read test image
                if (!File.Exists(ImagePath))
                {
                    Console.WriteLine($"Can't find image: {ImagePath}");
                    return;
                }

                var image = new MemoryStream(File.ReadAllBytes(ImagePath));

                // Get the default iteration to test against and check results
                var iterations       = trainingApi.GetIterations(project.Id);
                var defaultIteration = iterations.Where(i => i.IsDefault == true).FirstOrDefault();
                if (defaultIteration == null)
                {
                    Console.WriteLine($"No default iteration has been set");
                    return;
                }

                var result = trainingApi.QuickTestImage(project.Id, image, defaultIteration.Id);
                foreach (var prediction in result.Predictions)
                {
                    Console.WriteLine($"Tag: {prediction.Tag} Probability: {prediction.Probability}");
                }
            }

            // fin
            stopwatch.Stop();
            Console.WriteLine($"Done.");
            Console.WriteLine($"Total time: {stopwatch.Elapsed}");
        }