# Python object detection libraries

Python object detection libraries find objects in images and video and return each one with a label, a confidence score, and a bounding box. A detector runs a trained neural network on each image and filters overlapping boxes before returning results. These libraries let cameras, robots, and AI agents locate what appears in a scene.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Transformers](#transformers) | 120.5M | 169.2K | Nov 2026 | Apache-2.0 |
| [opencv-python-headless](#opencv-python-headless) | 64.1M | 5.5K | Nov 2026 | Apache-2.0 |
| [TorchVision](#torchvision) | 18.1M | 18.0K | Oct 2026 | BSD-3-Clause |
| [Ultralytics](#ultralytics) | 5.1M | 63.6K | Nov 2026 | AGPL-3.0 |
| [ModelScope](#modelscope) | 4.3M | 9.2K | Nov 2026 | Apache-2.0 |
| [MediaPipe](#mediapipe) | 3.0M | 37.7K | Nov 2026 | Apache-2.0 |
| [PaddleX](#paddlex) | 1.1M | 6.3K | Jun 2026 | Apache-2.0 |
| [KerasHub](#keras-hub) | 471.7K | 999 | Nov 2026 | Apache-2.0 |

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

[Transformers](#transformers) has the most monthly downloads in this comparison, at 120.5M, a count that covers every model task in the library.

## Capabilities

| Library | PyTorch required for detector | Downloads pretrained weights |
| --- | --- | --- |
| [Transformers](#transformers) | Yes | Yes |
| [opencv-python-headless](#opencv-python-headless) | No | No |
| [TorchVision](#torchvision) | Yes | Yes |
| [Ultralytics](#ultralytics) | Yes | Yes |
| [ModelScope](#modelscope) | Yes | Yes |
| [MediaPipe](#mediapipe) | No | No |
| [PaddleX](#paddlex) | No | Yes |
| [KerasHub](#keras-hub) | No | Yes |

## Libraries

### Transformers

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

Loads detection models and processors for box prediction and task-specific fine-tuning.

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

**Strengths**

- **Detects objects from text prompts.** Use a zero-shot detector to search for named visual concepts.
- **Rescales boxes to image dimensions.** Pass target_sizes when postprocessing model predictions.

**Watch out for**

- **Custom labels need head replacement.** Provide label mappings and replace the pretrained classification head during fine-tuning.
- **Evaluation needs separate box batches.** Set eval_do_concat_batches=False when target-box counts differ across images.

```sh
pip install "transformers[torch,vision]==5.23.0" pillow
```

**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=Projects%20using%20transformers%20for%20image%20object%20detection%20with%20bounding%20boxes%20and%20annotation%20conversion&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 PIL import Image
from transformers import pipeline
detector = pipeline("object-detection", model="facebook/detr-resnet-50", device=-1)
print(detector(Image.new("RGB", (640, 480))))

```

From [object_detection.md](https://huggingface.co/docs/transformers/main/en/tasks/object_detection)

### opencv-python-headless

[GitHub](https://github.com/opencv/opencv-python) · [PyPI](https://pypi.org/project/opencv-python-headless) · [Docs](https://docs.opencv.org/5.1.0/d3/df1/classcv_1_1dnn_1_1DetectionModel.html)

Wraps the OpenCV Python bindings.

- Downloads / mo: 64.1M
- Stars: 5.5K
- Last release: 5.1.0.95
- License: Apache-2.0
- Capabilities: [From the opencv-python-headless docs](https://docs.opencv.org/5.1.0/d3/df1/classcv_1_1dnn_1_1DetectionModel.html)

```sh
pip install opencv-python-headless==5.1.0.95
```

**opencv/opencv** (91.6K stars)

[opencv/opencv](https://github.com/opencv/opencv) 

```python
def processingThreadBody():
    global processedFramesQueue, predictionsQueue, args, process, asyncN

    futureOutputs = []
    while process:
        # Get a next frame
        frame = None
        try:
            frame = framesQueue.get_nowait()

            if asyncN:
                if len(futureOutputs) == asyncN:
                    frame = None  # Skip the frame
            else:
                framesQueue.queue.clear()  # Skip the rest of frames
        except queue.Empty:
            pass


        if not frame is None:
            frameHeight = frame.shape[0]
            frameWidth = frame.shape[1]

            # Create a 4D blob from a frame.
            inpWidth = args.width if args.width else frameWidth
            inpHeight = args.height if args.height else frameHeight
            blob = cv.dnn.blobFromImage(frame, scalefactor=args.scale, mean=args.mean, size=(inpWidth, inpHeight), swapRB=args.rgb, ddepth=cv.CV_32F)
            processedFramesQueue.put(frame)

            # Run a model
            net.setInput(blob)

            if asyncN:
                futureOutputs.append(net.forwardAsync())
            else:
                outs = net.forward(outNames)
                net.printPerfProfile()
                predictionsQueue.put(copy.deepcopy(outs))

        while futureOutputs and futureOutputs[0].wait_for(0):
            out = futureOutputs[0].get()
            predictionsQueue.put(copy.deepcopy([out]))

            del futureOutputs[0]
```

[samples/dnn/object_detection.py](https://github.com/opencv/opencv/blob/e4f78fbcf1a773fbed69e14500e8b734963eb585/samples/dnn/object_detection.py) · [More projects using opencv-python-headless →](https://dashboard.exa.ai/playground/search?q=opencv-python-headless%20GitHub%20projects)

**Quickstart**

```python
import json, sys, cv2
detector = cv2.dnn.DetectionModel(sys.argv[1])
detector.setInputParams(**json.loads(sys.argv[2]))
print(detector.detect(cv2.imread(sys.argv[3]), confThreshold=0.5, nmsThreshold=0.4))

```

From [dnn.hpp](https://docs.opencv.org/5.1.0/d3/df1/classcv_1_1dnn_1_1DetectionModel.html)

### TorchVision

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

Provides models for object detection and instance segmentation.

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

**Strengths**

- **Pairs weights with preprocessing.** Use the chosen weights’ transforms before running the detector.
- **Returns detection training losses.** Inspect the classification and regression losses returned during training.

**Watch out for**

- **Detection APIs can change.** The detection module is beta and does not guarantee backward compatibility.
- **Requires scaled tensor inputs.** Pass image tensors with values scaled between zero and one.

```sh
pip install torchvision==0.29.2 "torch>=2.14.0" pillow
```

**cvat-ai/cvat** (17.1K stars)

[cvat-ai/cvat](https://github.com/cvat-ai/cvat) 

```python
def detect(
    self, context: cvataa.DetectionFunctionContext, image: PIL.Image.Image
) -> list[models.LabeledShapeRequest]:
    conf_threshold = context.conf_threshold or 0
    results = self._model([self._transforms(image)])

    return [
        cvataa.rectangle(label.item(), [x.item() for x in box])
        for result in results
        for box, label, score in zip(result["boxes"], result["labels"], result["scores"])
        if score >= conf_threshold
    ]
```

[cvat-sdk/cvat_sdk/auto_annotation/functions/torchvision_detection.py](https://github.com/cvat-ai/cvat/blob/125313b9e252478a5e4d179c37bdcd2a1bb69760/cvat-sdk/cvat_sdk/auto_annotation/functions/torchvision_detection.py) · [More projects using TorchVision →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20torchvision%20for%20image%20object%20detection%20with%20bounding%20boxes%20and%20annotation%20conversion&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 PIL import Image
from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights
weights = FasterRCNN_ResNet50_FPN_Weights.DEFAULT
model = fasterrcnn_resnet50_fpn(weights=weights).eval()
print(model([weights.transforms()(Image.new("RGB", (640, 480)))]))

```

From [models.html](https://docs.pytorch.org/vision/stable/models/generated/torchvision.models.detection.fasterrcnn_resnet50_fpn.html)

### Ultralytics

[GitHub](https://github.com/ultralytics/ultralytics) · [PyPI](https://pypi.org/project/ultralytics) · [Docs](https://docs.ultralytics.com/modes/predict/)

Runs YOLO detection and exposes structured results for images, batches, and streams.

- Downloads / mo: 5.1M
- Stars: 63.6K
- Last release: 8.4.215
- License: AGPL-3.0
- Capabilities: [From the Ultralytics docs](https://docs.ultralytics.com/modes/predict/)

**Strengths**

- **Streams results as they arrive.** Use stream=True to process results without retaining the complete list.
- **Accepts custom text labels.** Set the class vocabulary with a supported YOLO-World model.

**Watch out for**

- **Default results retain every frame.** Use stream=True for long videos instead of keeping every result in memory.
- **Threads need separate model instances.** Instantiate a model inside each prediction thread.

```sh
pip install ultralytics==8.4.215 numpy
```

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

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

```python
def load_model(self):
    """Detection model is initialized and set to self.model.

    Supports both PyTorch (.pt) and ONNX (.onnx) models.
    """

    from ultralytics import YOLO

    if self.model_path and ".onnx" in self.model_path:
        check_requirements(["onnx", "onnxruntime"])

    try:
        model = YOLO(self.model_path)
        # Only call .to(device) for PyTorch models, not ONNX
        if self.model_path and not self.model_path.endswith(".onnx"):
            model.to(self.device)
        self.set_model(model)
        if self.fuse and hasattr(model, "fuse"):
            model.fuse()

    except Exception as e:
        raise TypeError("model_path is not a valid Ultralytics model path: ", e)
```

[sahi/models/ultralytics.py](https://github.com/obss/sahi/blob/8af413e53115525e4af1cfbc1873019ccb548434/sahi/models/ultralytics.py) · [More projects using Ultralytics →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20ultralytics%20for%20image%20object%20detection%20with%20bounding%20boxes%20and%20annotation%20conversion&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 numpy as np
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
print(model.predict(np.zeros((640, 640, 3), dtype=np.uint8), device="cpu"))

```

From [predict.md](https://docs.ultralytics.com/modes/predict/)

### ModelScope

[GitHub](https://github.com/modelscope/modelscope) · [PyPI](https://pypi.org/project/modelscope) · [Docs](https://github.com/modelscope/modelscope/blob/v1.40.3/modelscope/pipelines/cv/tinynas_detection_pipeline.py)

Provides models as a service.

- Downloads / mo: 4.3M
- Stars: 9.2K
- Last release: 1.40.3
- License: Apache-2.0
- Capabilities: [From the ModelScope docs](https://github.com/modelscope/modelscope/blob/v1.40.3/modelscope/pipelines/cv/tinynas_detection_pipeline.py)

```sh
pip install "modelscope[cv]==1.40.3" torch numpy
```

**Quickstart**

```python
import sys, numpy as np
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
detector = pipeline(Tasks.image_object_detection, model=sys.argv[1], device="cpu")
print(detector(np.zeros((640, 640, 3), dtype=np.uint8)))

```

From [tinynas_detection_pipeline.py](https://github.com/modelscope/modelscope/blob/v1.40.3/modelscope/pipelines/cv/tinynas_detection_pipeline.py) · [Find projects using ModelScope →](https://dashboard.exa.ai/playground/search?q=modelscope%20GitHub%20projects)

### MediaPipe

[GitHub](https://github.com/google-ai-edge/mediapipe) · [PyPI](https://pypi.org/project/mediapipe) · [Docs](https://ai.google.dev/edge/mediapipe/solutions/vision/object_detector/python)

Builds machine learning solutions for mobile, edge, cloud, and web.

- Downloads / mo: 3.0M
- Stars: 37.7K
- Last release: 1.2.3
- License: Apache-2.0
- Capabilities: [From the MediaPipe docs](https://ai.google.dev/edge/mediapipe/solutions/vision/object_detector/python)

```sh
pip install mediapipe==1.2.3
```

**google-ai-edge/mediapipe-samples** (2.9K stars)

[google-ai-edge/mediapipe-samples](https://github.com/google-ai-edge/mediapipe-samples) 

```python
def run(model: str, max_results: int, score_threshold: float, 
        camera_id: int, width: int, height: int) -> None:
  """Continuously run inference on images acquired from the camera.

  Args:
    model: Name of the TFLite object detection model.
    max_results: Max number of detection results.
    score_threshold: The score threshold of detection results.
    camera_id: The camera id to be passed to OpenCV.
    width: The width of the frame captured from the camera.
    height: The height of the frame captured from the camera.
  """

  # Start capturing video input from the camera
  cap = cv2.VideoCapture(camera_id)
  cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
  cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

  # Visualization parameters
  row_size = 50  # pixels
  left_margin = 24  # pixels
  text_color = (0, 0, 0)  # black
  font_size = 1
  font_thickness = 1
  fps_avg_frame_count = 10

  detection_frame = None
  detection_result_list = []

  def save_result(result: vision.ObjectDetectorResult, unused_output_image: mp.Image, timestamp_ms: int):
      global FPS, COUNTER, START_TIME

      # Calculate the FPS
      if COUNTER % fps_avg_frame_count == 0:
          FPS = fps_avg_frame_count / (time.time() - START_TIME)
          START_TIME = time.time()

      detection_result_list.append(result)
      COUNTER += 1

  # Initialize the object detection model
  base_options = python.BaseOptions(model_asset_path=model)
  options = vision.ObjectDetectorOptions(base_options=base_options,
                                         running_mode=vision.RunningMode.LIVE_STREAM,
                                         max_results=max_results, score_threshold=score_threshold,
                                         result_callback=save_result)
  detector = vision.ObjectDetector.create_from_options(options)


  # Continuously capture images from the camera and run inference
  while cap.isOpened():
    success, image = cap.read()
    if not success:
      sys.exit(
          'ERROR: Unable to read from webcam. Please verify your webcam settings.'
      )

    image = cv2.flip(image, 1)

    # Convert the image from BGR to RGB as required by the TFLite model.
    rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_image)

    # Run object detection using the model.
    detector.detect_async(mp_image, time.time_ns() // 1_000_000)

    # Show the FPS
    fps_text = 'FPS = {:.1f}'.format(FPS)
    text_location = (left_margin, row_size)
    current_frame = image
    cv2.putText(current_frame, fps_text, text_location, cv2.FONT_HERSHEY_DUPLEX,
                font_size, text_color, font_thickness, cv2.LINE_AA)

    if detection_result_list:
        # print(detection_result_list)
        current_frame = visualize(current_frame, detection_result_list[0])
        detection_frame = current_frame
        detection_result_list.clear()

    if detection_frame is not None:
        cv2.imshow('object_detection', detection_frame)

    # Stop the program if the ESC key is pressed.
    if cv2.waitKey(1) == 27:
      break

  detector.close()
  cap.release()
  cv2.destroyAllWindows()
```

[examples/object_detection/raspberry_pi/detect.py](https://github.com/google-ai-edge/mediapipe-samples/blob/46d60d66baf21ae91977c488ea0875f0e13c4d2b/examples/object_detection/raspberry_pi/detect.py) · [More projects using MediaPipe →](https://dashboard.exa.ai/playground/search?q=mediapipe%20GitHub%20projects)

**Quickstart**

```python
import sys, mediapipe as mp
options = mp.tasks.vision.ObjectDetectorOptions(base_options=mp.tasks.BaseOptions(model_asset_path=sys.argv[1]))
with mp.tasks.vision.ObjectDetector.create_from_options(options) as detector:
    print(detector.detect(mp.Image.create_from_file(sys.argv[2])))

```

From [README.md](https://ai.google.dev/edge/mediapipe/solutions/vision/object_detector/python)

### PaddleX

[GitHub](https://github.com/PaddlePaddle/PaddleX) · [PyPI](https://pypi.org/project/paddlex) · [Docs](https://paddlepaddle.github.io/PaddleX/latest/en/pipeline_usage/tutorials/cv_pipelines/object_detection.html)

Develops models with low code on PaddlePaddle.

- Downloads / mo: 1.1M
- Stars: 6.3K
- Last release: 3.7.2
- License: Apache-2.0
- Capabilities: [From the PaddleX docs](https://paddlepaddle.github.io/PaddleX/latest/en/pipeline_usage/tutorials/cv_pipelines/object_detection.html)

```sh
pip install "paddlex[base]==3.7.2" paddlepaddle numpy
```

**Quickstart**

```python
import numpy as np
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="object_detection", device="cpu")
for result in pipeline.predict(np.zeros((640, 640, 3), dtype=np.uint8), threshold=0.5):
    result.print()

```

From [object_detection.md](https://paddlepaddle.github.io/PaddleX/latest/en/pipeline_usage/tutorials/cv_pipelines/object_detection.html) · [Find projects using PaddleX →](https://dashboard.exa.ai/playground/search?q=paddlex%20GitHub%20projects)

### KerasHub

[GitHub](https://github.com/keras-team/keras-hub) · [PyPI](https://pypi.org/project/keras-hub) · [Docs](https://keras.io/keras_hub/api/models/retinanet/retinanet_object_detector/)

Provides pretrained models for Keras.

- Downloads / mo: 471.7K
- Stars: 999
- Last release: 0.33.0
- License: Apache-2.0
- Capabilities: [From the KerasHub docs](https://keras.io/keras_hub/api/models/retinanet/retinanet_object_detector/)

```sh
pip install keras-hub==0.33.0 numpy torch
```

**Quickstart**

```python
import os
os.environ["KERAS_BACKEND"] = "torch"
import numpy as np, keras_hub
detector = keras_hub.models.RetinaNetObjectDetector.from_preset("retinanet_resnet50_fpn_coco")
print(detector.predict(np.zeros((1, 800, 800, 3), dtype=np.uint8)))

```

From [retinanet_object_detector.py](https://keras.io/keras_hub/api/models/retinanet/retinanet_object_detector/) · [Find projects using KerasHub →](https://dashboard.exa.ai/playground/search?q=keras-hub%20GitHub%20projects)

## FAQ

### Which Python object detection library should I use?

[Ultralytics](#ultralytics) suits YOLO models with prediction, training, and export in one interface. [Transformers](#transformers) suits pretrained transformer detectors and prompted detection models. [TorchVision](#torchvision) suits projects already built on PyTorch tensors and training code.

### What is Ultralytics?

[Ultralytics](#ultralytics) is a Python package for YOLO models that covers detection, segmentation, classification, and pose estimation. It loads published checkpoints automatically and runs on CPU or GPU.

### What is ModelScope?

[ModelScope](#modelscope) is a model hub with task pipelines that load a model by ID and return structured results. Its object detection pipeline runs registered detection models on PyTorch.

### How do I detect objects with OpenCV?

[opencv-python-headless](#opencv-python-headless) runs exported detection models through its DNN module, with preprocessing and non-maximum suppression. The application supplies the model files.

### What is MediaPipe?

[MediaPipe](#mediapipe) provides an on-device object detector for still images, video, and live streams, with score and category filters.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python object detection libraries Ultralytics TorchVision Transformers MMDetection code examples",
    "numResults": 5
  }
}
```

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