Detectar propiedades de imagen en un archivo de Cloud Storage

Realiza la detección de propiedades de imágenes en un archivo almacenado en Cloud Storage.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

Go

Antes de probar este código de muestra, sigue las instrucciones de configuración para Go que se encuentran en la Guía de inicio rápido de Vision sobre cómo usar las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Vision para Go.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


// detectProperties gets image properties from the Vision API for an image at the given file path.
func detectPropertiesURI(w io.Writer, file string) error {
	ctx := context.Background()

	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return err
	}

	image := vision.NewImageFromURI(file)
	props, err := client.DetectImageProperties(ctx, image, nil)
	if err != nil {
		return err
	}

	fmt.Fprintln(w, "Dominant colors:")
	for _, quantized := range props.DominantColors.Colors {
		color := quantized.Color
		r := int(color.Red) & 0xff
		g := int(color.Green) & 0xff
		b := int(color.Blue) & 0xff
		fmt.Fprintf(w, "%2.1f%% - #%02x%02x%02x\n", quantized.PixelFraction*100, r, g, b)
	}

	return nil
}

Java

Antes de probar este código de muestra, sigue las instrucciones de configuración para Java que se encuentran en la Guía de inicio rápido de Vision sobre cómo usar las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Vision para Java.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.ColorInfo;
import com.google.cloud.vision.v1.DominantColorsAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DetectPropertiesGcs {

  public static void detectPropertiesGcs() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg";
    detectPropertiesGcs(filePath);
  }

  // Detects image properties such as color frequency from the specified remote image on Google
  // Cloud Storage.
  public static void detectPropertiesGcs(String gcsPath) throws IOException {
    List<AnnotateImageRequest> requests = new ArrayList<>();

    ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature feat = Feature.newBuilder().setType(Feature.Type.IMAGE_PROPERTIES).build();
    AnnotateImageRequest request =
        AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
    requests.add(request);

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
      BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
      List<AnnotateImageResponse> responses = response.getResponsesList();

      for (AnnotateImageResponse res : responses) {
        if (res.hasError()) {
          System.out.format("Error: %s%n", res.getError().getMessage());
          return;
        }

        // For full list of available annotations, see http://g.co/cloud/vision/docs
        DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors();
        for (ColorInfo color : colors.getColorsList()) {
          System.out.format(
              "fraction: %f%nr: %f, g: %f, b: %f%n",
              color.getPixelFraction(),
              color.getColor().getRed(),
              color.getColor().getGreen(),
              color.getColor().getBlue());
        }
      }
    }
  }
}

Node.js

Antes de probar este código de muestra, sigue las instrucciones de configuración para Node.js que se encuentran en la Guía de inicio rápido de Vision sobre cómo usar las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Vision para Node.js.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Imports the Google Cloud client libraries
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ImageAnnotatorClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Bucket where the file resides, e.g. my-bucket';
// const fileName = 'Path to file within bucket, e.g. path/to/image.png';

// Performs property detection on the gcs file
const [result] = await client.imageProperties(
  `gs://${bucketName}/${fileName}`
);
const colors = result.imagePropertiesAnnotation.dominantColors.colors;
colors.forEach(color => console.log(color));

PHP

Antes de probar este código de muestra, sigue las instrucciones de configuración para PHP que se encuentran en la Guía de inicio rápido de Vision sobre cómo usar las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Vision para PHP.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ImageAnnotatorClient;

/**
 * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg"
 */
function detect_image_property_gcs(string $path)
{
    $imageAnnotator = new ImageAnnotatorClient();

    # annotate the image
    $response = $imageAnnotator->imagePropertiesDetection($path);
    $props = $response->getImagePropertiesAnnotation();

    if ($props) {
        print('Properties:' . PHP_EOL);
        foreach ($props->getDominantColors()->getColors() as $colorInfo) {
            printf('Fraction: %s' . PHP_EOL, $colorInfo->getPixelFraction());
            $color = $colorInfo->getColor();
            printf('Red: %s' . PHP_EOL, $color->getRed());
            printf('Green: %s' . PHP_EOL, $color->getGreen());
            printf('Blue: %s' . PHP_EOL, $color->getBlue());
            print(PHP_EOL);
        }
    } else {
        print('No Results.' . PHP_EOL);
    }

    $imageAnnotator->close();
}

Python

Antes de probar este código de muestra, sigue las instrucciones de configuración para Python que se encuentran en la Guía de inicio rápido de Vision sobre cómo usar las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Vision para Python.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

def detect_properties_uri(uri):
    """Detects image properties in the file located in Google Cloud Storage or
    on the Web."""
    from google.cloud import vision

    client = vision.ImageAnnotatorClient()
    image = vision.Image()
    image.source.image_uri = uri

    response = client.image_properties(image=image)
    props = response.image_properties_annotation
    print("Properties:")

    for color in props.dominant_colors.colors:
        print(f"frac: {color.pixel_fraction}")
        print(f"\tr: {color.color.red}")
        print(f"\tg: {color.color.green}")
        print(f"\tb: {color.color.blue}")
        print(f"\ta: {color.color.alpha}")

    if response.error.message:
        raise Exception(
            "{}\nFor more info on error messages, check: "
            "https://cloud.google.com/apis/design/errors".format(response.error.message)
        )

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.