Skip to main content

A comprehensive toolkit for computer vision and segmentation tasks

Project description

GCPDS Computer Vision Python Kit

A comprehensive toolkit for computer vision and segmentation tasks, developed by the GCPDS Team. This package provides state-of-the-art tools for training, evaluating, and deploying segmentation models with support for various architectures, loss functions, and performance metrics.

๐Ÿš€ Features

  • Segmentation Models: Support for UNet, ResUNet, DeepLabV3Plus, and FCN architectures
  • Multiple Loss Functions: DICE, Cross Entropy, Focal Loss, and Tversky Loss
  • Performance Evaluation: Comprehensive metrics including Dice, Jaccard, Sensitivity, and Specificity
  • Training Pipeline: Complete training workflow with validation and monitoring
  • Data Loading: Efficient data loading utilities for segmentation tasks
  • Experiment Tracking: Integration with Weights & Biases (wandb)
  • Mixed Precision Training: Automatic Mixed Precision (AMP) support for faster training
  • Dataset Management: Built-in Kaggle dataset download and preparation utilities
  • Visualization Tools: Random sample visualization utilities for dataset exploration
  • Memory Management: Efficient memory handling and cleanup utilities

๐Ÿ“‹ Requirements

  • Python >= 3.8
  • PyTorch >= 2.0.0
  • CUDA-compatible GPU (recommended)

๐Ÿ”ง Installation

From PyPI

pip install gcpds-cv-pykit

From Source

git clone https://github.com/UN-GCPDS/gcpds-cv-pykit.git
cd gcpds-cv-pykit
pip install -e .

Development Installation

git clone https://github.com/UN-GCPDS/gcpds-cv-pykit.git
cd gcpds-cv-pykit
pip install -e ".[dev,docs]"

๐Ÿ“ฆ Dependencies

Core Dependencies

  • torch>=2.0.0 - Deep learning framework
  • torchvision>=0.15.0 - Computer vision utilities
  • numpy>=1.21.0 - Numerical computing
  • opencv-python>=4.6.0 - Image processing
  • matplotlib>=3.5.0 - Plotting and visualization
  • wandb>=0.15.0 - Experiment tracking
  • tqdm>=4.64.0 - Progress bars
  • Pillow>=9.0.0 - Image handling
  • scipy>=1.9.0 - Scientific computing
  • pandas>=1.4.0 - Data manipulation
  • kagglehub - Kaggle dataset downloads

Optional Dependencies

  • Development: pytest>=7.0.0, pytest-cov>=4.0.0, black>=22.0.0, flake8>=5.0.0, isort>=5.10.0
  • Documentation: sphinx>=5.0.0, sphinx-rtd-theme>=1.0.0

๐Ÿ—๏ธ Project Structure

gcpds_cv_pykit/
โ”œโ”€โ”€ baseline/
โ”‚   โ”œโ”€โ”€ trainers/           # Training utilities
โ”‚   โ”‚   โ”œโ”€โ”€ trainer.py      # Main training class
โ”‚   โ”‚   โ””โ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ models/             # Model architectures
โ”‚   โ”‚   โ”œโ”€โ”€ UNet.py         # U-Net implementation
โ”‚   โ”‚   โ”œโ”€โ”€ ResUNet.py      # Residual U-Net
โ”‚   โ”‚   โ”œโ”€โ”€ DeepLabV3Plus.py # DeepLab v3+ implementation
โ”‚   โ”‚   โ”œโ”€โ”€ FCN.py          # Fully Convolutional Network
โ”‚   โ”‚   โ””โ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ losses/             # Loss functions
โ”‚   โ”‚   โ”œโ”€โ”€ DICE.py         # DICE loss implementation
โ”‚   โ”‚   โ”œโ”€โ”€ CrossEntropy.py # Cross entropy loss
โ”‚   โ”‚   โ”œโ”€โ”€ Focal.py        # Focal loss implementation
โ”‚   โ”‚   โ”œโ”€โ”€ Tversky.py      # Tversky loss implementation
โ”‚   โ”‚   โ””โ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ dataloaders/        # Data loading utilities
โ”‚   โ”‚   โ”œโ”€โ”€ dataloader.py   # Custom data loading implementations
โ”‚   โ”‚   โ””โ”€โ”€ __init__.py
โ”‚   โ””โ”€โ”€ performance_model.py # Model evaluation and performance metrics
โ”œโ”€โ”€ crowd/                  # Crowd-specific implementations (under development)
โ”œโ”€โ”€ datasets/               # Dataset utilities and Kaggle integration
โ”‚   โ”œโ”€โ”€ datasets.py         # Kaggle dataset download and preparation
โ”‚   โ””โ”€โ”€ __init__.py
โ”œโ”€โ”€ visuals/               # Visualization tools
โ”‚   โ”œโ”€โ”€ random_sample_visualizations.py  # Dataset visualization utilities
โ”‚   โ””โ”€โ”€ __init__.py
โ”œโ”€โ”€ _version.py            # Version information
โ””โ”€โ”€ __init__.py

