Пример #1
0
        /*
         * END - GENERATE THUMBNAIL
         */

        // <snippet_extract_call>

        /*
         * BATCH READ FILE - URL IMAGE
         * Recognizes handwritten text.
         * This API call offers an improvement of results over the Recognize Text calls.
         */
        public static async Task BatchReadFileUrl(ComputerVisionClient client, string urlImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("BATCH READ FILE - URL IMAGE");
            Console.WriteLine();

            // Read text from URL
            var textHeaders = await client.ReadAsync(urlImage, language : "en");

            // After the request, get the operation location (operation ID)
            string operationLocation = textHeaders.OperationLocation;
            // </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
            // 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.GetReadResultAsync(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);
            // </snippet_extract_response>

            // <snippet_extract_display>
            // Display the found text.
            Console.WriteLine();
            var textRecognitionLocalFileResults = results.RecognitionResults;

            foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
            {
                foreach (Line line in recResult.Lines)
                {
                    Console.WriteLine(line.Text);
                }
            }
            Console.WriteLine();
        }
Пример #2
0
        /*
         * END - GENERATE THUMBNAIL
         */

        // <snippet_read_url>
        // <snippet_readfileurl_1>

        /*
         * READ FILE - URL
         * Extracts text.
         */
        public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("READ FILE FROM URL");
            Console.WriteLine();

            // Read text from URL
            var textHeaders = await client.ReadAsync(urlFile, language : "en");

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

            Thread.Sleep(2000);

            // </snippet_readfileurl_1>
            // <snippet_readfileurl_2>
            // <snippet_read_response>
            // Retrieve the URI where the extracted 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($"Extracting text from URL file {Path.GetFileName(urlFile)}...");
            Console.WriteLine();
            do
            {
                results = await client.GetReadResultAsync(Guid.Parse(operationId));
            }while ((results.Status == OperationStatusCodes.Running ||
                     results.Status == OperationStatusCodes.NotStarted));
            // </snippet_readfileurl_2>
            // </snippet_read_response>

            // <snippet_read_display>
            // <snippet_readfileurl_3>
            // 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);
                }
            }
            // </snippet_read_display>
            Console.WriteLine();
        }
        /*
         * READ FILE - URL
         * Extracts text.
         */
        public static async Task <ReadOperationResult> ReadFileUrl(ComputerVisionClient client, string urlFile)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("READ FILE FROM URL");
            Console.WriteLine();

            // Read text from URL
            var textHeaders = await client.ReadAsync(urlFile, language : "en");

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

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

            // <snippet_read_response>
            // Retrieve the URI where the extracted 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);

            return(await GetReadOperationResult(client, operationId));
        }
        static async Task Main(string[] args)
        {
            const string SUBSCRIPTION_KEY = "PONER AQUI LA CLAVE";
            const string ENDPOINT         = "PONER AQUI LA URL DEL ENDPOINT";
            const string IMAGE_BASE_URL   = "https://moderatorsampleimages.blob.core.windows.net/samples";

            ComputerVisionClient client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(SUBSCRIPTION_KEY))
            {
                Endpoint = ENDPOINT
            };

            /////////////////////////
            //Análisis de imagen (ComputerVision-Analyze Image)
            /////////////////////////
            Console.WriteLine("---Análisis de imagen---");

            //Definimos la lista de características y detalles que queremos obtener de la imagen
            List <VisualFeatureTypes?> caracteristicas = new List <VisualFeatureTypes?>()
            {
                VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
                VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,
                VisualFeatureTypes.Objects
            };

            List <Details?> detalles = new List <Details?>()
            {
                Details.Celebrities
            };

            //Invocamos el método de la API para el análisis de la imagen
            ImageAnalysis resultado = await client.AnalyzeImageAsync(
                url : $"{IMAGE_BASE_URL}/sample1.jpg",
                visualFeatures : caracteristicas,
                details : detalles,
                language : "es"
                );

            //Procesamos el resultado
            //Descripción
            Console.WriteLine($"Descripción:{resultado.Description.Captions[0].Text}");

            //Categorías
            Console.WriteLine("Categorías:");
            foreach (Category categoria in resultado.Categories)
            {
                Console.WriteLine($"\t{categoria.Name} ({categoria.Score})");
            }
            ;

            //Etiquetas
            Console.WriteLine("Etiquetas:");
            foreach (ImageTag etiqueta in resultado.Tags)
            {
                Console.WriteLine($"\t{etiqueta.Name} ({etiqueta.Confidence})");
            }
            ;

            //Contenido para adultos
            Console.WriteLine($"¿Contenido para adultos? {resultado.Adult.IsAdultContent}");
            Console.WriteLine($"¿Contenido subido de tono? {resultado.Adult.IsRacyContent}");
            Console.WriteLine($"¿Contenido sangriento? {resultado.Adult.IsGoryContent}");

            //Objetos encontrados
            Console.WriteLine("Objetos:");
            foreach (DetectedObject objeto in resultado.Objects)
            {
                Console.WriteLine($"\t{objeto.ObjectProperty} ({objeto.Rectangle.W},{objeto.Rectangle.H},{objeto.Rectangle.X},{objeto.Rectangle.Y})");
            }
            ;

            //Famosos
            Console.WriteLine("Famosos:");
            foreach (Category categoria in resultado.Categories)
            {
                if (categoria.Detail?.Celebrities != null)
                {
                    foreach (CelebritiesModel famoso in categoria.Detail.Celebrities)
                    {
                        Console.WriteLine($"\t{famoso.Name}");
                    }
                }
            }

            /////////////////////////
            //Obtención de miniatura (ComputerVision-Get Thumbnail)
            /////////////////////////
            Console.WriteLine("---Obtención de miniatura---");

            //Invocamos el método de la API para obtener la miniatura
            Stream miniatura = await client.GenerateThumbnailAsync(100, 100, $"{IMAGE_BASE_URL}/sample6.png", true);

            //Almacenamos el stream del resultado en un fichero local
            using (Stream file = File.Create("./miniatura.jpg")) { miniatura.CopyTo(file); }
            Console.WriteLine($"Generado el fichero miniatura.jpg");

            /////////////////////////
            //OCR (ComputerVision-Read)
            /////////////////////////
            Console.WriteLine("---OCR---");

            //Invocamos el método de la API para solicitar la operación de lectura
            ReadHeaders operacionOCR = await client.ReadAsync($"{IMAGE_BASE_URL}/sample2.jpg", language : "es");

            //Obtenemos el identificador de la operaciónd e lectura
            string localizador = operacionOCR.OperationLocation;
            string idOperacion = localizador.Substring(localizador.Length - 36);

            //Esperamos a que la operación de lectura acabe
            ReadOperationResult resultadoOCR;

            while (true)
            {
                await Task.Delay(1000);

                resultadoOCR = await client.GetReadResultAsync(Guid.Parse(idOperacion));

                if (resultadoOCR.Status == OperationStatusCodes.Succeeded)
                {
                    break;
                }
            }

            //Procesamos el resultado
            Console.WriteLine("Texto encontrado:");
            foreach (ReadResult pagina in resultadoOCR.AnalyzeResult.ReadResults)
            {
                foreach (Line linea in pagina.Lines)
                {
                    Console.WriteLine($"\t{linea.Text}");
                }
            }
        }
        private async Task <ReadOperationResult> ComputerVisionReadByUrlAsync(string imageUrl, ReadLanguage readLanguage)
        {
            var readRequestHeaders = await _computerVisionClient.ReadAsync(imageUrl, language : readLanguage.ToString());

            return(await GetReadOperationResultAsync(readRequestHeaders.OperationLocation));
        }