<jupyter_start><jupyter_text>Image Data Export* Export labels from image annotation projects<jupyter_code>!pip install labelbox
!pip install requests
!pip install numpy
!pip install PILLOW
!pip install opencv-python
from labelbox import Client
import requests
from getpass import getpass
from PIL import Image
import numpy as np
from io import BytesIO
from typing import Dict, Any
import os
import cv2
# If you don't want to give google access to drive you can skip this cell
# and manually set `API_KEY` below.

COLAB = "google.colab" in str(get_ipython())
if COLAB:
    !pip install colab-env -qU
    from colab_env import envvar_handler
    envvar_handler.envload()

API_KEY = os.environ.get("LABELBOX_API_KEY")
if not os.environ.get("LABELBOX_API_KEY"):
    API_KEY = getpass("Please enter your labelbox api key")
    if COLAB:
        envvar_handler.add_env("LABELBOX_API_KEY", API_KEY)
# Pick a project that has and of box, point, polygon, or segmentation tools tools in the ontology
# and has completed labels
PROJECT_ID = "ckmdx02yhzsrt0757owj3aprx"
# Only update this if you have an on-prem deployment
ENDPOINT = "https://api.labelbox.com/graphql"
client = Client(api_key=API_KEY, endpoint=ENDPOINT)
project = client.get_project(PROJECT_ID)<jupyter_output><empty_output><jupyter_text>Export the labels<jupyter_code>export_url = project.export_labels()<jupyter_output><empty_output><jupyter_text>* Data is exported to a url that is available for you to download<jupyter_code>print(export_url)
exports = requests.get(export_url).json()<jupyter_output><empty_output><jupyter_text>* To get more information on the fields in the label payload click on the following link: https://docs.labelbox.com/data-model/en/index-enlabel<jupyter_code># First annotation in first data row
exports[0]["Label"]["objects"][0]

# If the number of annotations is 0
# Or if this example does not have any annotations, then this will throw a KeyError<jupyter_output><empty_output><jupyter_text>Using the data* We are going to visualize the result.* For your own project update the visualization code to include etl logic.<jupyter_code>def visualize_poly(image: np.ndarray, tool: Dict[str, Any]) -> np.ndarray:
    """
    Draws a polygon on an image
    
    Args:
        image (np.ndarray): image to draw a polygon onto
        tool (Dict[str,any]): Dict response from the export
    Returns:
        image with a polygon drawn on it.
    """
    poly = [[pt["x"], pt["y"]] for pt in tool["polygon"]]
    poly = np.array(poly)
    return cv2.polylines(image, [poly], True, (0, 255, 0), thickness=5)


def visualize_bbox(image: np.ndarray, tool: Dict[str, Any]) -> np.ndarray:
    """
    Draws a bounding box on an image
    
    Args:
        image (np.ndarray): image to draw a bounding box onto
        tool (Dict[str,any]): Dict response from the export
    Returns:
        image with a bounding box drawn on it.
    """
    start = (tool["bbox"]["left"], tool["bbox"]["top"])
    end = (tool["bbox"]["left"] + tool["bbox"]["width"],
           tool["bbox"]["top"] + tool["bbox"]["height"])
    return cv2.rectangle(image, start, end, (255, 0, 0), 5)


def visualize_point(image: np.ndarray, tool: Dict[str, Any]) -> np.ndarray:
    """
    Draws a point on an image
    
    Args:
        image (np.ndarray): image to draw a point onto
        tool (Dict[str,any]): Dict response from the export
    Returns:
        image with a point drawn on it.
    """
    return cv2.circle(image, (tool["point"]["x"], tool["point"]["y"]),
                      radius=10,
                      color=(0, 0, 255),
                      thickness=-1)


def visualize_mask(image: np.ndarray,
                   tool: Dict[str, Any],
                   alpha: float = 0.5) -> np.ndarray:
    """
    Overlays a mask onto an image
    
    Args:
        image (np.ndarray): image to overlay mask onto
        tool (Dict[str,any]): Dict response from the export
        alpha: How much to weight the mask when adding to the image
    Returns:
        image with a point drawn on it.
    """
    mask = np.array(
        Image.open(BytesIO(requests.get(
            tool["instanceURI"]).content)))[:, :, :3]
    mask[:, :, 1] *= 0
    mask[:, :, 2] *= 0
    weighted = cv2.addWeighted(image, alpha, mask, 1 - alpha, 0)
    image[np.sum(mask, axis=-1) > 0] = weighted[np.sum(mask, axis=-1) > 0]
    return image
# Example image
image = np.array(
    Image.open(BytesIO(requests.get(exports[0]["Labeled Data"]).content)))
for tool in exports[0]["Label"]["objects"]:
    if "bbox" in tool:
        image = visualize_bbox(image, tool)
    elif "point" in tool:
        image = visualize_point(image, tool)
    elif "polygon" in tool:
        image = visualize_poly(image, tool)
    elif "instanceURI" in tool and tool['title'] == "car":
        # All tools have instanceURI but the car was made with the segmentation tool
        image = visualize_mask(image, tool)

image = Image.fromarray(image.astype(np.uint8))
w, h = image.size
image.resize((w // 4, h // 4))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11870432549871618, 'fraction_numerical': 0.010468101915860163, 'mean_word_length': 3.3958333333333335, 'pattern_counts': {'":': 1, '<': 21, '<?xml version=': 0, '>': 27, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '275997', 'license': 'Apache-2.0', 'n_tokens_mistral': 1668, 'n_tokens_neox': 1618, 'n_words': 524, 'path': 'examples/label_export/images.ipynb', 'repo_name': 'ccrndn/labelbox-python', 'size': '5063'}