DeepForest

repository·main·Indexed 20 days ago

https://github.com/weecology/deepforest

A Python package for training and predicting ecological objects, such as tree crowns, birds, and livestock, in airborne RGB imagery using deep learning object detection. Built on the torchvision object detection module, it provides prebuilt models and supports fine-tuning for specific ecosystems. DeepForest supports distributed execution on Slurm clusters and integrates with ArcGIS Pro via the Tree Crown Delineation Tool and QGIS via the TreeEyed plugin.

Tokens
49.4K
Snippets
167
Records
217
Agent score
73%

What's inside deepforest

  1. Overview of the deepforest package structure

    main

    The deepforest package is organized into several subpackages and modules designed for tree detection and analysis.

    Core Subpackages:

    • deepforest.data: Handles data management.
    • deepforest.datasets: Manages dataset loading and structures.

    Key Functional Modules:

    • deepforest.model: Contains model definitions and architectures.
    • deepforest.predict: Provides tools for running inference/predictions on images.
    • deepforest.preprocess: Includes functions for preparing images and data before processing.
    • deepforest.evaluate: Tools for assessing model performance.
    • deepforest.visualize: Utilities for visualizing detections and results.
    • deepforest.IoU: Implementation of Intersection over Union (IoU) metrics.
    • deepforest.callbacks: Support for training callbacks.
    • deepforest.utilities: General helper functions.
    • deepforest.main: Entry points for the package.
  2. What is DeepForest?

    main

    DeepForest is a Python package designed for training and predicting ecological objects in airborne imagery. It utilizes deep learning object detection networks to predict bounding boxes for individual organisms in RGB imagery.

    Key features include:

    • Prebuilt Models: Includes a tree crown object detection model and a bird detection model.
    • Extensibility: Both models are single-class modules that can be extended to species classification by annotating new data and training custom models.
    • Foundation: Built on the torchvision object detection module to simplify the training process for ecological detection tasks.
  3. Introduction to DeepForest

    main

    DeepForest is a Python package designed for training and predicting ecological objects in airborne imagery. It supports airborne object detection and classification tasks, such as tree crown detection and bird detection.

    Key capabilities include:

    • Immediate Use: Use prebuilt models for standard ecological object detection.
    • Customization: Fine-tune models by annotating and training on your own specific datasets.
  4. Ensure custom models match torchvision input and output formats

    main

    When implementing a custom model, you must adhere to specific tensor shapes and dictionary keys to remain compatible with DeepForest's training and inference pipelines.

    Input Format

    • Batch of images: The model must accept a list or batch of tensors in the format [channels, height, width].
    • Channels: Standard models are trained on 3-band images, though check_model can be customized for other dimensions.

    Output Format (Inference)

    During inference, the model must return a List[Dict[Tensor]] (one dictionary per input image). Each dictionary must contain the following keys:

    • boxes (FloatTensor[N, 4]): Predicted boxes in [x1, y1, x2, y2] format, where 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.
    • labels (Int64Tensor[N]): The predicted class labels for each detection.
    • scores (Tensor[N]): The confidence scores for each detection.

    Input Format (Training)

    During training, the model expects both input tensors and a list of target dictionaries containing:

    • boxes (FloatTensor[N, 4]): Ground-truth boxes in [x1, y1, x2, y2] format.
    • labels (Int64Tensor[N]): Class labels for each ground-truth box.
  5. Use CropModel for post-detection classification

    main

    The CropModel allows you to apply a secondary classification model to the bounding boxes predicted by an object detection model (like the 'tree' or 'bird' backbones). This decouples detection from classification, which is useful when you have detailed labels (like species or health) for only a subset of detected objects.

    When using predict_tile or predict_image with a CropModel, the resulting DataFrame will include new columns: cropmodel_label and cropmodel_score alongside the original detection columns.

    import pandas as pd
    from deepforest import model
    from deepforest import main as m
    from deepforest.utilities import get_data
    
    # Load data
    df = pd.read_csv(get_data("testfile_multi.csv"))
    
    # Initialize CropModel
    crop_model = model.CropModel(num_classes=2)
    # Or load existing weights: crop_model = model.CropModel.load_from_checkpoint(<path>)
    
    m.create_trainer()
    result = m.predict_tile(path=path, crop_model=crop_model)
  6. Configure the dataloader-strategy for predict_tile

    main

    The dataloader_strategy parameter in predict_tile allows you to balance memory usage and speed:

    • single: Loads the entire image into CPU memory and passes individual windows to the GPU.
    • batch: Loads the entire image into GPU memory and creates views as batches. This is fast but requires the entire tile to fit in GPU memory.
    • window: Loads only the specific window required from the raster dataset. This is the most memory-efficient option but cannot be parallelized across windows (workers must be set to 0).
    prediction_single = m.predict_tile(path=path, patch_size=300, dataloader_strategy="single")
  7. How DeepForest works

    main
    DeepForest leverages deep learning to identify ecological objects (like trees) in high-resolution RGB imagery. It specifically predicts bounding boxes that correspond to individual tree crowns. The underlying architecture is based on the torchvision object detection framework, optimized to make the training of custom detection models more accessible for ecological research.
  8. Understand the DeepForest data model

    main

    The DeepForest data model is designed to facilitate tree detection and analysis using four core components:

    1. Annotations as Dataframes: Annotations are stored in GeoPandas dataframes. Each row represents a single annotation with one geometry and one label. Every dataframe must include an image_path column (containing the basename of the image, not the full path) and a label column.
    2. Shapely Geometries: Annotation geometry is stored as shapely objects, which allows for seamless conversion between Point, Polygon, and Box representations.
    3. Image Coordinates: All annotations are expressed in image coordinates (pixels) rather than geographic coordinates. DeepForest provides utilities to convert geospatial data (like .shp or .gpkg) into this image-coordinate format.
    4. Root Directory: A root_dir attribute is attached to the dataframe to specify the directory where the actual image files are stored.
  9. Understand DeepForest evaluation metrics

    main

    DeepForest provides several metrics to assess model performance:

    • Recall: Proportion of ground-truth objects correctly covered by predictions.
    • Precision: Proportion of predictions that overlap ground-truth.
    • Empty-frame accuracy: Proportion of ground-truth images predicted to have no objects. To use this, set xmin, ymin, xmax, ymax to 0 in your ground truth CSV.
    • Average Intersection over Union (IoU): Measures the average overlap between predictions and ground truth boxes.
    • Mean-Average-Precision (mAP): The standard COCO metric. It is a summary statistic representing the area under the precision-recall curve across various IoU thresholds.
    • Precision and Recall at a set IoU threshold: An intuitive metric for ecological tasks (e.g., IoU > 0.4) that uses Hungarian matching to assign predictions to ground truth.
  10. Understand Lightning vs. Hugging Face checkpoints

    main

    DeepForest uses two distinct checkpoint formats:

    1. Lightning Checkpoints (.ckpt): A full snapshot of the training state used to resume or continue training. Access these via main.deepforest.save_checkpoint and main.deepforest.load_from_checkpoint.
    2. Hugging Face Hub Checkpoints: The preferred format for distribution. These contain only the weights and a JSON config file. Access these via model.save_pretrained and model.load_pretrained on the model instance (e.g., main.deepforest.model).