Esempio n. 1
0
        // Recognize text from a local image
        private static async Task ExtractLocalTextAsync(
            ComputerVisionClient computerVision, string imagePath)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine(
                    "\nUnable to open or read localImagePath:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                // Start the async process to recognize the text
                BatchReadFileInStreamHeaders textHeaders =
                    await computerVision.BatchReadFileInStreamAsync(
                        imageStream);

                await GetTextAsync(computerVision, textHeaders.OperationLocation);
            }
        }
        private static async Task <string> GetTextFromImage(Stream imageStream, ILogger logger)
        {
            string cognitiveServiceApiKey   = GetEnvVarValue(COGNITIVESERVICE_KEY);
            string cognitiveServiceEndpoint = GetEnvVarValue(COGNITIVESERVICE_ENDPOINT);

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

            computerVisionClient.Endpoint = cognitiveServiceEndpoint;

            // Start the async process to recognize the text
            BatchReadFileInStreamHeaders textHeaders =
                await computerVisionClient.BatchReadFileInStreamAsync(imageStream);

            var t = GetTextAsync(computerVisionClient, textHeaders.OperationLocation);

            t.Wait();
            return(t.Result);
        }
Esempio n. 3
0
                        public async Task ExtractText(string data, bool flag)
                        {
                            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { });

                            //Endpoint
                            computerVision.Endpoint = Endpoint;

                            if (flag)
                            {
                                if (!Uri.IsWellFormedUriString(data, UriKind.Absolute))
                                {
                                    Error = "Invalid remoteImageUrl: " + data;
                                }

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

                                await GetTextAsync(computerVision, textHeaders.OperationLocation);
                            }
                            else
                            {
                                //Image data to Byte Array
                                byte[] imageBytes = Convert.FromBase64String(data);

                                //Byte Array To Stream
                                Stream stream = new MemoryStream(imageBytes);

                                try
                                {
                                    //Starting the async process to recognize the text
                                    BatchReadFileInStreamHeaders textHeaders = await computerVision.BatchReadFileInStreamAsync(stream, textRecognitionMode);

                                    await GetTextAsync(computerVision, textHeaders.OperationLocation);
                                }
                                catch (Exception e)
                                {
                                    Error = e.Message;
                                }
                            }
                        }
Esempio n. 4
0
        private String BatchReadFileLocal(ComputerVisionClient client, String localImage)
        {
            StringBuilder stringBuilder = new StringBuilder();
            const Int32   numberOfCharsInOperationId = 36;

            using (Stream imageStream = System.IO.File.OpenRead(localImage))
            {
                BatchReadFileInStreamHeaders localFileTextHeaders = client.BatchReadFileInStreamAsync(imageStream).Result;
                string operationLocation = localFileTextHeaders.OperationLocation;

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

                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = client.GetReadOperationResultAsync(operationId).Result;
                    Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                    Task.Delay(1000);
                    if (i == 9)
                    {
                        return(String.Empty);
                    }
                }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)
                    {
                        stringBuilder.Append(line.Text);
                    }
                }
            }

            return(stringBuilder.ToString());
        }
Esempio n. 5
0
        public static async Task <IList <TextRecognitionResult> > GetTextAsync(Stream imageToAnalyze)
        {
            BatchReadFileInStreamHeaders textHeaders = await _computerVisionClient.BatchReadFileInStreamAsync(imageToAnalyze);

            string operationLocation = textHeaders.OperationLocation;
            string operationId       = operationLocation.Substring(operationLocation.Length - NumberOfCharsInOperationId);

            ReadOperationResult result = await _computerVisionClient.GetReadOperationResultAsync(operationId);

            int i          = 0;
            int maxRetries = 10;

            while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries)
            {
                await Task.Delay(1000);

                result = await _computerVisionClient.GetReadOperationResultAsync(operationId);
            }

            IList <TextRecognitionResult> recResults = result.RecognitionResults;

            return(recResults);
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            string endpoint = "https://westeurope.api.cognitive.microsoft.com/";
            string key      = "c50bac85176f4da384d8e2d06bf17d41";

            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new ComputerVisionClient(credentials);

            client.Endpoint = endpoint;

            //Detección de objetos

            var files = Directory.GetFiles(Environment.CurrentDirectory, "*.jpg");

            if (!files.Any())
            {
                System.Console.WriteLine("No hay imágenes");
                return;
            }

            var features = new List <VisualFeatureTypes>();

            features.Add(VisualFeatureTypes.Objects);
            features.Add(VisualFeatureTypes.Description);
            features.Add(VisualFeatureTypes.Tags);

            foreach (var file in files)
            {
                using (Stream stream = File.OpenRead(file)){
                    var analysis = client.AnalyzeImageInStreamAsync(stream, features).Result;

                    System.Console.WriteLine($"Archivo: {file}");
                    System.Console.WriteLine(analysis.Description?.Captions?.FirstOrDefault().Text);
                    System.Console.WriteLine(analysis.Objects?.FirstOrDefault()?.ObjectProperty);
                    System.Console.WriteLine();
                    System.Console.WriteLine();
                }
            }

            //Detección de texto

            files = Directory.GetFiles(Environment.CurrentDirectory, "texto*.jpg");

            foreach (var file in files)
            {
                using (Stream stream = File.OpenRead(file))
                {
                    var analysis = client.BatchReadFileInStreamAsync(stream, TextRecognitionMode.Printed).Result;

                    string operationId = analysis.OperationLocation.Substring(analysis.OperationLocation.Length - 36);

                    var result = client.GetReadOperationResultAsync(operationId).Result;

                    while (result.Status == TextOperationStatusCodes.Running ||
                           result.Status == TextOperationStatusCodes.NotStarted)
                    {
                        System.Console.WriteLine("Esperando...");
                        Task.Delay(1000).Wait();

                        result = client.GetReadOperationResultAsync(operationId).Result;
                    }


                    if (result.RecognitionResults == null)
                    {
                        continue;
                    }

                    foreach (var recognition in result.RecognitionResults)
                    {
                        foreach (var line in recognition?.Lines)
                        {
                            System.Console.WriteLine(line.Text);
                        }
                    }
                }
            }
        }