Tutorial de pistas de recorte

Audiencia

El objetivo de este tutorial es ayudarte a desarrollar aplicaciones con la función Sugerencias de recorte de la API Vision. Se da por supuesto que conoces las estructuras y las técnicas de programación básicas. Sin embargo, aunque seas un programador principiante, deberías poder seguir este tutorial y ejecutarlo sin dificultad, y luego usar la documentación de referencia de la API Vision para crear aplicaciones básicas.

En este tutorial se explica paso a paso una aplicación de la API Vision y se muestra cómo hacer una llamada a la API Vision para usar su función Sugerencias de recorte.

Requisitos previos

Información general

En este tutorial se explica cómo crear una aplicación básica de la API Vision que usa una Crop Hints solicitud. Puedes proporcionar la imagen que se va a procesar mediante un URI de Cloud Storage (ubicación del segmento de Cloud Storage) o insertándola en la solicitud. Una Crop Hints respuesta correcta devuelve las coordenadas de un cuadro delimitador recortado alrededor del objeto o la cara dominantes de la imagen.

Listado de código

Mientras lees el código, te recomendamos que consultes la referencia de Python de la API Cloud Vision.

import argparse

from typing import MutableSequence

from google.cloud import vision
from PIL import Image, ImageDraw



def get_crop_hint(path: str) -> MutableSequence[vision.Vertex]:
    """Detect crop hints on a single image and return the first result.

    Args:
        path: path to the image file.

    Returns:
        The vertices for the bounding polygon.
    """
    client = vision.ImageAnnotatorClient()

    with open(path, "rb") as image_file:
        content = image_file.read()

    image = vision.Image(content=content)

    crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.77])
    image_context = vision.ImageContext(crop_hints_params=crop_hints_params)

    response = client.crop_hints(image=image, image_context=image_context)
    hints = response.crop_hints_annotation.crop_hints

    # Get bounds for the first crop hint using an aspect ratio of 1.77.
    vertices = hints[0].bounding_poly.vertices

    return vertices


def draw_hint(image_file: str) -> None:
    """Draw a border around the image using the hints in the vector list.

    Args:
        image_file: path to the image file.
    """
    vects = get_crop_hint(image_file)

    im = Image.open(image_file)
    draw = ImageDraw.Draw(im)
    draw.polygon(
        [
            vects[0].x,
            vects[0].y,
            vects[1].x,
            vects[1].y,
            vects[2].x,
            vects[2].y,
            vects[3].x,
            vects[3].y,
        ],
        None,
        "red",
    )
    im.save("output-hint.jpg", "JPEG")
    print("Saved new image to output-hint.jpg")


def crop_to_hint(image_file: str) -> None:
    """Crop the image using the hints in the vector list.

    Args:
        image_file: path to the image file.
    """
    vects = get_crop_hint(image_file)

    im = Image.open(image_file)
    im2 = im.crop([vects[0].x, vects[0].y, vects[2].x - 1, vects[2].y - 1])
    im2.save("output-crop.jpg", "JPEG")
    print("Saved new image to output-crop.jpg")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("image_file", help="The image you'd like to crop.")
    parser.add_argument("mode", help='Set to "crop" or "draw".')
    args = parser.parse_args()

    if args.mode == "crop":
        crop_to_hint(args.image_file)
    elif args.mode == "draw":
        draw_hint(args.image_file)

Una mirada en profundidad

Importar bibliotecas

import argparse

from typing import MutableSequence

from google.cloud import vision
from PIL import Image, ImageDraw

Importamos bibliotecas estándar: