Skip to main content

Production-ready zero-shot object detection and segmentation toolkit

Project description

Perceptra Zero-Shot

Python 3.8+ License: MIT

A production-ready toolkit for zero-shot object detection and segmentation using state-of-the-art vision-language models.

๐Ÿš€ Features

  • Unified Interface: Single API for multiple zero-shot detection models
  • Multiple Models: OWL-ViT v2, Grounding DINO, and extensible architecture
  • Production Ready: Robust error handling, type hints, comprehensive docs
  • Three Ways to Use:
    • ๐Ÿ Python Package
    • ๐Ÿ–ฅ๏ธ Command Line Interface (CLI)
    • ๐ŸŒ REST API Server
  • Flexible Output: Dict, COCO format, custom serialization
  • Visualization Tools: Built-in result visualization
  • Batch Processing: Efficient multi-image inference

๐Ÿ“ฆ Installation

Basic Installation

pip install perceptra-zero-shot

With Optional Dependencies

# For CLI support
pip install perceptra-zero-shot[cli]

# For API server
pip install perceptra-zero-shot[api]

# For visualization
pip install perceptra-zero-shot[viz]

# Install everything
pip install perceptra-zero-shot[all]

From Source

git clone https://github.com/tannousgeagea/perceptra-zero-shot.git
cd perceptra-zero-shot
pip install -e .

๐ŸŽฏ Quick Start

Python Package

from perceptra_zero_shot import ZeroShotDetector
from PIL import Image

# Initialize detector
detector = ZeroShotDetector(model_name="owlv2-base", device="cuda")

# Load image
image = Image.open("photo.jpg")

# Detect objects
result = detector.detect(
    image=image,
    prompts=["cat", "dog", "person"],
    confidence_threshold=0.3
)

# Print results
print(f"Found {len(result)} objects")
for box in result.boxes:
    print(f"{box.label}: {box.confidence:.2f} at {box.to_xyxy()}")

Command Line Interface

# Detect objects in an image
perceptra detect image.jpg person car dog --model owlv2-base --output result.jpg

# Batch process a directory
perceptra detect-batch images/ person car --pattern "*.jpg" --output-dir results/

# List available models
perceptra list-models

# Start API server
perceptra serve --port 8000

REST API

Start the server:

perceptra serve --port 8000

Use the API:

import requests

url = "http://localhost:8000/detect"
files = {"file": open("image.jpg", "rb")}
data = {"prompts": "person,car,dog"}

response = requests.post(url, files=files, data=data)
print(response.json())

Or with curl:

curl -X POST "http://localhost:8000/detect" \
     -F "file=@image.jpg" \
     -F "prompts=person,car,dog"

API Documentation available at: http://localhost:8000/docs

๐Ÿค– Supported Models

Model Name Description
OWL-ViT v2 Base owlv2-base Fast, accurate zero-shot detection
OWL-ViT v2 Large owlv2-large Higher accuracy, slower
Grounding DINO grounding-dino State-of-the-art open-vocabulary
Grounding DINO Tiny grounding-dino-tiny Faster, lightweight
from perceptra_zero_shot import ModelRegistry

# List all available models
print(ModelRegistry.list_models())

๐Ÿ“– Advanced Usage

Batch Processing

from perceptra_zero_shot import ZeroShotDetector

detector = ZeroShotDetector("owlv2-base")

# Process multiple images
results = detector.detect_batch(
    images=["img1.jpg", "img2.jpg", "img3.jpg"],
    prompts=["car", "truck", "bus"]
)

for i, result in enumerate(results):
    print(f"Image {i}: {len(result)} detections")

Filtering and Post-Processing

# Filter by confidence
high_conf = result.filter_by_confidence(0.5)

# Filter by specific labels
cars_only = result.filter_by_label(["car"])

# Apply Non-Maximum Suppression
result_nms = result.apply_nms(iou_threshold=0.5)

# Get boxes for specific label
car_boxes = result.get_boxes_by_label("car")

Visualization

from perceptra_zero_shot.utils import visualize_detections

# Visualize results
vis_image = visualize_detections(
    image=image,
    result=result,
    show_labels=True,
    show_confidence=True,
    output_path="output.jpg"
)

Export Formats

# Export as dictionary
data = result.to_dict()

# Export as COCO format
coco_annotations = result.to_coco_format()

# Individual box formats
for box in result.boxes:
    xyxy = box.to_xyxy()      # [x_min, y_min, x_max, y_max]
    xywh = box.to_xywh()      # [x_min, y_min, width, height]
    cxcywh = box.to_cxcywh()  # [center_x, center_y, width, height]

Custom Model Parameters

# OWLv2 with custom settings
detector = ZeroShotDetector(
    model_name="owlv2-base",
    confidence_threshold=0.4,
    device="cuda"
)

# Grounding DINO with custom thresholds
detector = ZeroShotDetector(
    model_name="grounding-dino",
    confidence_threshold=0.3,
    box_threshold=0.25,
    text_threshold=0.25
)

๐Ÿ—๏ธ Architecture

