Пример #1
0
        // Analyze a local image
        private static async Task GetAreaOfInterestFromStreamAsync(ComputerVisionClient computerVision, string imagePath)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                AreaOfInterestResult analysis = await computerVision.GetAreaOfInterestInStreamAsync(imageStream);

                Console.WriteLine(imagePath);
                DisplayAreaOfInterest(analysis);
            }
        }
Пример #2
0
        // Recognize text from a local image
        private static async Task ExtractLocalTextAsync(
            ComputerVisionClient computerVision, System.Drawing.Image img)
        {
            using (Stream imageStream = new MemoryStream())
            {
                img.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                imageStream.Seek(0, SeekOrigin.Begin);

                // Start the async process to recognize the text
                RecognizeTextInStreamHeaders textHeaders =
                    await computerVision.RecognizeTextInStreamAsync(
                        imageStream, textRecognitionMode);

                await GetTextAsync(computerVision, textHeaders.OperationLocation);
            }
        }
Пример #3
0
 public override ApiResult Init()
 {
     try
     {
         ApiKeyServiceClientCredentials c = new ApiKeyServiceClientCredentials(ApiAccountKey);
         Client          = new ComputerVisionClient(c);
         Client.Endpoint = ApiEndpointUrl;
         return(SetInitializedStatusAndReturnSucces());
     }
     catch (Exception e)
     {
         Error(e, "Error creating Microsoft Computer Vision API client.");
         Status = ApiStatus.RemoteApiClientError;
         return(ApiResult.Failure);
     }
 }
Пример #4
0
        public static async Task RunAsync(string endpoint, string key)
        {
            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
            {
                Endpoint = endpoint
            };

            // See this repo's README.md on how to get these images.
            // Alternatively, you can just set the path to any appropriate image on your machine.
            string localImagePath = @"Images\objects.jpg";
            string remoteImageUrl = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/faces.jpg";

            Console.WriteLine("area of interest being found ...");
            await GetAreaOfInterestFromUrlAsync(computerVision, remoteImageUrl);
            await GetAreaOfInterestFromStreamAsync(computerVision, localImagePath);
        }
        async Task PredictPhoto(MediaFile photo)
        {
            ComputerVisionClient computerVision = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(subscriptionKey),
                new System.Net.Http.DelegatingHandler[] { });

            computerVision.Endpoint = AppSettingsManager.Settings["CognitiveServicesEndpoint"];

            // Analyse.
            var objectResults = await computerVision.AnalyzeImageInStreamAsync(photo.GetStream(), features);

            AllPredictions = objectResults.Objects
                             .Where(p => p.Confidence > Probability)
                             .ToList();
            AllCategories = objectResults.Categories.ToList();
        }
        public async static Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            var computerVisionClient = new ComputerVisionClient(new ApiKeyServiceClientCredentials(Constants.ComputerVisionApiKey));

            computerVisionClient.Endpoint = Constants.ComputerVisionEndpoint;

            var imageStream = req.Body;

            var result = await computerVisionClient.AnalyzeImageInStreamAsync(imageStream, details : new [] { Details.Landmarks });

            var landmark = result.Categories.FirstOrDefault(c => c.Detail != null && c.Detail.Landmarks.Any());

            return(landmark != null ? (ActionResult) new OkObjectResult($"I think I see the {landmark.Detail.Landmarks.First().Name}")
                    : new BadRequestObjectResult("No landmark was found in this image"));
        }
Пример #7
0
        private static ComputerVisionClient GetComputerVisionClient()
        {
            if (computerVisionClient == null)
            {
                var computerVisionKey = System.Environment.GetEnvironmentVariable("COMPUTER_VISION_KEY");
                var computerVisionUrl = System.Environment.GetEnvironmentVariable("COMPUTER_VISION_URL");

                computerVisionClient = new ComputerVisionClient(
                    new ApiKeyServiceClientCredentials(computerVisionKey),
                    new System.Net.Http.DelegatingHandler[] { });

                computerVisionClient.Endpoint = computerVisionUrl;
            }

            return(computerVisionClient);
        }
Пример #8
0
        // [HttpPost]
        // [Route("api/Ocr/GetLines")]
        // public async Task<ActionResult<string>> GetLines()
        // {
        //     return this.Ok("Test");
        // }

        private async Task<OcrResult> AzureOcr(Stream fileStream)
        {
            string subscriptionKey = "";
            string endpoint = "";

            var computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey))
            {
                Endpoint = endpoint,
            };

            var analysis = await computerVision.RecognizePrintedTextInStreamAsync(true, fileStream);

            //var result = DisplayResults(analysis);

            return analysis;
        }
