예제 #1
0
        /// <summary>
        /// Sends a URL to Cognitive Services and generates a thumbnail.
        /// </summary>
        /// <param name="imageUrl">The URL of the image for which to generate a thumbnail.</param>
        /// <param name="width">Width of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.</param>
        /// <param name="height">Height of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.</param>
        /// <param name="smartCropping">Boolean flag for enabling smart cropping.</param>
        /// <returns>Awaitable stream containing the image thumbnail.</returns>
        private async Task <Stream> ThumbnailUrlAsync(string imageUrl, int width, int height, bool smartCropping)
        {
            // -----------------------------------------------------------------------
            // KEY SAMPLE CODE STARTS HERE
            // -----------------------------------------------------------------------

            //
            // Create Cognitive Services Vision API Service client.
            //
            using (var client = new ComputerVisionClient(Credentials)
            {
                Endpoint = Endpoint
            })
            {
                Log("ComputerVisionClient is created");

                //
                // Generate a thumbnail for the given URL.
                //
                Log("Calling ComputerVisionClient.GenerateThumbnailAsync()...");
                return(await client.GenerateThumbnailAsync(width, height, imageUrl, smartCropping));
            }

            // -----------------------------------------------------------------------
            // KEY SAMPLE CODE ENDS HERE
            // -----------------------------------------------------------------------
        }
예제 #2
0
        public async Task <Stream> GenerateThumbnailUrl(string imageUrl)
        {
            ComputerVisionClient client = await GetClient();

            Stream thumbnailUrl = await client.GenerateThumbnailAsync(60, 60, imageUrl, true);

            return(thumbnailUrl);
        }
예제 #3
0
        /// <summary>
        /// Sends a url to Project Oxford and generates a thumbnail
        /// </summary>
        /// <param name="imageUrl">The url of the image to generate a thumbnail for</param>
        /// <param name="width">Width of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.</param>
        /// <param name="height">Height of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.</param>
        /// <param name="smartCropping">Boolean flag for enabling smart cropping.</param>
        /// <returns></returns>
        private async Task <Stream> ThumbnailUrl(string imageUrl, int width, int height, bool smartCropping)
        {
            //
            // Generate a thumbnail for the given url
            //
            Log("Calling VisionServiceClient.GetThumbnailAsync()...");
            var thumbnail = await VisionServiceClient.GenerateThumbnailAsync(width, height, imageUrl, smartCropping);

            return(thumbnail);

            // -----------------------------------------------------------------------
            // KEY SAMPLE CODE ENDS HERE
            // -----------------------------------------------------------------------
        }
예제 #4
0
        public static async Task <string> GenerateThumbnail([ActivityTrigger] string name, ILogger log)
        {
            log.LogInformation($"Generating thumbnail for {name}.");
            var thumbnailBlob = await GetImageFromContainer("thumbnails", name);

            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("CognitiveApiKey")), new System.Net.Http.DelegatingHandler[] { });

            computerVision.Endpoint = Environment.GetEnvironmentVariable("CognitiveApiUrl");

            var thumbnailStream = await computerVision.GenerateThumbnailAsync(200, 200, await GetBlobAccessUrl("processed", name, TimeSpan.FromSeconds(60)), true);

            await thumbnailBlob.UploadFromStreamAsync(thumbnailStream);

            return(thumbnailBlob.Uri.ToString());
        }
        private static async Task GetRemoteThumbnailAsync(ComputerVisionClient computerVision, string imageUrl)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                Console.WriteLine("\nInvalid image:\n{0} \n", imageUrl);
                return;
            }
            Stream thumbnail = await computerVision.GenerateThumbnailAsync(thumbnailWidth, thumbnailHeight, imageUrl, false);

            string path              = localImagePath.Substring(0, localImagePath.LastIndexOf('\\'));
            string imageName         = imageUrl.Substring(imageUrl.LastIndexOf('/') + 1);
            string thumbnailFilePath = path + "\\" + imageName.Insert(imageName.Length - 4, "_thumb");

            SaveThumbnail(thumbnail, thumbnailFilePath);
        }
예제 #6
0
        private static async Task GetRemoteThumbnailTask(ComputerVisionClient computerVision, string imageUrl, int Width, int Height, bool storeToDisk)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                return;
            }
            Stream thumbnail = await computerVision.GenerateThumbnailAsync(
                Width, Height, imageUrl, true);

            string path              = Environment.CurrentDirectory;
            string imageName         = imageUrl.Substring(imageUrl.LastIndexOf('/') + 1);
            string thumbnailFilePath =
                path + "\\" + imageName.Insert(imageName.Length - 4, "_thumb");

            Save(thumbnail, thumbnailFilePath, storeToDisk);
        }