๐Ÿš€ Quick Start

Dataset Download and Preparation

from gcpds_cv_pykit.datasets import download_and_prepare_dataset

# Download a Kaggle dataset
dataset_path = download_and_prepare_dataset('username/dataset-name/versions/1')
print(f"Dataset prepared at: {dataset_path}")

Dataset Visualization

from gcpds_cv_pykit.visuals import random_sample_visualization
from torch.utils.data import DataLoader

# Visualize random samples from your dataset
random_sample_visualization(
    dataset=your_dataloader,
    num_classes=2,
    single_class=None,  # Show all classes
    max_classes_to_show=7,
    type="baseline"
)

Model Training

from gcpds_cv_pykit.baseline.trainers import Trainer
from gcpds_cv_pykit.baseline.models import UNet

# Initialize model
model = UNet(in_channels=3, out_channels=2, pretrained=True)

# Configure training
config = {
    'Device': 'cuda',
    'Loss Function': 'DICE',
    'Number of classes': 2,
    'Learning Rate': 0.001,
    'Epochs': 100,
    'Batch Size': 8,
    # ... other configuration parameters
}

# Initialize trainer
trainer = Trainer(
    model=model,
    train_dataset=train_dataloader,
    val_dataset=val_dataloader,
    config=config
)

# Start training
trainer.train()

Model Performance Evaluation

from gcpds_cv_pykit.baseline import PerformanceModels

# Evaluate trained model
config = {
    'Device': 'cuda',
    'Loss Function': 'DICE',
    'Number of classes': 2,
    # ... other configuration parameters
}

evaluator = PerformanceModels(
    model=trained_model,
    test_dataset=test_dataloader,
    config=config
)

๐Ÿ“Š Supported Models

The toolkit provides several state-of-the-art segmentation model architectures, all with ResNet34 backbone support:

UNet

  • Architecture: Classic U-Net with ResNet34 encoder
  • Features:
    • Skip connections for precise localization
    • Pretrained ResNet34 backbone support
    • Configurable encoder/decoder channels
    • Optional final activation functions (sigmoid, softmax, tanh)
    • Bilinear interpolation for upsampling
  • Use Case: General-purpose segmentation tasks

ResUNet

  • Architecture: Residual U-Net with ResNet34 backbone
  • Features:
    • Enhanced skip connections with residual blocks
    • ResNet34 pretrained encoder
    • Improved gradient flow through residual connections
    • Batch normalization and ReLU activations
  • Use Case: Complex segmentation tasks requiring deeper feature learning

DeepLabV3Plus

  • Architecture: DeepLab v3+ with Atrous Spatial Pyramid Pooling (ASPP)
  • Features:
    • ASPP module for multi-scale feature extraction
    • Separable convolutions for efficiency
    • ResNet34 backbone with dilated convolutions
    • Low-level feature fusion
    • Configurable atrous rates
  • Use Case: High-resolution segmentation with multi-scale context

FCN (Fully Convolutional Network)

  • Architecture: FCN with ResNet34 backbone
  • Features:
    • Multi-scale skip connections (FCN-8s, FCN-16s, FCN-32s style)
    • Transposed convolutions for upsampling
    • ResNet34 pretrained encoder
    • Feature fusion at multiple scales
  • Use Case: Semantic segmentation with multi-scale feature integration

Common Model Features

  • Backbone: ResNet34 with ImageNet pretrained weights
  • Input Channels: Configurable (default: 3 for RGB)
  • Output Channels: Configurable number of classes
  • Activation Functions: Support for sigmoid, softmax, tanh, or none
  • Mixed Precision: Compatible with AMP training
  • Memory Efficient: Optimized for GPU memory usage

Model Usage Example

from gcpds_cv_pykit.baseline.models import UNet, ResUNet, DeepLabV3Plus, FCN

# UNet with default settings
model = UNet(
    in_channels=3,
    out_channels=2,  # Binary segmentation
    pretrained=True,
    final_activation='sigmoid'
)

# DeepLabV3Plus for multi-class segmentation
model = DeepLabV3Plus(
    in_channels=3,
    out_channels=5,  # 5-class segmentation
    pretrained=True,
    final_activation='softmax'
)

# ResUNet for complex segmentation
model = ResUNet(
    in_channels=3,
    out_channels=1,
    pretrained=True
)

# FCN for semantic segmentation
model = FCN(
    in_channels=3,
    out_channels=10,
    pretrained=True,
    final_activation='softmax'
)

๐ŸŽฏ Loss Functions

The following loss functions are available through the baseline.losses module:

  • DICE Loss: Optimized for segmentation tasks with class imbalance
  • Cross Entropy: Standard classification loss for multi-class segmentation
  • Focal Loss: Addresses class imbalance by focusing on hard examples
  • Tversky Loss: Generalization of Dice loss with configurable precision/recall balance

Loss Function Usage

from gcpds_cv_pykit.baseline.losses import DICELoss, CrossEntropyLoss, FocalLoss, TverskyLoss

