Web detection

Perform web detection on a file, URL, or Cloud Storage URI.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


Before trying this sample, follow the Python setup instructions in the Vision quickstart using client libraries. For more information, see the Vision Python API reference documentation.

To authenticate to Vision, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import argparse

from google.cloud import vision

def annotate(path: str) -> vision.WebDetection:
    """Returns web annotations given the path to an image.

        path: path to the input image.

        An WebDetection object with relevant information of the
        image from the internet (i.e., the annotations).
    client = vision.ImageAnnotatorClient()

    if path.startswith("http") or path.startswith("gs:"):
        image = vision.Image()
        image.source.image_uri = path

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

        image = vision.Image(content=content)

    web_detection = client.web_detection(image=image).web_detection

    return web_detection

def report(annotations: vision.WebDetection) -> None:
    """Prints detected features in the provided web annotations.

        annotations: The web annotations (WebDetection object) from which
        the features should be parsed and printed.
    if annotations.pages_with_matching_images:
            f"\n{len(annotations.pages_with_matching_images)} Pages with matching images retrieved"

        for page in annotations.pages_with_matching_images:
            print(f"Url   : {page.url}")

    if annotations.full_matching_images:
        print(f"\n{len(annotations.full_matching_images)} Full Matches found: ")

        for image in annotations.full_matching_images:
            print(f"Url  : {image.url}")

    if annotations.partial_matching_images:
        print(f"\n{len(annotations.partial_matching_images)} Partial Matches found: ")

        for image in annotations.partial_matching_images:
            print(f"Url  : {image.url}")

    if annotations.web_entities:
        print(f"\n{len(annotations.web_entities)} Web entities found: ")

        for entity in annotations.web_entities:
            print(f"Score      : {entity.score}")
            print(f"Description: {entity.description}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
    path_help = str(
        "The image to detect, can be web URI, "
        "Google Cloud Storage, or path to local file."
    parser.add_argument("image_url", help=path_help)
    args = parser.parse_args()


What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.