Пример #9
0
        // Analyze a local image
        private static async Task RecognizeDomainSpecificContentFromStreamAsync(ComputerVisionClient computerVision, string imagePath, string specificDomain)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                DomainModelResults analysis = await computerVision.AnalyzeImageByDomainInStreamAsync(specificDomain, imageStream);  //change "celebrities" to "landmarks" if that is the domain you are interested in

                Console.WriteLine(imagePath);
                DisplayResults(analysis);
            }
        }
        public static string[] UploadImageAndHandleTagsResoult(Stream photo, float recognizeLevel = 0.5f)
        {
            RecognizeLevelPublic = recognizeLevel;

            ComputerVisionClient computerVision = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(Variables.SUBSCRIPTION_KEY_FOR_AI_VISION),
                new System.Net.Http.DelegatingHandler[] { });

            computerVision.Endpoint = Variables.ENDPOINT_FOR_AI_VISION;

            Task <string[]> t1 = AnalyzeLocalAsync(computerVision, photo);

            t1.Wait();

            return(t1.Result);
        }
Пример #11
0
        private static async Task OCRFromStreamAsync(ComputerVisionClient computerVision, string imagePath)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                OcrResult analysis = await computerVision.RecognizePrintedTextInStreamAsync(true, imageStream);

                Console.WriteLine(imagePath);
                DisplayResults(analysis);
            }
        }
        // Analyze a local image
        private static async Task DescribeImageFromStreamAsync(ComputerVisionClient computerVision, string imagePath)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                ImageDescription descriptions = await computerVision.DescribeImageInStreamAsync(imageStream);

                Console.WriteLine(imagePath);
                DisplayDescriptions(descriptions);
            }
        }
Пример #13
0
        // Read text from a remote image
        private static async Task ExtractTextFromUrlAsync(ComputerVisionClient computerVision, string imageUrl, int numberOfCharsInOperationId)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                Console.WriteLine("\nInvalid remote image url:\n{0} \n", imageUrl);
                return;
            }

            // For handwritten text, change to TextRecognitionMode.Handwritten
            TextRecognitionMode textRecognitionMode = TextRecognitionMode.Printed;

            // Start the async process to read the text
            BatchReadFileHeaders textHeaders = await computerVision.BatchReadFileAsync(imageUrl, textRecognitionMode);

            await GetTextAsync(computerVision, textHeaders.OperationLocation, numberOfCharsInOperationId);
        }
Пример #14
0
        public ImageDescriptionService()
        {
            _computerVision = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(SUBSCRIPTION_KEY),
                new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = ENDPOINT
            };

            _features = new List <VisualFeatureTypes>()
            {
                VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
                VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,
                VisualFeatureTypes.Tags
            };
        }
        // Analyze a local image
        private static async Task TagImageFromStreamAsync(ComputerVisionClient computerVision, string imagePath)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                TagResult tags = await computerVision.TagImageInStreamAsync(imageStream);

                Console.WriteLine(imagePath);
                DisplayTags(tags);
            }
        }
Пример #16
0
        public static async Task <byte[]> ReplaceWordsInImage(
            ComputerVisionClient client,
            byte[] originalImage,
            string[] wordsToReplace,
            decimal scaleUp = 1)
        {
            IImageFormat imgFormat;

            using (var slxImage = Image.Load(originalImage, out imgFormat)) {
                var oldSize         = new Size(slxImage.Width, slxImage.Height);
                var maxWidthRatio   = Convert.ToDecimal(4200d / slxImage.Width);
                var maxHeightRation = Convert.ToDecimal(4200d / slxImage.Height);
                var maxRatio        = maxWidthRatio < maxHeightRation ? maxWidthRatio : maxHeightRation;
                maxRatio = (maxRatio < scaleUp) ? maxRatio : scaleUp;
                var newSize = new Size(Convert.ToInt32(slxImage.Width * maxRatio), Convert.ToInt32(slxImage.Height * maxRatio));
                using (var ms = new MemoryStream()) {
                    // There is a real possibility that the image requires scaling up to read text at small resolutions (I've had issues at 1920 x 1080).
                    // So, we need the option to resize the image upwards.
                    if (maxRatio > 1)
                    {
                        slxImage.Mutate(ctx => ctx.Resize(newSize));
                    }
                    // Azure Computer Vision requires a stream, hence the save to MemoryStream
                    slxImage.Save(ms, imgFormat);
                    ms.Seek(0, SeekOrigin.Begin);
                    var result = await client.RecognizePrintedTextInStreamAsync(false, ms);

                    var bounds = result.Coordinates(wordsToReplace);

                    foreach (var boundingBox in bounds)
                    {
                        var rect = new Rectangle(boundingBox[0], boundingBox[1], boundingBox[2], boundingBox[3]);
                        slxImage.Mutate(ctx => ctx.BoxBlur(rect.Width / 2, rect));
                    }

                    if (maxRatio > 1)
                    {
                        slxImage.Mutate(ctx => ctx.Resize(oldSize));
                    }

                    using (var resultMs = new MemoryStream()) {
                        slxImage.Save(resultMs, imgFormat);
                        return(resultMs.ToArray());
                    }
                }
            }
        }