perceptra-zero-shot/
โ”œโ”€โ”€ perceptra_zero_shot/
โ”‚   โ”œโ”€โ”€ core/              # Core detection logic
โ”‚   โ”‚   โ”œโ”€โ”€ detector.py    # Main ZeroShotDetector class
โ”‚   โ”‚   โ””โ”€โ”€ result.py      # DetectionResult & BoundingBox
โ”‚   โ”œโ”€โ”€ models/            # Model implementations
โ”‚   โ”‚   โ”œโ”€โ”€ base.py        # Abstract base class
โ”‚   โ”‚   โ”œโ”€โ”€ registry.py    # Model registry
โ”‚   โ”‚   โ”œโ”€โ”€ owlv2.py      # OWL-ViT v2
โ”‚   โ”‚   โ””โ”€โ”€ grounding_dino.py  # Grounding DINO
โ”‚   โ”œโ”€โ”€ utils/             # Utility functions
โ”‚   โ”œโ”€โ”€ api/               # FastAPI REST API
โ”‚   โ””โ”€โ”€ cli/               # Command-line interface
โ”œโ”€โ”€ examples/              # Usage examples
โ””โ”€โ”€ tests/                 # Unit tests

๐Ÿ“Š API Reference

ZeroShotDetector

Main interface for zero-shot object detection.

detector = ZeroShotDetector(
    model_name: str = "owlv2-base",
    device: Optional[str] = None,
    confidence_threshold: float = 0.3,
    **model_kwargs
)

Methods:

  • detect(image, prompts, **kwargs) โ†’ DetectionResult
  • detect_batch(images, prompts, **kwargs) โ†’ List[DetectionResult]
  • to(device) โ†’ ZeroShotDetector

DetectionResult

Container for detection results.

Properties:

  • boxes: List[BoundingBox]
  • image_size: tuple
  • model_name: str
  • inference_time: float

Methods:

  • filter_by_confidence(threshold) โ†’ DetectionResult
  • filter_by_label(labels) โ†’ DetectionResult
  • apply_nms(iou_threshold) โ†’ DetectionResult
  • to_dict() โ†’ dict
  • to_coco_format() โ†’ List[dict]

BoundingBox

Represents a detected object.

Properties:

  • x_min, y_min, x_max, y_max: float
  • confidence: float
  • label: str
  • width, height, area: float
  • center: tuple

Methods:

  • to_xyxy() โ†’ List[float]
  • to_xywh() โ†’ List[float]
  • to_cxcywh() โ†’ List[float]
  • iou(other) โ†’ float

๐Ÿ”ง Development

Setup Development Environment

git clone https://github.com/tannousgeagea/perceptra-zero-shot.git
cd perceptra-zero-shot
pip install -e ".[dev]"

Run Tests

pytest tests/ -v --cov=perceptra_zero_shot

Code Formatting

black perceptra_zero_shot/
isort perceptra_zero_shot/
flake8 perceptra_zero_shot/

๐ŸŽ“ Examples

See the examples/ directory for complete examples:

  • basic_detection.py - Simple detection example
  • batch_processing.py - Process multiple images
  • api_usage.py - Using the REST API
  • compare_models.py - Compare different models

๐Ÿ“ Requirements

  • Python โ‰ฅ 3.8
  • PyTorch โ‰ฅ 2.0.0
  • Transformers โ‰ฅ 4.30.0
  • PIL/Pillow โ‰ฅ 9.0.0
  • NumPy โ‰ฅ 1.21.0

๐Ÿค Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • OWL-ViT v2 by Google Research
  • Grounding DINO by IDEA-Research
  • Hugging Face Transformers library

๐Ÿ“š Citation

@software{perceptra2025,
  title = {Perceptra Zero-Shot: Production-Ready Zero-Shot Object Detection},
  author = {Perceptra Team},
  year = {2025},
  url = {https://github.com/tannousgeagea/perceptra-zero-shot}
}

๐Ÿ“ง Support


Made with โค๏ธ by the Perceptra Team

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

perceptra_zero_shot-0.1.0.tar.gz (29.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

perceptra_zero_shot-0.1.0-py3-none-any.whl (30.5 kB view details)

Uploaded Python 3

File details

Details for the file perceptra_zero_shot-0.1.0.tar.gz.

File metadata

  • Download URL: perceptra_zero_shot-0.1.0.tar.gz
  • Upload date:
  • Size: 29.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for perceptra_zero_shot-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ebdd8a94ba0ed6ca7c04b3556844bfce623ba74a5de1d66375b63c6de56951bb
MD5 36555bc3a9220a3130b7a8dda0a5aa02
BLAKE2b-256 a7d12c87aab72afc92e2e713ba06086e689b0712800d8078f0ea196313675976

See more details on using hashes here.

File details

Details for the file perceptra_zero_shot-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for perceptra_zero_shot-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 751d019c6082cc6f015116203374af27e8c1d7484c9a3cae4d1184dce7bf7bcd
MD5 b5bdd565b53399915048d6c4e616beba
BLAKE2b-256 56d7c5e82e8d5cd78da331ba6c18995fe1bacb21d58fc822ab0a83ed582831f0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page