private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            Log("Loading Images from Disk");
            LoadImagesFromDisk();
            Log("Loading Images Complete");


            Log("Uploading images to service");
            // Images can be uploaded one at a time
            foreach (var image in validImages)
            {
                using (var stream = new MemoryStream(File.ReadAllBytes(image)))
                {
                    trainingApi.CreateImagesFromData(project.Id, stream, new List <string>()
                    {
                        validTag.Id.ToString()
                    });
                }
            }

            // Or uploaded in a single batch
            var imageFiles = invalidImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList();

            trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>()
            {
                invalidTag.Id
            }));
            Log("Images Uploaded");
        }
        private static void trainStream(System.Drawing.Image augImage, TrainingApi trainingApi, Guid projectId, string tagId)
        {
            MemoryStream augImageStream = new MemoryStream();

            augImage.Save(augImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            augImageStream.Seek(0, SeekOrigin.Begin);
            trainingApi.CreateImagesFromData(projectId, augImageStream, new List <string>()
            {
                tagId
            });
        }
Example #3
0
        /// <summary>
        /// Train a Model given a set of trainings
        /// </summary>
        /// <param name="project"></param>
        /// <param name="trainings"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public void TrainModel(ref ProjectModel project, IList <Models.Training> trainings)
        {
            // Save all Training Tasks to be performed
            //var tagCreationTasks = (from training in trainings
            //        from tag in training.Tags
            //        select TrainingApi.CreateTagAsync(project.Id, tag.ToString(), cancellationToken: token)).
            //    Cast<Task>().ToList();

            var tagNames    = trainings.Select(t => t.TagName).Distinct();
            var tagNameToId = new Dictionary <string, Guid>();

            foreach (var tagName in tagNames)
            {
                var tagModel = TrainingApi.CreateTag(project.Id, tagName);
                tagNameToId.Add(tagName, tagModel.Id);
            }

            // Execute Trainings
            //await Task.WhenAny(tagCreationTasks);

            foreach (var training in trainings)
            {
                TrainingApi.CreateImagesFromData(project.Id, training.ImageFileStream,
                                                 new List <string> {
                    tagNameToId[training.TagName].ToString()
                });
            }

            //var imageCreationTasks = (from training in trainings
            //    from tag in training.Tags
            //    select TrainingApi.CreateImagesFromDataAsync(project.Id, training.ImageFileStream, new List<string> { tag.ToString() }, cancellationToken: token)).Cast<Task>().ToList();

            //await Task.WhenAny(imageCreationTasks);

            var iterationModel = TrainingApi.TrainProject(project.Id);


            // The returned iteration will be in progress, and can be queried periodically to see when it has completed
            while (iterationModel.Status == "Training")
            {
                Thread.Sleep(1000);

                // Re-query the iteration to get it's updated status
                iterationModel = TrainingApi.GetIteration(project.Id, iterationModel.Id);
            }

            iterationModel.IsDefault = true;

            // Complete Training
            TrainingApi.UpdateIteration(project.Id, iterationModel.Id, iterationModel);
        }
Example #4
0
        private static void UploadImages(String ImagePath, TrainingApi trainingApi, ProjectModel project, List <string> tags)
        {
            // Load images to upload and tag from disk
            List <MemoryStream> images = LoadImagesFromDisk(ImagePath);

            Console.Write("\tUploading");

            int count         = 0;
            int uploadCounter = 0;
            int skip          = 1;

            foreach (var image in images)
            {
                if (count % skip == 0)
                {
                    try
                    {
                        Console.Write(".");
                        trainingApi.CreateImagesFromData(project.Id, image, tags);
                        uploadCounter++;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"\n\tException: {e.Message}");
                        Console.Write("\n\tContinuing");
                    }
                }

                count++;

                if (count == max * skip)
                {
                    break;
                }

                //Remove image from memory
                //image.Dispose();

                // Throttle upload
                //Thread.Sleep(100);
            }

            Console.Write($"\tSuccessfully uploaded {uploadCounter} images.\n");
        }
