← Journal
Classify Images Without Labels: Running OpenCLIP

Classify Images Without Labels: Running OpenCLIP

A record of running OpenCLIP, an open implementation of CLIP that compares images and text in the same space, with the network disconnected. I wrote candidate sentences for the test, and OpenCLIP selected the correct description with high confidence. I used no label set from prior classifier training.

Repository covered in this article

mlfoundations/open_clip

An open source implementation of CLIP.

14k Python Other

To classify images with a conventional workflow, you prepare many labels such as "dog" and "cat" and train a classifier. OpenCLIP embeds images and text in the same vector space, so it can choose the closest text from arbitrary candidates without labeled data for the classification task. I installed it and tested zero-shot classification with the network disconnected.

OpenCLIP is an open implementation and reproduction of OpenAI's CLIP model. It converts images and text into embedding vectors, then computes their similarity. OpenCLIP uses the MIT License for its source.(*1)

1. Installation

Obtain the CLIP model weights, OpenAI's public ViT-B-32, during the build while the network is available.

FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'torch==2.13.0' 'torchvision==0.28.0' --index-url https://download.pytorch.org/whl/cpu
RUN pip install --no-cache-dir --quiet 'open_clip_torch==3.3.0'
COPY warmup_model.py /tmp/warmup_model.py
RUN python /tmp/warmup_model.py
WORKDIR /work
podman build -t open-clip-sandbox .

2. Classify an Image Without Training a Classifier

I generated a composite image representing "an outdoor landscape with sky, grass, and sun" (blue sky + green ground + yellow sun), then asked OpenCLIP to choose the closest of four candidate descriptions. I trained no classifier for this test. I ran it with the network disconnected.

import torch
from PIL import Image, ImageDraw
import open_clip

model, _, preprocess = open_clip.create_model_and_transforms("ViT-B-32", pretrained="openai")
tokenizer = open_clip.get_tokenizer("ViT-B-32")

img = Image.new("RGB", (224, 224), color=(90, 160, 230))
draw = ImageDraw.Draw(img)
draw.rectangle((0, 160, 224, 224), fill=(60, 140, 60))
draw.ellipse((150, 20, 200, 70), fill=(250, 210, 60))

candidate_labels = [
    "a sunny outdoor landscape with grass and sky",
    "a photo of a busy city street at night",
    "a close-up photo of a plate of food",
    "a photo of a laptop computer on a desk",
]

image_input = preprocess(img).unsqueeze(0)
text_input = tokenizer(candidate_labels)

with torch.no_grad():
    image_features = model.encode_image(image_input)
    text_features = model.encode_text(text_input)
    image_features /= image_features.norm(dim=-1, keepdim=True)
    text_features /= text_features.norm(dim=-1, keepdim=True)
    similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
  -v "$(pwd)":/work -w /work open-clip-sandbox \
  python classify_demo.py

The -v option makes the specified directory readable and writable from the container. Run this command in an empty directory reserved for experiments.

The command returned:

 92.6%  a sunny outdoor landscape with grass and sky
  7.3%  a close-up photo of a plate of food
  0.1%  a photo of a laptop computer on a desk
  0.0%  a photo of a busy city street at night

The correct candidate reached 92.6% confidence. The three unrelated candidates stayed at low probabilities. I used the four candidate sentences for this experiment and no other task. I kept them out of prior classifier training.

You Don't Need to Build a Classifier for Each Task

Preparing a dedicated labeled dataset and training a classifier adds setup work to image classification. A model such as OpenCLIP can compare images and text in the same space. You write the candidate descriptions you want to test and skip building a classifier for that task.

Sources

*1 OpenCLIP (GitHub), https://github.com/mlfoundations/open_clip, MIT License