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 frameworktorchvision>=0.15.0- Computer vision utilitiesnumpy>=1.21.0- Numerical computingopencv-python>=4.6.0- Image processingmatplotlib>=3.5.0- Plotting and visualizationwandb>=0.15.0- Experiment trackingtqdm>=4.64.0- Progress barsPillow>=9.0.0- Image handlingscipy>=1.9.0- Scientific computingpandas>=1.4.0- Data manipulationkagglehub- 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:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- GCPDS Team - gcpds_man@unal.edu.co
๐ 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
- Issues: GitHub Issues
- Documentation: Read the Docs
- Email: gcpds_man@unal.edu.co
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gcpds-cv-pykit-0.1.0.47.tar.gz.
File metadata
- Download URL: gcpds-cv-pykit-0.1.0.47.tar.gz
- Upload date:
- Size: 54.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2b01f0a5a0bc79b82c2a0f704cf764a33b49073c6e050b2218eb89eeb6fb5616
|
|
| MD5 |
b0e943a4ecb2aedf2fe2d59f27e17ff5
|
|
| BLAKE2b-256 |
a94911ef9ae159cb80da8f8462f6c65010b3dfeae43ef214b63e28f03c7b826c
|
File details
Details for the file gcpds_cv_pykit-0.1.0.47-py3-none-any.whl.
File metadata
- Download URL: gcpds_cv_pykit-0.1.0.47-py3-none-any.whl
- Upload date:
- Size: 62.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7afdce6201fd4bc5769ce1e74b27b599f7bcdd52691230c05da95c14aae850fa
|
|
| MD5 |
21269062d9383e2e4d5f817cc516e736
|
|
| BLAKE2b-256 |
eb80eca0cb2cf5f252fd951a47d91977505c0d71cb1b86525b2d61b8220025e8
|