Example #5
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);
        }
        public int Execute()
        {
            string tagName    = _tagArgument.Value;
            string imagesPath = _pathArgument.Value;

            if (!Directory.Exists(imagesPath))
            {
                return(Util.Fail($"The path '{imagesPath}' does not exist"));
            }

            string[] trainingImages = Directory.GetFiles(imagesPath);

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

            TagList tagList = trainingApi.GetTags(_projectId);
            Tag     tag     = tagList.Tags.FirstOrDefault(t => t.Name == tagName);

            if (tag == null)
            {
                return(Util.Fail($"No tag named {tagName} was found."));
            }

            List <string> tagIds = new List <string> {
                tag.Id.ToString()
            };

            foreach (var imagePath in trainingImages)
            {
                Console.Write($"Uploading '{imagePath}'... ");
                using (var imageStream = new MemoryStream(File.ReadAllBytes(imagePath)))
                    trainingApi.CreateImagesFromData(_projectId, imageStream, tagIds);
                Console.WriteLine($"done");
            }

            Console.WriteLine($"\r\nDone uploading {trainingImages.Length} images.");

            return(0);
        }
Example #7
0
            public void Classify()
            {
                Console.WriteLine("thread starting for {0}", f);
                WebClient client      = new WebClient();
                var       thisFoodTag = trainingApi.CreateTag(project.Id, f);

                Console.WriteLine("training for {0}", f);
                SearchResult     res    = BingImageSearch(f);
                SearchResultJson result = JsonConvert.DeserializeObject <SearchResultJson>(res.jsonResult);
                List <Stream>    ms     = new List <Stream>();

                Console.WriteLine("downloading {0} images", result.value.Count);
                foreach (var g in result.value)
                {
                    string img = g.thumbnailUrl;

                    /*try
                     * {*/
                    Console.WriteLine("url: {0}", img);
                    Stream s = new MemoryStream(client.DownloadData(img));
                    Console.WriteLine("{0} downloaded ok", img);
                    trainingApi.CreateImagesFromData(project.Id, s, new List <String> {
                        thisFoodTag.Id.ToString()
                    });
                    //trainingApi.TrainProject(project.Id);

                    /*}
                     * catch (Exception ex)
                     * {
                     *  Console.WriteLine("errored for {0}", img);
                     * }*/
                }
                Console.WriteLine("download OK, training");

                Console.WriteLine("training done for {0}", f);
            }
        static void Main(string[] args)
        {
            // Add your training and prediction key from the settings page of the portal
            string trainingKey   = "<add your training key here>";
            string predictionKey = "<add your prediction key here>";

            // Create the Api, passing in the training key

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

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

            // 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");
            LoadImagesFromDisk();

            // Images are then uploaded
            foreach (var image in hemlockImages)
            {
                trainingApi.CreateImagesFromData(project.Id, image, new List <string>()
                {
                    hemlockTag.Id.ToString()
                });
            }

            foreach (var image in japaneseCherryImages)
            {
                trainingApi.CreateImagesFromData(project.Id, image, new List <string>()
                {
                    japaneseCherryTag.Id.ToString()
                });
            }

            // 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("Done!\n");

            // Now there is a trained endpoint, it can be used to make a prediction
            PredictionEndpoint endpoint = new PredictionEndpoint()
            {
                ApiKey = predictionKey
            };

            // 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.TagName}: {c.Probability:P1}");
            }
            Console.ReadKey();
        }
Example #9
0
        public void Main(string[] args)
        {
            // Add your training & prediction key from the settings page of the portal
            string trainingKey = "d7ba782c8051443c8557ff464418949f";
            //string predictionKey = "<your prediction key here>";

            // Create the Api, passing in the training key
            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };

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

            // 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");
            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 <string>()
                    {
                        hemlockTag.Id.ToString()
                    });
                }
            }

            // 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
            }));

            // 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("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
            PredictionEndpoint endpoint = new PredictionEndpoint()
            {
                ApiKey = predictionKey
            };

            // 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.TagName}: {c.Probability:P1}");
            }
            Console.ReadKey();
        }