예제 #7
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);
        }
예제 #8
0
    public async Task Run(string url)
    {
        var result = await vision.AnalyzeImageAsync(url, features);

        // Record the image description and tags in blob metadata
        Metadata.Add("Caption", result.Description.Captions[0].Text);
        Description = result.Description.Captions[0].Text;

        for (int i = 0; i < result.Description.Tags.Count; i++)
        {
            string key = String.Format("Tag{0}", i);
            Metadata.Add(key, result.Description.Tags[i]);
        }

        // generate thumbnail
        ThumbnailStream = await vision.GenerateThumbnailAsync(200, 200, url, true);
    }
        /*
         * GENERATE THUMBNAIL
         * Taking in a URL and local image, this example will generate a thumbnail image with specified width/height (pixels).
         * The thumbnail will be saved locally.
         */
        public static async Task GenerateThumbnail(ComputerVisionClient client, string urlImage, string localImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("GENERATE THUMBNAIL - URL & LOCAL IMAGE");
            Console.WriteLine();

            // Thumbnails will be saved locally in your bin\Debug\netcoreappx.x\ folder of this project.
            string localSavePath = @".";

            // URL
            Console.WriteLine("Generating thumbnail with URL image...");
            // Setting smartCropping to true enables the image to adjust its aspect ratio
            // to center on the area of interest in the image. Change the width/height, if desired.
            Stream thumbnailUrl = await client.GenerateThumbnailAsync(60, 60, urlImage, true);

            string imageNameUrl         = Path.GetFileName(urlImage);
            string thumbnailFilePathUrl = Path.Combine(localSavePath, imageNameUrl.Insert(imageNameUrl.Length - 4, "_thumb"));


            Console.WriteLine("Saving thumbnail from URL image to " + thumbnailFilePathUrl);
            using (Stream file = File.Create(thumbnailFilePathUrl)) { thumbnailUrl.CopyTo(file); }

            Console.WriteLine();

            // LOCAL
            Console.WriteLine("Generating thumbnail with local image...");

            using (Stream imageStream = File.OpenRead(localImage))
            {
                Stream thumbnailLocal = await client.GenerateThumbnailInStreamAsync(100, 100, imageStream, smartCropping : true);

                string imageNameLocal         = Path.GetFileName(localImage);
                string thumbnailFilePathLocal = Path.Combine(localSavePath,
                                                             imageNameLocal.Insert(imageNameLocal.Length - 4, "_thumb"));
                // Save to file
                Console.WriteLine("Saving thumbnail from local image to " + thumbnailFilePathLocal);
                using (Stream file = File.Create(thumbnailFilePathLocal)) { thumbnailLocal.CopyTo(file); }
            }
            Console.WriteLine();
        }
예제 #10
0
        // Create a thumbnail from a remote image
        private static async Task GetRemoteThumbnailAsync(
            ComputerVisionClient computerVision, string imageUrl)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                Console.WriteLine(
                    "\nInvalid remoteImageUrl:\n{0} \n", imageUrl);
                return;
            }

            Stream thumbnail = await computerVision.GenerateThumbnailAsync(
                thumbnailWidth, thumbnailHeight, imageUrl, true);

            string path              = Environment.CurrentDirectory;
            string imageName         = imageUrl.Substring(imageUrl.LastIndexOf('/') + 1);
            string thumbnailFilePath =
                path + "\\" + imageName.Insert(imageName.Length - 4, "_thumb");

            // Save the thumbnail to the current working directory,
            // using the original name with the suffix "_thumb".
            SaveThumbnail(thumbnail, thumbnailFilePath);
        }
예제 #11
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
        {
            #region Preparation
            var imageUrl = req.Query["imageUrl"];

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var visionEndpoint        = config["visionEndpoint"];
            var visionSubscriptionKey = config["visionSubscriptionKey"];

            #endregion

            ComputerVisionClient computerVision = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(visionSubscriptionKey), new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = visionEndpoint
            };

            Stream thumbnail = await computerVision.GenerateThumbnailAsync(
                500, 500, imageUrl, true);

            #region Output
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = thumbnail.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return(new FileContentResult(ms.ToArray(), "image/jpeg"));
            }
            #endregion
        }
        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}");
                }
            }
        }