# Python computer vision libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Pillow](#pillow) | 703.4M | 14.0K | Oct 2026 | MIT-CMU |
| [Transformers](#transformers) | 119.8M | 169.2K | Nov 2026 | Apache-2.0 |
| [opencv-python-headless](#opencv-python-headless) | 63.0M | 5.5K | Nov 2026 | Apache-2.0 |
| [scikit-image](#scikit-image) | 31.7M | 6.6K | Dec 2025 | BSD-3-Clause |
| [TorchVision](#torchvision) | 18.0M | 18.0K | Oct 2026 | BSD |
| [TensorFlow](#tensorflow) | 12.4M | 201.6K | Mar 2026 | Apache-2.0 |
| [Keras](#keras) | 12.0M | 64.4K | Jul 2026 | Apache-2.0 |
| [timm](#timm) | 11.7M | 37.3K | Nov 2026 | Apache-2.0 |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Pillow](#pillow), whose count covers all image handling, has the most monthly downloads in this comparison, at 703.4M.

## Capabilities

| Library | Neural model loader | PyTorch required |
| --- | --- | --- |
| [Pillow](#pillow) | No | No |
| [Transformers](#transformers) | Yes | Yes |
| [opencv-python-headless](#opencv-python-headless) | Yes | No |
| [scikit-image](#scikit-image) | No | No |
| [TorchVision](#torchvision) | Yes | Yes |
| [TensorFlow](#tensorflow) | Yes | No |
| [Keras](#keras) | Yes | No |
| [timm](#timm) | Yes | Yes |

## Libraries

### Pillow

[GitHub](https://github.com/python-pillow/Pillow) · [PyPI](https://pypi.org/project/pillow) · [Docs](https://pillow.readthedocs.io/en/stable/)

Provides the maintained fork of the Python Imaging Library.

- Downloads / mo: 703.4M
- Stars: 14.0K
- Last release: 13.0.0
- License: MIT-CMU
- Capabilities: [From the Pillow docs](https://pillow.readthedocs.io/en/stable/)

```sh
python3 -m pip install pillow
```

**gradio-app/gradio** (44.1K stars)

[gradio-app/gradio](https://github.com/gradio-app/gradio) 

```python
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

```

[gradio/processing_utils.py](https://github.com/gradio-app/gradio/blob/ec06278ed72e5eb73494a9d171ca851d553dc82a/gradio/processing_utils.py#L737-L761) · [More projects using Pillow →](https://dashboard.exa.ai/playground/search?q=pillow%20GitHub%20projects)

**Quickstart**

```python
from PIL import Image
im = Image.open("hopper.ppm")

```

From [tutorial.rst](https://pillow.readthedocs.io/en/stable/handbook/tutorial.html)

### Transformers

[GitHub](https://github.com/huggingface/transformers) · [PyPI](https://pypi.org/project/transformers) · [Docs](https://huggingface.co/docs/transformers/en/tasks/image_classification)

Defines and runs pretrained models for text, vision, audio, and multimodal tasks.

- Downloads / mo: 119.8M
- Stars: 169.2K
- Last release: 5.23.0
- License: Apache-2.0
- Capabilities: [From the Transformers docs](https://huggingface.co/docs/transformers/en/tasks/image_classification)

```sh
python3 -m pip install "transformers[torch,vision]"
```

**obss/sahi** (5.6K stars)

[obss/sahi](https://github.com/obss/sahi) 

```python
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
```

[sahi/models/huggingface.py](https://github.com/obss/sahi/blob/8af413e53115525e4af1cfbc1873019ccb548434/sahi/models/huggingface.py) · [More projects using Transformers →](https://dashboard.exa.ai/playground/search?q=transformers%20GitHub%20projects)

**Quickstart**

```python
from transformers import CLIPVisionConfig, CLIPVisionModelWithProjection
configuration = CLIPVisionConfig()
model = CLIPVisionModelWithProjection(configuration)

```

From [clip.md](https://huggingface.co/docs/transformers/model_doc/clip)

### opencv-python-headless

[GitHub](https://github.com/opencv/opencv-python) · [PyPI](https://pypi.org/project/opencv-python-headless)

Wraps the OpenCV Python bindings.

- Downloads / mo: 63.0M
- Stars: 5.5K
- Last release: 5.1.0.95
- License: Apache-2.0
- Capabilities: [From the opencv-python-headless docs](https://github.com/opencv/opencv-python)

```sh
python3 -m pip install opencv-python-headless
```

**ultralytics/yolov5** (58.3K stars)

[ultralytics/yolov5](https://github.com/ultralytics/yolov5) 

```python
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
    """Resizes and pads image to new_shape with stride-multiple constraints, returns resized image, ratio, padding."""
    shape = im.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better val mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = round(shape[1] * r), round(shape[0] * r)
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = round(dh - 0.1), round(dh + 0.1)
    left, right = round(dw - 0.1), round(dw + 0.1)
    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return im, ratio, (dw, dh)

```

[utils/augmentations.py](https://github.com/ultralytics/yolov5/blob/cb2f17fd5d790cfdd0c07c25351904df9affbe6e/utils/augmentations.py#L85-L115) · [More projects using opencv-python-headless →](https://dashboard.exa.ai/playground/search?q=opencv-python-headless%20GitHub%20projects)

**Quickstart**

```python
import cv2
image = cv2.imread('input.jpg')
resized = cv2.resize(image, (320, 240))

```

From [imgproc_transform.html](https://docs.opencv.org/5.0/main_modules/imgproc_transform.html)

### scikit-image

[GitHub](https://github.com/scikit-image/scikit-image) · [PyPI](https://pypi.org/project/scikit-image) · [Docs](https://scikit-image.org/docs/stable/)

Analyzes NumPy images with image-processing, feature-detection, and scientific imaging functions.

- Downloads / mo: 31.7M
- Stars: 6.6K
- Last release: 0.26.0
- License: BSD-3-Clause
- Capabilities: [From the scikit-image docs](https://scikit-image.org/docs/stable/)

**Strengths**

- **Works directly with NumPy images.** Apply image processing to ordinary NumPy arrays.
- **Finds image edges with Canny.** Compare edge maps using different smoothing strengths.

**Watch out for**

- **Type changes need intensity rescaling.** Use image conversion helpers when changing pixel data types.
- **OpenCV colors need channel conversion.** Convert BGR images to RGB before processing them.

```sh
python3 -m pip install scikit-image
```

**sbrunner/deskew** (531 stars)

[sbrunner/deskew](https://github.com/sbrunner/deskew) 

```python
def determine_skew_dev(
    image: ImageType,
    sigma: float = 3.0,
    num_peaks: int = 20,
    min_angle: float | None = None,  # -np.pi / 2,
    max_angle: float | None = None,  # np.pi / 2,
    min_deviation: float = np.pi / 180,
    angle_pm_90: bool = False,
) -> tuple[
    np.float64 | None,
    tuple[
        tuple[ImageTypeUint64, list[list[np.float64]], ImageTypeFloat64],
        tuple[list[Any], list[np.float64], list[np.float64]],
        tuple[dict[np.float64, int], dict[np.float64, int]],
    ],
]:
    """Calculate skew angle."""
    num_angles = round(np.pi / min_deviation)
    imagergb = rgba2rgb(image) if len(image.shape) == 3 and image.shape[2] == 4 else image  # type: ignore[no-untyped-call]
    img = rgb2gray(imagergb) if len(imagergb.shape) == 3 else imagergb
    edges = canny(img, sigma=sigma)  # type: ignore[no-untyped-call]
    out, angles, distances = hough_line(edges, np.linspace(-np.pi / 2, np.pi / 2, num_angles, endpoint=False))  # type: ignore[no-untyped-call]
    hough_line_out = (out, angles, distances)

    hspace, angles_peaks, dists = hough_line_peaks(  # type: ignore[no-untyped-call]
        out,
        angles,
        distances,
        num_peaks=num_peaks,
        threshold=0.05 * np.max(out),
    )
    hough_line_peaks_out = (hspace, angles_peaks, dists)

    if len(angles_peaks) == 0:
        return None, (hough_line_out, hough_line_peaks_out, ({}, {}))

    freqs_original: dict[np.float64, int] = {}
    for peak in angles_peaks:
        freqs_original.setdefault(peak, 0)
        freqs_original[peak] += 1

    angles_peaks_corrected = [
        (a % np.pi - np.pi / 2) if angle_pm_90 else ((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
        for a in angles_peaks
    ]
    angles_peaks_filtred = (
        [a for a in angles_peaks_corrected if a >= min_angle]
        if min_angle is not None
        else angles_peaks_corrected
    )
    angles_peaks_filtred = (
        [a for a in angles_peaks_filtred if a <= max_angle] if max_angle is not None else angles_peaks_filtred
    )
    if not angles_peaks_filtred:
        return None, (hough_line_out, hough_line_peaks_out, ({}, {}))

    freqs: dict[np.float64, int] = {}
    for peak in angles_peaks_filtred:
        freqs.setdefault(peak, 0)
        freqs[peak] += 1

    sorted_keys = sorted(freqs.keys(), key=freqs.get, reverse=True)  # type: ignore[arg-type]
    max_freq = freqs[sorted_keys[0]]

    angle = None
    for sorted_key in sorted_keys:
        if freqs[sorted_key] == max_freq:
            angle = sorted_key
            break

    return (
        angle,
        (hough_line_out, hough_line_peaks_out, (freqs_original, freqs)),
    )

```

[deskew/__init__.py](https://github.com/sbrunner/deskew/blob/b362a48f18ccb650d69cd8d7df3d81c31a5410a5/deskew/__init__.py#L28-L101) · [More projects using scikit-image →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20scikit-image%20to%20resize%20detection%20inputs%2C%20adapt%20scientific%20image%20processing%20and%20build%20paired%20or%20training-time%20image%20transforms&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import skimage as ski
coins = ski.data.coins()
threshold_value = ski.filters.threshold_otsu(coins)

```

From [plot_canny.py](https://scikit-image.org/docs/stable/user_guide/getting_started.html)

### TorchVision

[GitHub](https://github.com/pytorch/vision) · [PyPI](https://pypi.org/project/torchvision) · [Docs](https://pytorch.org/vision/stable/models.html)

Provides PyTorch vision datasets, pretrained models, image transforms, and image encoding or decoding.

- Downloads / mo: 18.0M
- Stars: 18.0K
- Last release: 0.29.2
- License: BSD
- Capabilities: [From the TorchVision docs](https://pytorch.org/vision/stable/models.html)

**Strengths**

- **Bundles preprocessing with pretrained weights.** Use each weight configuration’s transforms before running inference.
- **Augments CPU and GPU tensors.** Use image transforms with PIL images or CPU and CUDA tensors.

**Watch out for**

- **Detection APIs can change.** The detection module remains beta without guaranteed backward compatibility.
- **Pretrained weights need matching preprocessing.** Apply the selected weight’s transforms to prepare images for inference.

```sh
python3 -m pip install torchvision
```

**lucidrains/denoising-diffusion-pytorch** (10.7K stars)

[lucidrains/denoising-diffusion-pytorch](https://github.com/lucidrains/denoising-diffusion-pytorch) 

```python
def __init__(
    self,
    folder,
    image_size,
    exts = ['jpg', 'jpeg', 'png', 'tiff'],
    augment_horizontal_flip = False,
    convert_image_to = None
):
    super().__init__()
    self.folder = folder
    self.image_size = image_size
    self.paths = [p for ext in exts for p in Path(f'{folder}').glob(f'**/*.{ext}')]

    maybe_convert_fn = partial(convert_image_to_fn, convert_image_to) if exists(convert_image_to) else nn.Identity()

    self.transform = T.Compose([
        T.Lambda(maybe_convert_fn),
        T.Resize(image_size),
        T.RandomHorizontalFlip() if augment_horizontal_flip else nn.Identity(),
        T.CenterCrop(image_size),
        T.ToTensor()
    ])

```

[denoising_diffusion_pytorch/denoising_diffusion_pytorch.py](https://github.com/lucidrains/denoising-diffusion-pytorch/blob/c8155b1dc622e3f1ef0d53dc6e5a570ca105bcec/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py#L854-L875) · [More projects using TorchVision →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20torchvision%20to%20resize%20detection%20inputs%2C%20adapt%20scientific%20image%20processing%20and%20build%20paired%20or%20training-time%20image%20transforms&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from torchvision.models import resnet50, ResNet50_Weights
model = resnet50(weights=None)

```

From [plot_transforms_getting_started.py](https://pytorch.org/vision/stable/models.html)

### TensorFlow

[GitHub](https://github.com/tensorflow/tensorflow) · [PyPI](https://pypi.org/project/tensorflow) · [Docs](https://www.tensorflow.org/api_docs/python/tf/image)

Provides an open-source machine learning framework.

- Downloads / mo: 12.4M
- Stars: 201.6K
- Last release: 2.21.0
- License: Apache-2.0
- Capabilities: [From the TensorFlow docs](https://www.tensorflow.org/api_docs/python/tf/image)

```sh
python3 -m pip install tensorflow
```

**Quickstart**

```python
import tensorflow as tf
image = tf.zeros([224, 224, 3])
flipped = tf.image.flip_left_right(image)

```

From [image_ops_impl.py](https://www.tensorflow.org/api_docs/python/tf/image/flip_left_right) · [Find projects using TensorFlow →](https://dashboard.exa.ai/playground/search?q=tensorflow%20GitHub%20projects)

### Keras

[GitHub](https://github.com/keras-team/keras) · [PyPI](https://pypi.org/project/keras) · [Docs](https://keras.io/getting_started/)

Provides multi-backend Keras.

- Downloads / mo: 12.0M
- Stars: 64.4K
- Last release: 3.15.1
- License: Apache-2.0
- Capabilities: [From the Keras docs](https://keras.io/getting_started/)

```sh
python3 -m pip install keras tensorflow
```

**keras-team/keras-io** (3.0K stars)

[keras-team/keras-io](https://github.com/keras-team/keras-io) 

```python
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)

```

[examples/vision/image_classification_from_scratch.py](https://github.com/keras-team/keras-io/blob/f5891b3cd4df69f6bd5a3c26ea92310f3a973626/examples/vision/image_classification_from_scratch.py#L236-L278) · [More projects using Keras →](https://dashboard.exa.ai/playground/search?q=keras%20GitHub%20projects)

**Quickstart**

```python
from keras.applications.resnet50 import ResNet50
model = ResNet50(weights='imagenet')

```

From [index.md](https://keras.io/api/applications/)

### timm

[GitHub](https://github.com/huggingface/pytorch-image-models) · [PyPI](https://pypi.org/project/timm) · [Docs](https://huggingface.co/docs/timm/quickstart)

Provides PyTorch image models.

- Downloads / mo: 11.7M
- Stars: 37.3K
- Last release: 1.0.31
- License: Apache-2.0
- Capabilities: [From the timm docs](https://huggingface.co/docs/timm/quickstart)

```sh
python3 -m pip install timm
```

**huggingface/transformers** (169.2K stars)

[huggingface/transformers](https://github.com/huggingface/transformers) 

```python
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
    )

```

[src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py](https://github.com/huggingface/transformers/blob/8f9c231c86db3e41b4b09cd0df90965c9b951dad/src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py#L52-L71) · [More projects using timm →](https://dashboard.exa.ai/playground/search?q=timm%20GitHub%20projects)

**Quickstart**

```python
import timm
m = timm.create_model('mobilenetv3_large_100', pretrained=True)
m.eval()

```

From [quickstart.mdx](https://huggingface.co/docs/timm/quickstart)

## FAQ

### Which Python computer vision library should I use?

[opencv-python-headless](#opencv-python-headless) suits classical image processing and video on servers. [TorchVision](#torchvision) and [timm](#timm) suit training and running image models in PyTorch. [Transformers](#transformers) suits pretrained vision and multimodal models.

### What is OpenCV?

OpenCV is an open-source computer vision library with Python bindings for image processing, video capture, and feature detection. The [headless package](#opencv-python-headless) drops GUI dependencies for servers.

### What is Pillow?

[Pillow](#pillow) is the maintained fork of the Python Imaging Library. It opens, converts, resizes, and saves images in many formats.

### What is timm?

[timm](#timm), short for PyTorch Image Models, is a collection of pretrained image models with training and inference scripts.

### What is torchvision?

[TorchVision](#torchvision) provides PyTorch vision datasets, pretrained models, and image transforms.

### Keras vs TensorFlow: what is the difference?

[Keras](#keras) is a high-level model API that runs on TensorFlow, JAX, or PyTorch. [TensorFlow](#tensorflow) is a full machine learning framework that Keras can use as its backend.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python computer vision libraries OpenCV scikit-image Kornia Torchvision code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