Example #10
0
        private static void CreateTheModel(string trainingSetPath, Project project)
        {
            var trainingKey = ConfigurationManager.AppSettings["CustomVision_TrainingKey"];
            var trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };

            var trainingModel = new List <Model>();

            var trainingSet = Directory.GetDirectories(trainingSetPath);

            foreach (var subdirectory in trainingSet)
            {
                var dir  = new DirectoryInfo(subdirectory);
                var name = dir.Name;

                Console.WriteLine($"\tAdding Tag - {name}");
                var tag = trainingApi.CreateTag(project.Id, name);

                var images = Directory.GetFiles($"{subdirectory}").Select(f =>
                {
                    trainingModel.Add(new Model()
                    {
                        Label = name, Path = f
                    });
                    return(new MemoryStream(File.ReadAllBytes(f)));
                }).ToList();

                foreach (var image in images)
                {
                    try
                    {
                        Console.WriteLine($"\tUploading image with tag: {tag.Name}");
                        trainingApi.CreateImagesFromData(project.Id, image, new List <string>()
                        {
                            tag.Id.ToString()
                        });
                    }
                    catch (Exception e)
                    {
                        //kill exception and carry on
                        Console.WriteLine(e);
                    }
                }
            }

            try
            {
                using (TextWriter writer = new StreamWriter($"{trainingSetPath}\\trainingModel.csv"))
                {
                    var csv = new CsvWriter(writer);

                    csv.WriteRecords(trainingModel);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #11
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("<your key here>", 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("Car Assessment");

            // Make two tags in the new project
            var WriteOffTag = trainingApi.CreateTag(project.Id, "WriteOff");
            var DentTag     = trainingApi.CreateTag(project.Id, "Dent");

            // Add some images to the tags
            Console.WriteLine("\\tUploading images");
            LoadImagesFromDisk();

            // Images can be uploaded one at a time
            foreach (var image in WriteOffImages)
            {
                trainingApi.CreateImagesFromData(project.Id, image, new List <string> ()
                {
                    WriteOffTag.Id.ToString()
                });
            }

            // Or uploaded in a single batch
            trainingApi.CreateImagesFromData(project.Id, DentImages, new List <Guid> ()
            {
                DentTag.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("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();
        }
        static void Main(string[] args)
        {
            // Agregue su clave de entrenamiento desde la página de configuración del portale
            string trainingKey = "8f15a89a49a44979bf478d9391a45cd6";


            // Crea el Api, pasando la clave de entrenamiento
            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };

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


            // Crea un nuevo proyecto
            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");
            LoadImagesFromDisk();


            // Las imágenes se pueden cargar de a una por vez
            foreach (var image in hemlockImages)
            {
                using (var stream = new MemoryStream(File.ReadAllBytes(image)))
                {
                    trainingApi.CreateImagesFromData(project.Id, stream, new List <string>()
                    {
                        hemlockTag.Id.ToString()
                    });
                }
            }

            // O subido en un solo lote
            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
            }));


            // Ahora hay imágenes con etiquetas que comienzan a entrenar el proyecto
            Console.WriteLine("\tTraining");
            var iteration = trainingApi.TrainProject(project.Id);


            // La iteración devuelta estará en progreso, y se puede consultar periódicamente para ver cuándo se completó
            while (iteration.Status == "Training")
            {
                Thread.Sleep(1000);

                // Vuelva a consultar la iteración para obtener su estado actualizado
                iteration = trainingApi.GetIteration(project.Id, iteration.Id);
            }


            // La iteración ahora está entrenada. Convertirlo en el punto final predeterminado del proyecto
            iteration.IsDefault = true;
            trainingApi.UpdateIteration(project.Id, iteration.Id, iteration);
            Console.WriteLine("Done!\n");


            // Ahora hay un punto final entrenado, se puede usar para hacer una predicción

            // Agregue su clave de predicción desde la página de configuración del portal
            // La clave de predicción se usa en lugar de la clave de entrenamiento cuando se hacen predicciones
            string predictionKey = "559018cc3d434cef8095da2e8b8dd30c";


            // Crear un punto final de predicción, pasando la clave de predicción obtenida
            PredictionEndpoint endpoint = new PredictionEndpoint()
            {
                ApiKey = predictionKey
            };


            // Hacer una predicción contra el nuevo proyecto
            Console.WriteLine("Making a prediction:");
            var result = endpoint.PredictImage(project.Id, testImage);


            // Pasa el cursor sobre cada predicción y escribe los resultados
            foreach (var c in result.Predictions)
            {
                Console.WriteLine($"\t{c.Tag}: {c.Probability:P1}");
            }
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            // Add your training key from the settings page of the portal
            //76af0d521ed848ce8d4c8c70b7fb1f2b
            //5d0b18588d934e1293008dcf75dd0606
            string trainingKey = "76af0d521ed848ce8d4c8c70b7fb1f2b";


            // Create the Api, passing in the training key
            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };

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

            // Load all image folders
            imageLists = Directory.GetDirectories(@"..\..\..\Images").ToList();


            List <Tag> imageTags = new List <Tag>();

            foreach (string imageList in imageLists)
            {
                string imageClass = imageList.Split('\\').LastOrDefault();

                Tag imageTag = trainingApi.CreateTag(project.Id, imageClass);
                imageTags.Add(imageTag);

                DirectoryInfo d     = new DirectoryInfo(@imageList);
                FileInfo[]    infos = d.GetFiles();

                List <string> images = Directory.GetFiles(@imageList).ToList();

                foreach (var image in images)
                {
                    using (var stream = new MemoryStream(File.ReadAllBytes(image)))
                    {
                        trainingApi.CreateImagesFromData(project.Id, stream, new List <string>()
                        {
                            imageTag.Id.ToString()
                        });
                    }
                }
            }



            //    // 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("Done!\n");

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

            //    // Add your prediction key from the settings page of the portal
            //    // The prediction key is used in place of the training key when making predictions
            //    string predictionKey = "<your key here>";

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

            //    // 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();
            //}

            //private static void LoadImagesFromDisk()
            //{
            //    // this loads the images to be uploaded from disk into memory
            //    hemlockImages = Directory.GetFiles(@"..\..\..\Images\Hemlock").ToList();
            //    japaneseCherryImages = Directory.GetFiles(@"..\..\..\Images\Japanese Cherry").ToList();
            //    testImage = new MemoryStream(File.ReadAllBytes(@"..\..\..\Images\Test\test_image.jpg"));
            //}
        }
