# Computer Vision

> Draw bounding boxes, polygons and freehand shapes, classify and segment images, and plug in models for object detection with human-in-the-loop annotation.

Source: https://prodi.gy/docs/computer-vision

Prodigy comes with built-in annotation interfaces for common computer vision
tasks such as object detection, image segmentation and image classification. You
can boost your annotation efforts by plugging in statistical models with
Prodigy's custom recipes for powerful human-in-the-loop and active-learning
workflows.

## Quickstart

**I want to draw bounding boxes and polygons with labels onto images.**

Prodigy's built-in [`image.manual`](https://prodi.gy/docs/recipes#image-manual) recipe is the easiest way to get started.
It lets you load in a directory and define one or more labels to annotate. In
the [`image_manual`](https://prodi.gy/docs/api-interfaces#image_manual) UI you can then draw bounding boxes and polygon
shapes. For more details and examples, see [this section](https://prodi.gy/docs/computer-vision#manual).

**I want to review and correct existing bounding box annotations.**

Prodigy's [`image.manual`](https://prodi.gy/docs/recipes#image-manual) recipe supports loading images from a directory,
or from a JSONL file containing image URLs. You can read more about it
[in this section](https://prodi.gy/docs/computer-vision#manual-jsonl). If you have existing bounding box annotations,
you can convert them to [Prodigy's format](https://prodi.gy/docs/api-interfaces#image_manual),
load them in and update the annotations. Also see
[this helper function](https://prodi.gy/docs/computer-vision#tip-box-coordinates) for converting bounding box
coordinates. The [`image_manual`](https://prodi.gy/docs/api-interfaces#image_manual) interface currently supports moving
existing boxes using keyboard shortcuts, changing labels of existing shapes and
removing and re-adding shapes.

**I want to assign one or more categories to images.**

For binary categories (i.e. to annotate whether one label applies or not), you
can use the [`mark`](https://prodi.gy/docs/recipes#mark) recipe with the [`classification`](https://prodi.gy/docs/api-interfaces#classification) UI, a `--label`
of your choice and a directory of images with the image loader. See the docs on
[binary image classification](https://prodi.gy/docs/computer-vision#classification-binary) for more details and an
example.

If you want to choose from multiple labels (or assign multiple labels at the
same time), you can write a [custom recipe](https://prodi.gy/docs/custom-recipes) using the
[`choice`](https://prodi.gy/docs/api-interfaces#choice) interface. See the docs on [image classification with multiple
labels](https://prodi.gy/docs/computer-vision#classification-multi) for more details and example code.

**I want to annotate content and layout features of PDFs or scans.**

Prodigy lets you load in documents as images and annotate bounding boxes and shapes using [`image_manual`](https://prodi.gy/docs/api-interfaces#image_manual) UI. You can also use the [`pages`](https://prodi.gy/docs/api-interfaces#pages) interface to group [multi-page documents](https://prodi.gy/docs/computer-vision#pages) together within the same efficient interface. The [Prodigy-PDF](https://prodi.gy/docs/plugins#pdf) plugin extends Prodigy with more workflows for loading and visually annotating PDFs, as well as OCR (Optical Character Recognition) to extract text-based content.

**I want to plug in my own image model.**

Prodigy lets you write [custom recipes](https://prodi.gy/docs/custom-recipes) to script your own
annotation workflows in Python. If you can load your image model and extract
predictions from it in Python, you can plug it into Prodigy. Prodigy represents
annotation tasks using a simple [JSON format](https://prodi.gy/docs/api-interfaces#image). If
your model predicts labels for the whole image, you can add them to each
annotation task and annotate whether the predicted labels are correct. If your
model predicts bounding boxes, you can add them as `"spans"` and manually
correct the result, or accept or reject the individual bounding boxes. See the
section on [custom models](https://prodi.gy/docs/computer-vision#custom-model) for more details and inspiration.

For an end-to-end example using Prodigy with TensorFlow object detection API to
annotate with a model in the loop, check out [this section](https://prodi.gy/docs/computer-vision#tensorflow) (or go
straight [to the tutorial](https://support.prodi.gy/t/1965)).

## Manual annotation of bounding boxes and image segments

The [`image.manual`](https://prodi.gy/docs/recipes#image-manual) recipe lets you load images from a directory and add
bounding boxes and polygon or freeform shapes for one or more labels. You can
click and drag to draw boxes, or click anywhere on the canvas to add polygon
points. Polygon shapes can also be closed by double-clicking when adding the
last point, similar to closing a shape in Photoshop or Illustrator. Clicking on
a shape or its the label will select a shape so you can change the label, its
position and size or delete it. [See here](https://prodi.gy/docs/api-interfaces#image_manual)
for more details about the interface and its configuration options.

```bash title="Example"
prodigy image.manual images_dataset ./images --label PERSON,SKATEBOARD
```

### Bounding box data format

As of v1.10, Prodigy exposes more detailed information for rectangular bounding
boxes, giving you all the measurements you need for training your model. All
coordinates and measurements are provided in pixels, relative to the original
image.

![](https://prodi.gy/docs/ui_image_manual_boxes.svg)

```json title="Bounding box"
{
    "x": 47.5,
    "y": 171.4,
    "width": 109.1,
    "height": 67.4,
    "points": [[47.5, 171.4], [47.5, 238.8], [156.6, 238.8], [156.6, 171.4]],
    "center": [102.05, 205.1],
    "label": "SKATEBOARD"
}
```

> **Warning: Important note about how image annotations are stored**
>
> When you load images from a directory, Prodigy will convert them to a
> base64-encoded data URIs and store the image data **with the annotation task**
> and **in the database**. This is the safest way to ensure that you never lose
> the reference to the original data. However, this can potentially make your
> database and examples _very_ large. To prevent this, **resize your images**
> before you load them in, **load them from URLs** instead or set
> `--remove-base64` to remove the data URI before placing the annotation in the
> database.

### Image collections and multi-page documents

If you organize your images in [subdirectories](https://prodi.gy/api/api-loaders#pages-loader-media), you can set `--loader pages` to group them together in a single interface using the [`pages`](https://prodi.gy/docs/api-interfaces#pages) UI. This can be especially useful for multi-page documents or collections of images that should be viewed together. If you're working with PDFs, the [Prodigy-PDF](https://prodi.gy/docs/plugins#pdf) plugin also supports  loading paginated documents.

```bash title="Example"
prodigy image.manual papers_layout ./documents --loader pages --label FIGURE,FOOTNOTE,PARAGRAPH
```

### Loading images from URLs instead of a directory

If you don't want to store the image data with the tasks, the easiest way to
load images is by providing URLs. Modern browsers typically
[block images from local paths](https://stackoverflow.com/questions/39007243/cannot-open-local-file-chrome-not-allowed-to-load-local-resource)
for security reasons. So you can either host the images with a **local web
server** (e.g. Prodigy's
[`image-server` loader](https://prodi.gy/docs/api-loaders#input-images)) or in an **S3 bucket**
(or similar). You can then load in a JSONL file formatted like this:

```json title="images.jsonl"
{"image": "https://example.com/image1.jpg"}
{"image": "https://example.com/image2.jpg"}
```

It's recommended to include additional meta like an `"id"` or a `"text"`
describing the image so you don't lose the reference to the image if the links
stop working. Additional custom keys you add to the task data will be passed
through and stored in the dataset with the annotations. To load the image data
from a file, you can pass your JSONL file to [`image.manual`](https://prodi.gy/docs/recipes#image-manual) and set
`--loader json`. You also want to set `--no-fetch` to tell Prodigy to _not_ try
and convert all images to base64.

```bash title="Example"
prodigy image.manual images_dataset ./images.jsonl --loader jsonl --label PERSON,SKATEBOARD --no-fetch
```

If you load in data from a JSONL file, you can also pre-populate the `"spans"`
with already annotated bounding boxes. For example, you can export Prodigy
annotations with [`db-out`](https://prodi.gy/docs/recipes#db-out) and re-annotate them, or convert older existing
annotations to [Prodigy's format](https://prodi.gy/docs/api-interfaces#image_manual).

## Image classification

Many computer vision tasks only require assigning labels to whole images.
Framing your annotation problem this way lets you collect data much faster. It
also makes it easier to compare answers or use a workflow like [`review`](https://prodi.gy/docs/recipes#review) to
resolve conflicts (which would be more difficult for bounding boxes, since their
pixels are never going to be identical, so you need additional logic to
determine whether two people annotated the same box).

### Assigning a binary label to images

If you only have one category and you want to annotate whether a label applies
to an image or not, the easiest way to get started is to use the [`mark`](https://prodi.gy/docs/recipes#mark). It
will stream in whatever is in your data using a loader of your choice, assign an
optional `"label"` and render the annotation task with a given
[interface](https://prodi.gy/docs/api-interfaces). In this example, we're annotating whether a
finger is covering the lens:

If the label applies, you can hit `accept`, otherwise you can hit

`reject`. The interface used to render this task is the
[`classification`](https://prodi.gy/docs/api-interfaces#classification) interface, which shows any content (text, images or HTML) with a label on
top. Setting `--loader images` tells Prodigy to use the [image
loader](https://prodi.gy/docs/api-loaders#input-images).

```bash title="Example"
prodigy mark finger_lens_images ./images --loader images --label FINGER_OVER_LENS --view-id classification
```

### Assigning multiple labels to images

If your label set consists of multiple labels, you can use the [`choice`](https://prodi.gy/docs/api-interfaces#choice)
interface to render them as multiple choice options. Let's say you work in the
fashion retail industry and you have a bunch of images of people wearing
products by a specific brand. You already know the brand, but you want to match
up the exact models to items in your catalogue.

If you recognize the model, you can select one of the options. If the question
itself is wrong – for instance, if the sunglasses pictured are a different brand
– you can hit `reject`. And if you're not sure, you can hit

`ignore`. When you export the annotations later, you can filter by `"answer"` to filter out
problematic images or use the rejected examples to fix mistakes in your upstream pipeline.

The custom recipe for this workflow is pretty straightforward: using the
[`get_stream`](https://prodi.gy/docs/api-components#stream.get_stream) util, Prodigy will
automically resolve a directory of images to use the Image loader. You can then
add a list of `"options"` to each incoming example. The `"text"` value is
displayed to the user and the `"id"` is used under the hood. IDs can be integers
or strings, so you can also use your internal catalogue identifiers. When you
select options, their `"id"` values will be added to the task as `"accept"`,
e.g. `"accept": [2]`.

```python title="recipe.py"
import prodigy
from prodigy.components.stream import get_stream as prodigy_get_stream

OPTIONS = [
    {"id": 0, "text": "Ray Ban Wayfarer (Original)"},
    {"id": 1, "text": "Ray Ban Wayfarer (New)"},
    {"id": 2, "text": "Ray Ban Clubmaster (Classic)"},
    {"id": 3, "text": "Ray Ban Aviator (Classic)"},
    {"id": -1, "text": "Other model"}
]

@prodigy.recipe("classify-images")
def classify_images(dataset, source):
    def get_stream():
        # Load the directory of images and add options to each task
        stream = prodigy_get_stream(source)
        for eg in stream:
            eg["options"] = OPTIONS
            yield eg

    return {
        "dataset": dataset,
        "stream": get_stream(),
        "view_id": "choice",
        "config": {
            "choice_style": "single",  # or "multiple"
            # Automatically accept and submit the answer if an option is
            # selected (only available for single-choice tasks)
            "choice_auto_accept": True
        }
    }
```

```bash title="Command-line usage"
prodigy classify-images sunglasses_brands ./images -F recipe.py
```

### Selecting images for a given label

This example shows a classic "CAPTCHA"-style task. The annotator is asked to
select all images that a label applies to – in this case, whether the
low-resolution image shows a car.

Under the hood, this workflow uses the [`choice`](https://prodi.gy/docs/api-interfaces#choice) interface with a
top-level `"label"` and three `"options"` that all define an `"image"`. For
multiple image options, Prodigy will try to align them as nicely as possible in
columns. When you select options, their `"id"` values will be added to the task,
as `"accept"`, e.g. `"accept": [1, 3]`.

```json title="Example JSON task"
{
  "label": "CARS",
  "options": [
    {"id": 1, "image": "https://i.imgur.com/qVhETd4.jpg"},
    {"id": 2, "image": "https://i.imgur.com/HdrE9pv.jpg"},
    {"id": 3, "image": "https://i.imgur.com/KqxpIrc.jpg"}
  ]
}
```

All the stream in your custom recipe needs to do is select the image options and
create a task dict consisting of the `"label"` and the `"options"`. In this
example, we're using a random sample from a list – but depending on your use
case, you probably want to use a different selection strategy. If you already
have a selection of images that you _know_ should never be selected, you could
also randomly mix them in with the options and assign them a special ID. When
you export the data later on, this lets you assess the annotation quality.

```python title="recipe.py"
import prodigy
import random

# Images and IDs (you probably want to be loading them from a file)
IMAGES = [
    (1, "https://i.imgur.com/qVhETd4.jpg"),
    (2, "https://i.imgur.com/HdrE9pv.jpg"),
    (3, "https://i.imgur.com/KqxpIrc.jpg")
]

@prodigy.recipe("captcha")
def captcha_classification(dataset, label):
    def get_stream():
        # Here we're just getting a random sample of 3 and then remove them
        # from the list (you can adjust that for your selection strategy)
        image_sample = random.sample(IMAGES, 3)
        for image in image_sample:
            IMAGES.remove(image)
        options = [{"id": idx, "image": img} for idx, img in image_sample]
        yield {"label": label, "options": options}

    return {
        "dataset": dataset,
        "view_id": "choice",
        "stream": get_stream(),
        "config": {"choice_style": "multiple"}
    }
```

```bash title="Command-line usage"
prodigy captcha cars_dataset CARS -F recipe.py
```

## Using a custom model

If you can load your custom model in Python, you can integrate it with Prodigy
using a [custom recipe](https://prodi.gy/docs/custom-recipes). To view your model's predictions
in the annotation UI, your recipe needs to create a stream that processes each
incoming image and adds the data in Prodigy's [JSON format](https://prodi.gy/docs/computer-vision#image). For
example, you could add a classification `"label"` predicted by your model, or
add `"spans"` containing one or more bounding boxes or polygon shapes.

If your model needs to consume the image data as bytes, you can use the
[`b64_uri_to_bytes` helper function](https://prodi.gy/docs/api-components#b64_uri_to_bytes) that
takes a base64-encoded data URI (created by Prodigy's image loader) and returns
a byte string.

```python
import prodigy
from prodigy.components.stream import get_stream
from prodigy.util import b64_uri_to_bytes

@prodigy.recipe("classify-images")
def classify_images(dataset, source):

    def predict(stream, model):
        for eg in stream:
            image_bytes = b64_uri_to_bytes(eg["image"])
            # Pass the image (bytes) to your model and get its predictions
            predictions = model(image_bytes)
            # 🚨 Add the predictions to the task, e.g. as "label" or "spans"
            # ...
            yield eg

    stream = get_stream(source)

    custom_model = load_your_custom_model()
    stream.apply(predict, model=custom_model)

    return {
        "dataset": dataset,
        "stream": stream,
        "view_id": "choice",
        "config": {
            "choice_style": "single",  # or "multiple"
            "choice_auto_accept": True,
        }
    }
```

What you add to the task depends on your model:

1. **Image classification:** In this case, the model's predictions could be a
   list of labels and their scores. You could then pick the label with the
   highest score, add it as `eg["label"]` and annotate whether it's correct. You
   could also use the labels with the highest scores to pre-select answers in a

   [`choice`](https://prodi.gy/docs/api-interfaces#choice) interface, or use a [sorter](https://prodi.gy/docs/api-components#sorters) like
   `prefer_uncertain` or `prefer_high_scores` to decide which examples to send out for annotation.

2. **Object detection:** In this case, the model would predict bounding boxes
   and their labels. For each bounding box, you could add an entry to
   `eg["spans"]` with a `"label"` and `"points"` describing the coordinates. If
   you use the [`image_manual`](https://prodi.gy/docs/api-interfaces#image_manual) interface, you'll be able to remove
   incorrect boxes and add new ones. If you use the [`image`](https://prodi.gy/docs/api-interfaces#image) interface and
   yield out one task for each bounding box, you'll be able to `accept`
   or `reject` the individual predictions separately.

[Video: /docs/annotation\_image-binary-boxes.mp4](https://prodi.gy/docs/annotation_image-binary-boxes.mp4)

**Tip: Converting bounding box measurements to pixel coordinates**

> **Warning: Important note**
>
> As of v1.10, Prodigy exposes more detailed measurements for rectangular bounding
> boxes by default, including the width and height of the box, as well as the
> center and top/left `x` and `y` coordinates. See the section on the
> [bounding box data format](https://prodi.gy/docs/computer-vision#box-data-format) for details.

Depending on the implementation you use, your model might represent bounding
boxes using the `x` and `y` coordinates of the center and the `width` and
`height` of the box. To convert this format to the `[x, y]` pixel coordinates of
the bounding box corners used by Prodigy, you can run this handy helper
function:

```python
def convert_points(x, y, width, height):
    return [[x - width / 2, y - height / 2], [x - width / 2, y + height / 2],
            [x + width / 2, y + height / 2], [x + width / 2, y - height / 2]]
```

For example, a bounding box with a center at 500px/300px that's 100px wide and
150px high has the corner coordinates
`[[450, 225], [450, 375], [550, 375], [550, 225]]`.

### Example: Using Prodigy with TensorFlow's object detection API

[This great tutorial](https://support.prodi.gy/t/1965) by Abhijit Balaji
explains the process of creating a custom recipe to integrate Prodigy with
[TensorFlow's object detection API](https://github.com/tensorflow/models/tree/master/research/object_detection)
and use a TensorFlow model in the loop for semi-automatic annotation of
[cute raccoons](https://github.com/datitran/raccoon_dataset). The custom recipe
uses [TensorFlow Serving ](https://www.tensorflow.org/tfx/guide/serving) to make
predictions and sends annotations created in Prodigy back to the model. As you
annotate, the model in the loop is updated and saved as a `model.ckpt`.

![](https://prodi.gy/docs/annotation_image-raccoons1.jpg)

![](https://prodi.gy/docs/annotation_image-raccoons2.jpg)

[Read tutorial](https://support.prodi.gy/t/1965)
[View recipes & scripts](https://github.com/explosion/prodigy-recipes/tree/master/image/tf_odapi)
