예제 #1
0
        private IEnumerable <Image> GetImagesInBatch(Func <int, int, IEnumerable <ImageModel> > getAnImageModelBatch)
        {
            var tagIdToName = TrainingApi.GetTags(ProjectId, IterationId).Tags.ToDictionary(x => x.Id, x => x.Name);

            var batchIndex = 0;

            IList <ImageModel> imageModels;

            do
            {
                imageModels = getAnImageModelBatch(ImageDownloadBatchSize, batchIndex * ImageDownloadBatchSize).ToList();
                foreach (var imageModel in imageModels)
                {
                    yield return(new Image
                    {
                        Id = imageModel.Id,
                        Path = imageModel.ImageUri,
                        TagIds = imageModel.Labels?.Select(x => x.TagId).ToList(),
                        TagNames = imageModel.Labels?.Select(x => tagIdToName[x.TagId]).ToList()
                    });
                }

                batchIndex++;
            } while (imageModels.Count != 0);
        }
예제 #2
0
        private IEnumerable <Guid> GetTagIds(IEnumerable <string> tagNames)
        {
            var tagNameToDictionary = TrainingApi.GetTags(ProjectId, IterationId).Tags.ToDictionary(x => x.Name, x => x.Id);

            return(tagNames?.Select(x =>
            {
                Guid id;
                return tagNameToDictionary.TryGetValue(x, out id) ? id : Guid.Empty;
            }).Where(x => x != Guid.Empty).ToList() ?? Enumerable.Empty <Guid>());
        }
예제 #3
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);
        }
예제 #4
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);
        }
예제 #6
0
        public static void CreateImageFromUrls([QueueTrigger("create-image-from-urls")] CreateImageFromUrlsRequest imageCreateRequest, TraceWriter log)
        {
            log.Info($"C# Queue trigger function processed: {imageCreateRequest}");

            // https://docs.microsoft.com/ja-jp/azure/cognitive-services/custom-vision-service/csharp-tutorial
            var CV_ProjectId   = Environment.GetEnvironmentVariable("CV_ProjectId");
            var CV_TrainingKey = Environment.GetEnvironmentVariable("CV_TrainingKey");
            //var CV_PredictionKey = Environment.GetEnvironmentVariable("CV_PredictionKey");

            var trainingApi = new TrainingApi()
            {
                ApiKey = CV_TrainingKey
            };
            var projectId = Guid.Parse(CV_ProjectId);
            //var project = new ProjectInfo(trainingApi.GetProject(Guid.Parse(CV_ProjectId)));

            var requestTags      = imageCreateRequest.Tags.ToList();
            var existTags        = trainingApi.GetTags(projectId);
            var nonExistTagNames = requestTags.Except(existTags.Select(x => x.Name));
            var tagIds           = existTags.Where(x => requestTags.Contains(x.Name)).Select(x => x.Id).ToList();

            nonExistTagNames.ToList().ForEach(tagName =>
            {
                // XXX 同時に同じタグ名を指定された複数のキューを処理すると、重複してタグ作成してしまう。
                // 現状、重複エラー後のリトライで処理
                var tag = trainingApi.CreateTag(projectId, tagName);
                tagIds.Add(tag.Id);
            });

            var images = new List <ImageUrlCreateEntry>()
            {
                new ImageUrlCreateEntry()
                {
                    Url = imageCreateRequest.Url
                }
            };

            trainingApi.CreateImagesFromUrls(Guid.Parse(CV_ProjectId), new ImageUrlCreateBatch(images, tagIds));
        }
예제 #7
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();
            }
        }
예제 #8
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!");
        }
예제 #9
0
        /// <summary>
        /// 根据Project Id获取所有Tags
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ImageTagListModel GetAllTags(Guid projectId)
        {
            ImageTagListModel taglist = trainingApi.GetTags(projectId);

            return(taglist);
        }