Example #14
0
 /// <summary>
 /// 上传图片
 /// </summary>
 /// <param name="projectId"></param>
 /// <param name="fileStream"></param>
 /// <param name="tagIds"></param>
 /// <returns></returns>
 public Task UploadImage(Guid projectId, Stream fileStream, List <string> tagIds)
 {
     return(Task.Run(() => {
         trainingApi.CreateImagesFromData(projectId, fileStream, tagIds);
     }));
 }
        static void Main(string[] args)
        {
            string      trainingKey = GetTrainingKey(configTrainingKey, args);
            TrainingApi trainingApi = new TrainingApi {
                ApiKey = trainingKey
            };

            Console.WriteLine("Creating new project:");

            var project   = trainingApi.CreateProject("Bike Type");
            var MbikesTag = trainingApi.CreateTag(project.Id, "Mountain");
            var RbikesTag = trainingApi.CreateTag(project.Id, "Racing");

            Console.WriteLine("\tUploading images");
            LoadImages();

            foreach (var image in bikesImages)
            {
                trainingApi.CreateImagesFromData(project.Id, image, new List <string>()
                {
                    MbikesTag.Id.ToString()
                });
            }

            foreach (var image in rBikesImages)
            {
                trainingApi.CreateImagesFromData(project.Id, image, new List <string>()
                {
                    RbikesTag.Id.ToString()
                });
            }

            trainingApi.CreateImagesFromData(project.Id, testImage, new List <string>()
            {
                MbikesTag.Id.ToString()
            });

            Console.WriteLine("\tTraining");
            var iteration = trainingApi.TrainProject(project.Id);

            while (iteration.Status.Equals("Training"))
            {
                Thread.Sleep(1000);
                iteration = trainingApi.GetIteration(project.Id, iteration.Id);
            }

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

            Console.WriteLine("Done!\n");

            var predictionKey           = GetPredictionKey(configPredictionKey, args);
            PredictionEndpoint endpoint = new PredictionEndpoint {
                ApiKey = predictionKey
            };

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

            foreach (var c in result.Predictions)
            {
                Console.WriteLine($"\t{c.Tag}: {c.Probability:P1}");
            }

            Console.ReadKey();
        }