Пример #17
0
        // public static ComputerVisionClient Authenticate(string endpoint, string key)
        // {
        //     ComputerVisionClient client =
        //       new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
        //       { Endpoint = endpoint };
        //     return client;
        // }

        public async Task <List <string> > BatchReadFileUrl(ComputerVisionClient client, Stream imgStream)
        {
            String fullTextResultList = "";

            // Read text from URL

            var textHeaders = await client.BatchReadFileInStreamAsync(imgStream);

            // After the request, get the operation location (operation ID)
            string operationLocation = textHeaders.OperationLocation;

            const int numberOfCharsInOperationId = 36;
            string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            // Extract the text
            // Delay is between iterations and tries a maximum of 10 times.
            int i          = 0;
            int maxRetries = 10;
            ReadOperationResult results;

            do
            {
                results = await client.GetReadOperationResultAsync(operationId);

                Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                await Task.Delay(1000);

                if (i == 9)
                {
                    Console.WriteLine("Server timed out.");
                }
            }while ((results.Status == TextOperationStatusCodes.Running ||
                     results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

            var textRecognitionLocalFileResults = results.RecognitionResults;

            foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
            {
                foreach (Line line in recResult.Lines)
                {
                    fullTextResultList += line.Text + " ";
                }
            }
            var cleanResults = resultCleanUp(fullTextResultList);

            return(cleanResults);
        }
        public async Task MakePhotoAsync()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await TextToSpeech.SpeakAsync("No Camera found");

                return;
            }
            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                Directory = "Sample",
                Name      = "test.jpg"
            });

            if (file == null)
            {
                return;
            }
            List <VisualFeatureTypes> features =
                new List <VisualFeatureTypes>()
            {
                VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
                VisualFeatureTypes.Faces,
                VisualFeatureTypes.Tags
            };
            ComputerVisionClient computerVision = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(subscriptionKey),
                new System.Net.Http.DelegatingHandler[] { });

            computerVision.Endpoint = "https://francecentral.api.cognitive.microsoft.com/";
            using (Stream imageStream = File.OpenRead(file.Path))
            {
                ImageAnalysis analysis = await computerVision.AnalyzeImageInStreamAsync(
                    imageStream, features);

                ausgewerterSatz = analysis.Description.Captions[0].Text;
            }
            await TextToSpeech.SpeakAsync(ausgewerterSatz);

            ausgewerterSatz = "";
            Stream   stream     = file.GetStream();
            var      imageBytes = GetImageAsByteData(stream);
            FileInfo fil        = new FileInfo(file.Path);
            //Upload(imageBytes, fil.Name); Would Post to Vits Rest API
        }
        /*
         * END - DETECT DOMAIN-SPECIFIC CONTENT
         */

        /*
         *	EXTRACT TEXT - URL IMAGE
         */
        public static async Task ExtractTextUrl(ComputerVisionClient client, string urlImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("EXTRACT TEXT - URL IMAGE");
            Console.WriteLine();

            // Read text from URL
            BatchReadFileHeaders textHeaders = await client.BatchReadFileAsync(urlImage);

            // After the request, get the operation location (operation ID)
            string operationLocation = textHeaders.OperationLocation;

            // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
            // We only need the ID and not the full URL
            const int numberOfCharsInOperationId = 36;
            string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            // Extract the text
            // Delay is between iterations and tries a maximum of 10 times.
            int i          = 0;
            int maxRetries = 10;
            ReadOperationResult results;

            Console.WriteLine($"Extracting text from URL image {Path.GetFileName(urlImage)}...");
            Console.WriteLine();
            do
            {
                results = await client.GetReadOperationResultAsync(operationId);

                Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                await Task.Delay(1000);
            }while ((results.Status == TextOperationStatusCodes.Running ||
                     results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

            // Display the found text.
            Console.WriteLine();
            var recognitionResults = results.RecognitionResults;

            foreach (TextRecognitionResult result in recognitionResults)
            {
                foreach (Line line in result.Lines)
                {
                    Console.WriteLine(line.Text);
                }
            }
            Console.WriteLine();
        }
Пример #20
0
        // </snippet_read_url>

        /*
         * END - READ FILE - URL
         */


        // <snippet_read_local>

        /*
         * READ FILE - LOCAL
         */

        public static async Task ReadFileLocal(ComputerVisionClient client, string localFile)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("READ FILE FROM LOCAL");
            Console.WriteLine();

            // Read text from URL
            var textHeaders = await client.ReadInStreamAsync(File.OpenRead(localFile), language : "en");

            // After the request, get the operation location (operation ID)
            string operationLocation = textHeaders.OperationLocation;

            Thread.Sleep(2000);
            // </snippet_extract_call>

            // <snippet_extract_response>
            // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
            // We only need the ID and not the full URL
            const int numberOfCharsInOperationId = 36;
            string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            // Extract the text
            ReadOperationResult results;

            Console.WriteLine($"Reading text from local file {Path.GetFileName(localFile)}...");
            Console.WriteLine();
            do
            {
                results = await client.GetReadResultAsync(Guid.Parse(operationId));
            }while ((results.Status == OperationStatusCodes.Running ||
                     results.Status == OperationStatusCodes.NotStarted));
            // </snippet_extract_response>

            // <snippet_extract_display>
            // Display the found text.
            Console.WriteLine();
            var textUrlFileResults = results.AnalyzeResult.ReadResults;

            foreach (ReadResult page in textUrlFileResults)
            {
                foreach (Line line in page.Lines)
                {
                    Console.WriteLine(line.Text);
                }
            }
            Console.WriteLine();
        }
        private async Task <(bool, string)> PassesImageModerationAsync(Stream image)
        {
            var client = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(ApiKey),
                httpClient,
                false)
            {
                Endpoint = ApiRoot
            };

            var result = await client.AnalyzeImageInStreamAsync(image, VisualFeatures);

            bool   containsCat = result.Description.Tags.Take(5).Contains(SearchTag);
            string message     = result?.Description?.Captions.FirstOrDefault()?.Text;

            return(containsCat, message);
        }
Пример #22
0
        // Analyze a remote image
        private static async Task GetThumbnailFromUrlAsync(ComputerVisionClient computerVision, string imageUrl, int height, int width, string localSavePath)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                Console.WriteLine("\nInvalid remote image url:\n{0} \n", imageUrl);
                return;
            }

            Stream thumbnail = await computerVision.GenerateThumbnailAsync(width, height, imageUrl, smartCropping : true);

            Console.WriteLine(imageUrl);

            string imageName         = Path.GetFileName(imageUrl);
            string thumbnailFilePath = Path.Combine(localSavePath, imageName.Insert(imageName.Length - 4, "_thumb"));

            SaveThumbnail(thumbnail, thumbnailFilePath);
        }
Пример #23
0
        public static async Task RunAsync(string endpoint, string key)
        {
            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
            {
                Endpoint = endpoint
            };

            string    localImagePath  = @"Images\objects.jpg"; // See this repo's readme.md for info on how to get these images. Alternatively, you can just set the path to any appropriate image on your machine.
            string    remoteImageUrl  = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/faces.jpg";
            string    localSavePath   = @".";
            const int thumbnailHeight = 60;
            const int thumbnailWidth  = 60;

            Console.WriteLine("Getting thumbnails ...");
            await GetThumbnailFromUrlAsync(computerVision, remoteImageUrl, thumbnailWidth, thumbnailHeight, localSavePath);
            await GetThumbnailFromStreamAsync(computerVision, localImagePath, thumbnailWidth, thumbnailHeight, localSavePath);
        }
Пример #24
0
        public static async Task RunAsync(string endpoint, string key)
        {
            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
            {
                Endpoint = endpoint
            };

            string localImagePath = @"Images\printed_text.jpg";  // See this repo's readme.md for info on how to get these images. Alternatively, you can just set the path to any appropriate image on your machine.
            string remoteImageUrl = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/printed_text.jpg";

            //OCR works well only for printed text. Look at the ExtractText sample code for how to use the ReadOperation SDK which works well for both printed and handwritten text

            Console.WriteLine("OCR on the images");

            await OCRFromUrlAsync(computerVision, remoteImageUrl);
            await OCRFromStreamAsync(computerVision, localImagePath);
        }