예제 #10
0
        static void Main(string[] args)
        {
            // Add your training & prediction key from the settings page of the portal
            string trainingKey = "d7ba782c8051443c8557ff464418949f";

            // 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.GetProject(new Guid("65d4860d-036d-4e2a-97af-50c3afaec972"));


            var sourceDirectory  = System.Configuration.ConfigurationSettings.AppSettings["ImageSourece"];
            var imageDirectories = Directory.GetDirectories(sourceDirectory).ToList();

            foreach (var directory in imageDirectories)
            {
                var diseaseTags = directory.Split(new string[] { "___" }, StringSplitOptions.None);
                if (diseaseTags.Count() < 2)
                {
                    continue;
                }
                var diseaseTag = diseaseTags[1].Replace('_', ' ');
                if (diseaseTag == "healthy")
                {
                    continue;
                }
                var plantName = diseaseTags[0].Substring(diseaseTags[0].LastIndexOf('\\') + 1).Replace('_', ' ');

                var imagefiles  = Directory.GetFiles(Path.Combine(sourceDirectory, directory)).ToList();
                var imagePerTag = 190;

                var tagName = string.Format("{0} {1}", plantName, diseaseTag);
                if (trainingApi.GetTags(project.Id).Any(t => t.Name == tagName))
                {
                    continue;
                }
                var tag = trainingApi.CreateTag(project.Id, tagName);

                var randomFiles = GetRandomFiles(imagefiles, imagePerTag);
                //max upload size 64 in a batch
                var batchStartIndex = 0;
                var batchsize       = 64;
                while (batchStartIndex < imagePerTag)
                {
                    var itemsCountToTake   = (imagePerTag - batchStartIndex >= batchsize) ? batchsize : imagePerTag - batchStartIndex;
                    var batchImages        = randomFiles.Skip(batchStartIndex).Take(itemsCountToTake);
                    var imageFilesToUpload = batchImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList();
                    trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFilesToUpload, new List <Guid>()
                    {
                        tag.Id
                    }));
                    batchStartIndex += itemsCountToTake;
                }
            }


            // 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")
            {
                System.Threading.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");

            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            // Add your training key from the settings page of the portal
            string trainingKey = "YOUR TRAINING KEY";

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

            // Find the object detection domain
            var domains            = trainingApi.GetDomains();
            var objDetectionDomain = domains.FirstOrDefault(d => d.Type == "ObjectDetection");

            // Create a new project
            Console.WriteLine("Creating new project:");
            var project = trainingApi.CreateProject("CSharp Office", null, objDetectionDomain.Id);

            //var project = trainingApi.GetProject();

            using (StreamReader r = new StreamReader("Office.json"))
            {
                string json = r.ReadToEnd();
                Console.Write(json);
                var data = JObject.Parse(json);

                //Export Tags from code
                var inputTags = data["inputTags"].ToString().Split(',');
                foreach (string t in inputTags)
                {
                    Console.WriteLine(t);
                    trainingApi.CreateTag(project.Id, t);
                }


                // Get all tagsIDs created on custom vision and add into a dictionary
                Dictionary <string, Guid> imgtags = new Dictionary <string, Guid>();
                foreach (Tag t in trainingApi.GetTags(project.Id))
                {
                    Console.WriteLine(t.Name + " - " + t.Id);
                    imgtags.Add(t.Name, t.Id);
                }

                // Create Image TagIDs with normalized points
                Dictionary <string, double[]> imgtagdic = new Dictionary <string, double[]>();
                foreach (var a in data["visitedFrames"])
                {
                    Console.WriteLine(a);
                    try {
                        foreach (var key in data["frames"][a.ToString()])
                        {
                            double x1      = Convert.ToDouble(key["x1"].ToString());
                            double y1      = Convert.ToDouble(key["y1"].ToString());
                            double x2      = Convert.ToDouble(key["x2"].ToString());
                            double y2      = Convert.ToDouble(key["y2"].ToString());
                            int    h       = Convert.ToInt32(key["height"].ToString());
                            int    w       = Convert.ToInt32(key["width"].ToString());
                            double tleft   = (double)x1 / (double)w;
                            double ttop    = (double)y1 / (double)h;
                            double twidth  = (double)(x2 - x1) / (double)w;
                            double theight = (double)(y2 - y1) / (double)h;
                            try {
                                string tag = key["tags"][0].ToString();
                                // Defining UniqueID per tags in photo below
                                imgtagdic.Add(imgtags[tag].ToString() + "," + a.ToString() + ',' + key["name"].ToString() + tag, new double[] { tleft, ttop, twidth, theight });
                            }
                            catch {
                                Console.WriteLine("An Error occured on imtagdic");
                            }
                        }
                    }
                    catch {
                        Console.WriteLine("An Error occured on json parsing");
                    }
                }

                // Add all images for fork
                var      imagePath = Path.Combine("", "Office");
                string[] allphotos = Directory.GetFiles(imagePath);


                var imageFileEntries = new List <ImageFileCreateEntry>();
                foreach (var key in imgtagdic)
                {
                    Guid tagguid  = Guid.Parse(key.Key.Split(',')[0]);
                    var  fileName = allphotos[Convert.ToInt32(key.Key.Split(',')[1])];
                    imageFileEntries.Add(new ImageFileCreateEntry(fileName, File.ReadAllBytes(fileName), null, new List <Region>(new Region[] { new Region(tagguid, key.Value[0], key.Value[1], key.Value[2], key.Value[3]) })));

                    //
                    //Tried the add list of tags
                    //List<Guid> listtags = new List<Guid> { tagguid };
                    //imageFileEntries.Add(new ImageFileCreateEntry(fileName, File.ReadAllBytes(fileName), listtags, new List<Region>(new Region[] { new Region(tagguid, key.Value[0], key.Value[1], key.Value[2], key.Value[3]) })));
                }

                Console.WriteLine("\tUpload has started!");
                trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFileEntries));
                Console.WriteLine("\tUpload is done!");

                // 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 != "Completed")
                {
                    Thread.Sleep(1000);

                    // Re-query the iteration to get its 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");
            }
        }