Example #16
0
        private static void CreateTheModel(string trainingSetPath, Project project)
        {
            var trainingKey = ConfigurationManager.AppSettings["CustomVision_TrainingKey"];
            var trainingApi = new TrainingApi()
            {
                ApiKey = trainingKey
            };

            var trainingModel = new List <Model>();

            bool performImageAugmentation = true;

            try
            {
                performImageAugmentation = Convert.ToBoolean(ConfigurationManager.AppSettings["PerformImageAugmentation"]);
            }
            catch { }

            int widthHeight = 299;

            try
            {
                widthHeight = Convert.ToInt32(ConfigurationManager.AppSettings["WidthHeight"]);
            }
            catch { }

            int padImages = 10;

            try
            {
                padImages = Convert.ToInt32(ConfigurationManager.AppSettings["PadImages"]);
            }
            catch { }

            var trainingSet = Directory.GetDirectories(trainingSetPath);

            foreach (var subdirectory in trainingSet)
            {
                var dir  = new DirectoryInfo(subdirectory);
                var name = dir.Name;

                Console.WriteLine($"\tAdding Tag - {name}");

                var tag = trainingApi.CreateTag(project.Id, name);

                var images = Directory.GetFiles($"{subdirectory}").Select(f =>
                {
                    trainingModel.Add(new Model()
                    {
                        Label = name, Path = f
                    });
                    return(new MemoryStream(File.ReadAllBytes(f)));
                }).ToList();

                foreach (var image in images)
                {
                    try
                    {
                        Console.WriteLine($"\tUploading image with tag: {tag.Name}");

                        if (performImageAugmentation)
                        {
                            // flip from RGB to BGR
                            System.Drawing.Bitmap img   = new System.Drawing.Bitmap(image);
                            Image <Bgr, byte>     ogImg = new Image <Bgr, byte>(img);

                            // perform Intensity Image Equalization
                            Image <Ycc, byte> ycrcb = ogImg.Convert <Ycc, byte>();
                            ycrcb._EqualizeHist();
                            ogImg = ycrcb.Convert <Bgr, byte>(); //replace original image with equalized image

                            int top    = 0;
                            int bottom = 0;
                            int left   = 0;
                            int right  = 0;

                            if (img.Width != img.Height)
                            {
                                // we need to pad our image if the width and height aren't set already in a previous smart crop step

                                if (img.Width < img.Height)
                                {
                                    int dif = img.Height - img.Width;
                                    left  = dif / 2;
                                    right = dif - left;
                                }

                                if (img.Height < img.Width)
                                {
                                    int dif = img.Width - img.Height;
                                    top    = dif / 2;
                                    bottom = dif - top;
                                }
                            }

                            if (padImages > 0)
                            {
                                top    += padImages;
                                bottom += padImages;
                                left   += padImages;
                                right  += padImages;
                            }

                            if ((top > 0) || (bottom > 0) || (left > 0) || (right > 0))
                            {
                                Image <Bgr, byte> padImg = new Image <Bgr, byte>(img.Width + left + right, img.Height + top + bottom);
                                CvInvoke.CopyMakeBorder(ogImg, padImg, top, bottom, left, right, Emgu.CV.CvEnum.BorderType.Constant, new MCvScalar(255, 255, 255)); // pad the image with a white background
                                ogImg = padImg;
                            }

                            if (ogImg.Width != widthHeight)
                            {
                                // resize the padded image
                                ogImg = ogImg.Resize(widthHeight, widthHeight, Emgu.CV.CvEnum.Inter.Linear);
                            }

                            trainStream(ogImg.ToBitmap(), trainingApi, project.Id, tag.Id.ToString());

                            for (var i = 0; i < 3; i++)
                            {
                                if ((new Random().Next(1, 11)) <= 5)
                                {
                                    // 50% of the time flip the image horizontally before rotation
                                    ogImg = ogImg.Flip(Emgu.CV.CvEnum.FlipType.Horizontal);
                                }
                                trainStream(ogImg.Rotate(new Random().Next(-45, 45), new Bgr(255, 255, 255)).ToBitmap(), trainingApi, project.Id, tag.Id.ToString()); // rotate with a white background
                            }
                        }
                        else
                        {
                            trainingApi.CreateImagesFromData(project.Id, image, new List <string>()
                            {
                                tag.Id.ToString()
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        //kill exception and carry on
                        Console.WriteLine(e);
                    }
                }
            }

            try
            {
                using (TextWriter writer = new StreamWriter($"{trainingSetPath}\\trainingModel.csv"))
                {
                    var csv = new CsvWriter(writer);

                    csv.WriteRecords(trainingModel);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #17
0
        static void Main(string[] args)
        {
            string chaveClassificacao = "<Chave de treinamento>";
            string idProjeto          = "<ID Projeto>";

            // Crio o cliente para o Azure Custom View
            TrainingApi trainingApi = new TrainingApi()
            {
                ApiKey = chaveClassificacao
            };

            Console.WriteLine("Iniciando as tags.");

            // Crio a tag shitzu
            Tag shitzuTag = trainingApi.CreateTag(new Guid(idProjeto), "Shitzu");
            // Crio a tag poodle
            Tag poodleTag = trainingApi.CreateTag(new Guid(idProjeto), "Poodle");

            // Carrego as imagens de shitzu
            string[] imagensShitzu = Directory.GetFiles(Path.Combine("Amostras", "Shitzu")).ToArray();

            // Carrego as imagens de poodle
            string[] imagensPoodle = Directory.GetFiles(Path.Combine("Amostras", "Poodle")).ToArray();

            Console.WriteLine("Cadastrando as imagens de shitzu.");

            // Cadastro das imagens de shitzu
            foreach (var imagem in imagensShitzu)
            {
                using (var stream = new MemoryStream(File.ReadAllBytes(imagem)))
                {
                    trainingApi.CreateImagesFromData(new Guid(idProjeto), stream, new List <string>()
                    {
                        shitzuTag.Id.ToString()
                    });
                }
            }

            Console.WriteLine("Cadastrando as imagens de poodle.");

            // Cadastro das imagens de poodle
            foreach (var imagem in imagensPoodle)
            {
                using (var stream = new MemoryStream(File.ReadAllBytes(imagem)))
                {
                    trainingApi.CreateImagesFromData(new Guid(idProjeto), stream, new List <string>()
                    {
                        poodleTag.Id.ToString()
                    });
                }
            }

            // Inicio o treinamento com as imagens cadastradas.
            Iteration interacao = trainingApi.TrainProject(new Guid(idProjeto));

            Console.WriteLine("Treinando.");

            // Verifico periodicamente até concluir
            while (interacao.Status == "Training")
            {
                Thread.Sleep(1000);

                // Verifico novamente o status
                interacao = trainingApi.GetIteration(new Guid(idProjeto), interacao.Id);
            }

            // Agora que o treinamento está concluído, configuro como o endpoint padrão.
            interacao.IsDefault = true;
            trainingApi.UpdateIteration(new Guid(idProjeto), interacao.Id, interacao);
            Console.WriteLine("Finalizado.");
        }
        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (pictureBox1.BackgroundImage == null)
            {
                MessageBox.Show("Missing image or selected regions");
                return;
            }

            if (currentPredictionMode == PredictionMode.Detection)
            {
                if (treeListToUpload.Count == 0)
                {
                    MessageBox.Show("Missing selected regions");
                    return;
                }
                try
                {
                    var imageFileEntries = new List <ImageFileCreateEntry>();

                    List <Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models.Region> regions = new List <Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models.Region>();
                    foreach (var item in treeListToUpload)
                    {
                        var tagList = trainingApi.GetTags(project.Id);
                        Tag tag     = tagList.FirstOrDefault(x => x.Name.ToLower().Equals(item.TagName.ToLower()));

                        if (tag == null)
                        {
                            tag = trainingApi.CreateTag(project.Id, System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(item.TagName.ToLower()));
                        }

                        var region = new double[] { item.BoundingBox.Left, item.BoundingBox.Top, item.BoundingBox.Width, item.BoundingBox.Height };
                        regions.Add(new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models.Region(tag.Id, region[0], region[1], region[2], region[3]));
                    }

                    imageFileEntries.Add(new ImageFileCreateEntry(null, GetStream(pictureBox1.BackgroundImage).ToArray(), null, regions));

                    trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFileEntries));
                    treeListToUpload.Clear();
                    pictureBox1.Invalidate();
                    MessageBox.Show("The image is uploaded successfully");
                }
                catch (Exception ex)
                {
                    labelInfo.Text = ex.ToString();
                }
            }
            else if (currentPredictionMode == PredictionMode.Classification)
            {
                if (imageTagToUpload == "")
                {
                    MessageBox.Show("Missing tag");
                    return;
                }
                try
                {
                    var tagList = trainingApi.GetTags(project.Id);
                    Tag tag     = tagList.FirstOrDefault(x => x.Name.ToLower().Equals(imageTagToUpload.ToLower()));
                    if (tag == null)
                    {
                        tag = trainingApi.CreateTag(project.Id, imageTagToUpload.ToLower());
                    }
                    trainingApi.CreateImagesFromData(project.Id, GetStream(pictureBox1.BackgroundImage), new List <string>()
                    {
                        tag.Id.ToString()
                    });
                    MessageBox.Show("The image is uploaded successfully");
                }
                catch (Exception ex)
                {
                    labelInfo.Text = ex.ToString();
                }
            }
        }