Tutorial petunjuk pangkas

Audience

Tujuan tutorial ini adalah untuk membantu Anda mengembangkan aplikasi menggunakan fitur Petunjuk Crop Vision API. Hal ini mengasumsikan bahwa Anda sudah terbiasa dengan konstruksi dan teknik pemrograman dasar. Namun, meskipun Anda adalah programmer pemula, Anda dapat mengikuti dan menjalankan tutorial ini dengan mudah. Setelah itu, gunakan dokumentasi referensi Vision API untuk membuat aplikasi dasar.

Tutorial ini menjelaskan tentang aplikasi Vision API, yang menunjukkan cara melakukan panggilan ke Vision API untuk menggunakan fitur Petunjuk Crop-nya.

Prasyarat

Ringkasan

Tutorial ini membahas aplikasi Vision API dasar yang menggunakan permintaan Crop Hints. Anda dapat memberikan image untuk diproses melalui URI Cloud Storage (lokasi bucket Cloud Storage) atau disematkan dalam permintaan. Respons Crop Hints yang berhasil akan menampilkan koordinat untuk kotak pembatas yang dipangkas di sekitar objek atau wajah yang dominan dalam gambar.

Daftar kode

Saat membaca kode, sebaiknya Anda mengikuti dengan melihat referensi Python Cloud Vision API Python.

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)

Jelajahi lebih lanjut

Mengimpor library

import argparse

from typing import MutableSequence

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

Kami mengimpor library standar:

  • argparse untuk mengizinkan aplikasi menerima nama file input sebagai argumen
  • io untuk file I/O

Impor lainnya:

  • Class ImageAnnotatorClient dalam library google.cloud.vision untuk mengakses Vision API.
  • Modul types dalam library google.cloud.vision untuk membuat permintaan
  • Modul Image dan ImageDraw dari Python Imaging Library (PIL). untuk menggambar kotak batas pada gambar input.

Menjalankan aplikasi

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)

Di sini, kita hanya mengurai argumen yang diteruskan yang menentukan nama file gambar lokal, dan meneruskannya ke fungsi untuk memangkas gambar atau menggambar petunjuk.

Mengautentikasi ke API

Sebelum berkomunikasi dengan layanan Vision API, Anda harus mengautentikasi layanan Anda menggunakan kredensial yang diperoleh sebelumnya. Dalam aplikasi, cara termudah untuk mendapatkan kredensial adalah dengan menggunakan Kredensial Default Aplikasi (ADC). Secara default, library klien akan mencoba mendapatkan kredensial dari variabel lingkungan GOOGLE_APPLICATION_CREDENTIALS, yang harus ditetapkan agar mengarah ke file kunci JSON akun layanan Anda (lihat Siapkan Akun Layanan untuk mengetahui informasi selengkapnya.)

Mendapatkan anotasi petunjuk pemangkasan untuk gambar

Setelah library klien Vision diautentikasi, kita dapat mengakses layanan dengan memanggil metode crop_hints dari instance ImageAnnotatorClient. Rasio aspek untuk output ditentukan dalam objek ImageContext; jika beberapa rasio aspek diteruskan, beberapa petunjuk crop akan ditampilkan, satu untuk setiap rasio aspek.

"""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

Library klien melakukan enkapsulasi detail permintaan dan respons ke API. Lihat Reference Vision API untuk mengetahui informasi lengkap tentang struktur permintaan.

Menggunakan respons untuk memangkas atau menggambar kotak pembatas petunjuk

Setelah operasi berhasil diselesaikan, respons API akan berisi koordinat kotak pembatas dari satu atau beberapa cropHint. Metode draw_hint menggambar garis di sekitar kotak pembatas CropHints, lalu menulis gambar ke output-hint.jpg.

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")

Metode crop_to_hint akan memangkas gambar menggunakan petunjuk pemangkasan yang disarankan.

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")

Menjalankan aplikasi

Untuk menjalankan aplikasi, Anda dapat mendownload file cat.jpg ini (Anda mungkin perlu mengklik kanan link), lalu meneruskan lokasi tempat Anda mendownload di komputer lokal Anda ke aplikasi tutorial (crop_hints.py).

Berikut adalah perintah Python, diikuti dengan output konsol, yang menampilkan respons cropHintsAnnotation JSON. Respons ini menyertakan koordinat kotak pembatas cropHints. Kami meminta area pemangkasan dengan rasio aspek lebar-tinggi 1,77, dan koordinat x,y kiri atas, kanan bawah, untuk kotak pangkas yang ditampilkan adalah 0,336, 1100,967 singkat ini.

python crop_hints.py cat.jpeg crop
{
 "responses": [
  {
   "cropHintsAnnotation": {
    "cropHints": [
     {
      "boundingPoly": {
       "vertices": [
        {
         "y": 336
        },
        {
         "x": 1100,
         "y": 336
        },
        {
         "x": 1100,
         "y": 967
        },
        {
         "y": 967
        }
       ]
      },
      "confidence": 0.79999995,
      "importanceFraction": 0.69
     }
    ]
   }
  }
 ]
}

Dan berikut adalah gambar yang dipangkas.

Selamat! Anda telah menjalankan Cloud Vision Crop Hints API untuk menampilkan koordinat kotak pembatas yang dioptimalkan di sekitar objek dominan yang terdeteksi dalam gambar.