예제 #12
0
        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();
                }
            }
        }
예제 #13
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);
            }
        }
예제 #14
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var allTags     = new List <string>();
                var json        = req.Content.ReadAsStringAsync().Result;
                var jobj        = JObject.Parse(json);
                var tags        = (JArray)jobj["tags"];
                var term        = jobj["term"].ToString();
                var projectId   = jobj["projectId"].ToString();
                var trainingKey = jobj["trainingKey"].ToString();
                var offset      = 0;

                if (jobj["offset"] != null)
                {
                    offset = (int)jobj["offset"];
                }

                var imageUrls = await SearchForImages(term, offset);

                var api     = new TrainingApi(new TrainingApiCredentials(trainingKey));
                var project = api.GetProject(Guid.Parse(projectId));

                var tagModels    = new List <ImageTagModel>();
                var existingTags = api.GetTags(project.Id);
                foreach (string tag in tags)
                {
                    ImageTagModel model = existingTags.Tags.SingleOrDefault(t => t.Name == tag);

                    if (model == null)
                    {
                        model = api.CreateTag(project.Id, tag.Trim());
                    }

                    tagModels.Add(model);
                }

                var batch   = new ImageUrlCreateBatch(tagModels.Select(m => m.Id).ToList(), imageUrls);
                var summary = api.CreateImagesFromUrls(project.Id, batch);

                //if(!summary.IsBatchSuccessful)
                //	return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Image batch was unsuccessful");

                //Traing the classifier and generate a new iteration, that we'll set as the default
                var iteration = api.TrainProject(project.Id);

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

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

                return(req.CreateResponse(HttpStatusCode.OK, iteration.Id));
            }
            catch (Exception e)
            {
                var exception = e.GetBaseException();
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, exception.Message));
            }

            async Task <List <string> > SearchForImages(string term, int offset)
            {
                var client = new HttpClient();

                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "c2adf0e5c057447ea9e0f50cc5202251");
                var uri = $"https://api.cognitive.microsoft.com/bing/v7.0/images/search?count=50&q={term}&offset={offset}";

                var json = await client.GetStringAsync(uri);

                var jobj = JObject.Parse(json);
                var arr  = (JArray)jobj["value"];

                var list = new List <string>();

                foreach (var result in arr)
                {
                    list.Add(result["contentUrl"].ToString());
                }

                return(list);
            }
        }