Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python computer vision libraries load images and video, transform them, and extract information such as objects, faces, and text. Most current pipelines pass each image through a trained neural network rather than hand-written filters. These libraries let apps and AI agents detect, classify, and measure what appears in images.
Popularity
Pillow, whose count covers all image handling, has the most monthly downloads in this comparison, at 703.4M.
def resize_and_crop(img, size, crop_type="center"):
"""
Resize and crop an image to fit the specified size.
args:
size: `(width, height)` tuple. Pass `None` for either width or height
to only crop and resize the other.
crop_type: can be 'top', 'middle' or 'bottom', depending on this
value, the image will cropped getting the 'top/left', 'middle' or
'bottom/right' of the image to fit the size.
raises:
ValueError: if an invalid `crop_type` is provided.
"""
if crop_type == "top":
center = (0, 0)
elif crop_type == "center":
center = (0.5, 0.5)
else:
raise ValueError
resize = list(size)
if size[0] is None:
resize[0] = img.size[0]
if size[1] is None:
resize[1] = img.size[1]
return ImageOps.fit(img, resize, centering=center) # type: ignore
Transformers
Defines and runs pretrained models for text, vision, audio, and multimodal tasks.
def perform_inference(self, image: list | np.ndarray):
"""Prediction is performed using self.model and the prediction result is set to self._original_predictions.
Args:
image: np.ndarray
A numpy array that contains the image to be predicted. 3 channel image should be in RGB order.
"""
import torch
# Confirm model is loaded if self.model is None or self.processor is None:
raise RuntimeError("Model is not loaded, load it by calling .load_model()")
with torch.no_grad():
inputs = self.processor(images=image, return_tensors="pt")
inputs["pixel_values"] = inputs.pixel_values.to(self.device)
if hasattr(inputs, "pixel_mask"):
inputs["pixel_mask"] = inputs.pixel_mask.to(self.device)
outputs = self.model(**inputs)
if isinstance(image, list):
self._image_shapes = [img.shape for img in image]
else:
self._image_shapes = [image.shape]
self._original_predictions = outputs
def make_model(input_shape, num_classes):
inputs = keras.Input(shape=input_shape)
# Entry block x = layers.Rescaling(1.0 / 255)(inputs)
x = layers.Conv2D(128, 3, strides=2, padding="same")(x)
x = layers.BatchNormalization()(x)
x = layers.Activation("relu")(x)
previous_block_activation = x # Set aside residual
for size in [256, 512, 728]:
x = layers.Activation("relu")(x)
x = layers.SeparableConv2D(size, 3, padding="same")(x)
x = layers.BatchNormalization()(x)
x = layers.Activation("relu")(x)
x = layers.SeparableConv2D(size, 3, padding="same")(x)
x = layers.BatchNormalization()(x)
x = layers.MaxPooling2D(3, strides=2, padding="same")(x)
# Project residual residual = layers.Conv2D(size, 1, strides=2, padding="same")(
previous_block_activation
)
x = layers.add([x, residual]) # Add back residual
previous_block_activation = x # Set aside next residual
x = layers.SeparableConv2D(1024, 3, padding="same")(x)
x = layers.BatchNormalization()(x)
x = layers.Activation("relu")(x)
x = layers.GlobalAveragePooling2D()(x)
if num_classes == 2:
units = 1
else:
units = num_classes
x = layers.Dropout(0.25)(x)
# We specify activation=None so as to return logits outputs = layers.Dense(units, activation=None)(x)
return keras.Model(inputs, outputs)
def __init__(
self,
pretrained_cfg: dict[str, Any],
architecture: str | None = None,
**kwargs,
):
super().__init__(architecture=architecture)
self.data_config = timm.data.resolve_data_config(pretrained_cfg, model=None, verbose=False)
self.val_transforms = timm.data.create_transform(**self.data_config, is_training=False)
# useful for training self.train_transforms = timm.data.create_transform(**self.data_config, is_training=True)
# If `ToTensor` is in the transforms, then the input should be numpy array or PIL image. # Otherwise, the input can be a tensor. In later timm versions, `MaybeToTensor` is used # which can handle both numpy arrays / PIL images and tensors. self._not_supports_tensor_input = any(
transform.__class__.__name__ == "ToTensor" for transform in self.val_transforms.transforms
)
FAQ
opencv-python-headless suits classical image processing and video on servers. TorchVision and timm suit training and running image models in PyTorch. Transformers suits pretrained vision and multimodal models.
OpenCV is an open-source computer vision library with Python bindings for image processing, video capture, and feature detection. The headless package drops GUI dependencies for servers.
Pillow is the maintained fork of the Python Imaging Library. It opens, converts, resizes, and saves images in many formats.
timm, short for PyTorch Image Models, is a collection of pretrained image models with training and inference scripts.
TorchVision provides PyTorch vision datasets, pretrained models, and image transforms.
Keras is a high-level model API that runs on TensorFlow, JAX, or PyTorch. TensorFlow is a full machine learning framework that Keras can use as its backend.
For coding agents
Found your computer vision library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.