# DICE Loss for binary segmentation
dice_loss = DICELoss()

# Cross Entropy for multi-class segmentation
ce_loss = CrossEntropyLoss()

# Focal Loss for handling class imbalance
focal_loss = FocalLoss(alpha=0.25, gamma=2.0)

# Tversky Loss with custom alpha/beta
tversky_loss = TverskyLoss(alpha=0.3, beta=0.7)

๐Ÿ“ˆ Metrics

The toolkit provides comprehensive evaluation metrics through the PerformanceModels class:

  • Dice Coefficient: Overlap-based similarity measure
  • Jaccard Index (IoU): Intersection over Union
  • Sensitivity (Recall): True positive rate
  • Specificity: True negative rate

All metrics are calculated both globally and per-class with detailed statistical analysis.

๐Ÿ”ง Configuration

The toolkit uses dictionary-based configuration. Key parameters include:

config = {
    # Model Configuration
    'Model': 'UNet',
    'Backbone': 'resnet34',
    'Pretrained': True,
    'Number of classes': 2,
    'Input size': [3, 256, 256],
    
    # Training Configuration
    'Loss Function': 'DICE',
    'Optimizer': 'Adam',
    'Learning Rate': 0.001,
    'Epochs': 100,
    'Batch Size': 8,
    
    # Advanced Options
    'AMP': True,  # Automatic Mixed Precision
    'Device': 'cuda',
    'Wandb monitoring': ['api_key', 'project_name', 'run_name']
}

๐Ÿ“Š Experiment Tracking

Integration with Weights & Biases for experiment tracking:

config['Wandb monitoring'] = [
    'your_wandb_api_key',
    'your_project_name',
    'experiment_name'
]

๐ŸŽจ Visualization

Built-in visualization tools for:

  • Random dataset sample visualization
  • Multi-class segmentation mask display
  • Training/validation curves (through wandb integration)
  • Model predictions vs ground truth

Example usage:

from gcpds_cv_pykit.visuals import random_sample_visualization

# Visualize a single class
random_sample_visualization(
    dataset=dataloader,
    num_classes=5,
    single_class=1,  # Show only class 1
    type="baseline"
)

# Visualize multiple classes
random_sample_visualization(
    dataset=dataloader,
    num_classes=5,
    max_classes_to_show=3,
    type="baseline"
)

๐Ÿงช Testing

Run the test suite:

# Run all tests
pytest

# Run with coverage
pytest --cov=gcpds_cv_pykit

# Run specific test file
pytest tests/test_models.py

๐Ÿ“š Documentation

Build documentation locally:

cd docs
make html

๐Ÿค Contributing

We welcome contributions! Please follow these steps:

  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

Development Setup

# Clone the repository
git clone https://github.com/UN-GCPDS/gcpds-cv-pykit.git
cd gcpds-cv-pykit

# Install in development mode
pip install -e ".[dev]"

# Run code formatting
black gcpds_cv_pykit/
isort gcpds_cv_pykit/

# Run linting
flake8 gcpds_cv_pykit/

๐Ÿ“„ License

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

๐Ÿ‘ฅ Authors

๐Ÿ™ Acknowledgments

  • PyTorch team for the excellent deep learning framework
  • The computer vision community for inspiration and best practices
  • Kaggle for providing accessible datasets through kagglehub
  • Contributors and users of this toolkit

๐Ÿ“ž Support


Note: This project is actively maintained and regularly updated. The API is stable for the current feature set. Please check the documentation and changelog for the latest updates and new features.

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

gcpds-cv-pykit-0.1.0.61.tar.gz (56.2 kB view details)

Uploaded Source

Built Distribution

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

gcpds_cv_pykit-0.1.0.61-py3-none-any.whl (66.8 kB view details)

Uploaded Python 3

File details

Details for the file gcpds-cv-pykit-0.1.0.61.tar.gz.

File metadata

  • Download URL: gcpds-cv-pykit-0.1.0.61.tar.gz
  • Upload date:
  • Size: 56.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for gcpds-cv-pykit-0.1.0.61.tar.gz
Algorithm Hash digest
SHA256 551df39f9f8f538a49abd55833cff3cb341be574ba2bbb1da520c3d918005139
MD5 a1a6732fb9d5e7c97b24954249ed380e
BLAKE2b-256 26fba7d42cf0b1f88126177c31bb15c9b9081bd684fee1b9e8b74fe8b05f9778

See more details on using hashes here.

File details

Details for the file gcpds_cv_pykit-0.1.0.61-py3-none-any.whl.

File metadata

File hashes

Hashes for gcpds_cv_pykit-0.1.0.61-py3-none-any.whl
Algorithm Hash digest
SHA256 86af4f1fc3edc0d554087561d36ef9d33c9e34f2429e992e967cc6e23f78ebbe
MD5 c9fceccd05ba48d56c6865a0d6fc9239
BLAKE2b-256 b6bd02a2cde664ead2b0b2dccfef1d7aeaf929d524ddfc460fd98efd70ca1517

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