Пример #25
0
        // Recognize text from a remote image
        private static async Task ExtractRemoteTextAsync(
            ComputerVisionClient computerVision, string imageUrl)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                Console.WriteLine(
                    "\nInvalid remoteImageUrl:\n{0} \n", imageUrl);
                return;
            }

            // Start the async process to recognize the text
            RecognizeTextHeaders textHeaders =
                await computerVision.RecognizeTextAsync(
                    imageUrl, textRecognitionMode);

            await GetTextAsync(computerVision, textHeaders.OperationLocation);
        }
        static void Main(string[] args)
        {
            ComputerVisionClient computerVision = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(subscriptionKey),
                new System.Net.Http.DelegatingHandler[] { });

            // Add your Computer Vision endpoint to your environment variables.
            computerVision.Endpoint = Environment.GetEnvironmentVariable("COMPUTER_VISION_SUBSCRIPTION_KEY");

            Console.WriteLine("Images being analyzed ...");
            var t1 = ExtractRemoteTextAsync(computerVision, remoteImageUrl);
            var t2 = ExtractLocalTextAsync(computerVision, localImagePath);

            Task.WhenAll(t1, t2).Wait(5000);
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
        }
Пример #27
0
        public static async Task TestComputerVisionApiKeyAsync(string key, string apiEndpoint)
        {
            bool isUri = !string.IsNullOrEmpty(apiEndpoint) ? Uri.IsWellFormedUriString(apiEndpoint, UriKind.Absolute) : false;

            if (!isUri)
            {
                throw new ArgumentException("Invalid URI");
            }
            else
            {
                ComputerVisionClient client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
                {
                    Endpoint = apiEndpoint
                };
                await client.ListModelsAsync();
            }
        }
Пример #28
0
        /*
         * END - RECOGNIZE PRINTED TEXT - URL IMAGE
         */


        /*
         * RECOGNIZE PRINTED TEXT - LOCAL IMAGE
         */
        public static async Task RecognizePrintedTextLocal(ComputerVisionClient client, string localImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("RECOGNIZE PRINTED TEXT - LOCAL IMAGE");
            Console.WriteLine();

            using (Stream stream = File.OpenRead(localImage))
            {
                Console.WriteLine($"Performing OCR on local image {Path.GetFileName(localImage)}...");
                Console.WriteLine();
                // Get the recognized text
                OcrResult localFileOcrResult = await client.RecognizePrintedTextInStreamAsync(true, stream);

                // Display text, language, angle, orientation, and regions of text from the results.
                Console.WriteLine("Text:");
                Console.WriteLine("Language: " + localFileOcrResult.Language);
                Console.WriteLine("Text Angle: " + localFileOcrResult.TextAngle);
                Console.WriteLine("Orientation: " + localFileOcrResult.Orientation);
                Console.WriteLine();
                Console.WriteLine("Text regions: ");

                // Getting only one line of text for testing purposes. To see full demonstration, remove the counter & conditional.
                int counter = 0;
                foreach (var localRegion in localFileOcrResult.Regions)
                {
                    Console.WriteLine("Region bounding box: " + localRegion.BoundingBox);
                    foreach (var line in localRegion.Lines)
                    {
                        Console.WriteLine("Line bounding box: " + line.BoundingBox);

                        if (counter == 1)
                        {
                            Console.WriteLine();
                            return;
                        }
                        counter++;

                        foreach (var word in line.Words)
                        {
                            Console.WriteLine("Word bounding box: " + word.BoundingBox);
                            Console.WriteLine("Text: " + word.Text);
                        }
                    }
                }
            }
        }
        /*
         * DETECT OBJECTS - URL IMAGE
         */
        public static async Task <DetectResult> DetectObjectsUrl(ComputerVisionClient client, string urlImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("DETECT OBJECTS - URL IMAGE");
            Console.WriteLine();

            Console.WriteLine($"Detecting objects in URL image {Path.GetFileName(urlImage)}...");
            Console.WriteLine();
            // Detect the objects
            DetectResult detectObjectAnalysis = await client.DetectObjectsAsync(urlImage);

            // For each detected object in the picture, print out the bounding object detected, confidence of that detection and bounding box within the image
            Console.WriteLine("Detected objects:");
            Console.WriteLine();

            return(detectObjectAnalysis);
        }
Пример #30
0
        static void Main(string[] args)
        {
            ComputerVisionClient computerVision = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(subscriptionKey),
                new System.Net.Http.DelegatingHandler[] { });

            // Add your Computer Vision endpoint to your environment variables.
            computerVision.Endpoint = "https://southeastasia.api.cognitive.microsoft.com/";

            Console.WriteLine("Images being analyzed ...");
            var t1 = AnalyzeRemoteAsync(computerVision, remoteImageUrl);
            var t2 = AnalyzeLocalAsync(computerVision, localImagePath);

            Task.WhenAll(t1, t2).Wait(5000);
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
        }