Upload inference script and README model card
Browse files- README.md +93 -0
- treelens_ortho_inference.py +503 -0
README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# TreeLens Detectron2 Tree Detection Model
|
| 3 |
+
|
| 4 |
+
This repository hosts the **TreeLens** tree detection model, built on **Detectron2** and integrated with the **SAHI (Slicing Aided Hyper Inference)** library. It is designed to detect and map tree crowns in high-resolution aerial orthomosaics and estimate tree biophysical parameters like crown width, height, and biomass (using digital elevation models).
|
| 5 |
+
|
| 6 |
+
Developed by **Farmers for Forests**, this model is optimized to work with SAHI sliced inference.
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
## 🚀 How to Run the Inference Script
|
| 11 |
+
|
| 12 |
+
This guide explains how to run the `treelens_ortho_inference.py` script step-by-step. The script is structured with `# %%` cell markers, meaning you can easily open it in Google Colab (by renaming it to `.ipynb` or uploading it directly) or run it in VS Code as interactive cells.
|
| 13 |
+
|
| 14 |
+
### Step 1: Upload and Organize Your Files
|
| 15 |
+
1. Place your orthomosaic (`.tif` format) and digital elevation model (`.tif` format) in your Google Drive.
|
| 16 |
+
2. By default, the script looks for your files at:
|
| 17 |
+
- **Orthomosaic:** `/content/drive/MyDrive/test.tif`
|
| 18 |
+
- **DEM (Elevation):** `/content/drive/MyDrive/test.tif`
|
| 19 |
+
- **Output Directory:** `/content/drive/MyDrive`
|
| 20 |
+
*(If you want to use different paths, edit lines 6 to 11 in **Cell 2** of the script).*
|
| 21 |
+
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
### Step 2: Open and Run the Script in Google Colab
|
| 25 |
+
You can run this code by uploading the script to a Google Colab notebook:
|
| 26 |
+
|
| 27 |
+
#### **Cell 1: Mount Google Drive**
|
| 28 |
+
This cell links your Google Drive to the runtime environment to access your orthomosaic and DEM images.
|
| 29 |
+
```python
|
| 30 |
+
from google.colab import drive
|
| 31 |
+
drive.mount('/content/drive')
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
#### **Cell 2: Setup Paths and Parameters**
|
| 35 |
+
Define your file inputs, output folder, confidence threshold, and average tree crown width.
|
| 36 |
+
* `aveg_width = 13` The script will automatically calculate the best slicing patch size based on this width and the ground resolution (GSD) of your `.tif. aveg_width/GSD=sahi slice size (pixel)
|
| 37 |
+
|
| 38 |
+
#### **Cell 3: Download Model Files from Hugging Face**
|
| 39 |
+
Downloads the Detectron2 weights (`Treelens_model.pth`) and the training configuration (`config.yaml`) from the Hugging Face hub automatically.
|
| 40 |
+
```python
|
| 41 |
+
repo_id = "farmersforforests/TreeLens-detectron2"
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
#### **Cell 4 & 5: Install Dependencies & Import Libraries**
|
| 45 |
+
Installs and imports the core packages:
|
| 46 |
+
* `sahi` (Sliced Inference framework)
|
| 47 |
+
* `detectron2` (Object Detection engine)
|
| 48 |
+
* `rasterio` (Geospatial metadata & projection parser)
|
| 49 |
+
* `scipy` & `pycocotools`
|
| 50 |
+
|
| 51 |
+
#### **Cell 6: Load Helper Functions**
|
| 52 |
+
Executes function definitions for:
|
| 53 |
+
* Geocoding coordinates (pixels to Latitude & Longitude)
|
| 54 |
+
* Outputting Pascal VOC XML and COCO JSON formats
|
| 55 |
+
* Extracting GSD resolution and calculating tree heights from the DEM
|
| 56 |
+
|
| 57 |
+
#### **Cell 7: Initialize Model**
|
| 58 |
+
Loads the Detectron2 model onto your GPU (`cuda:0`).
|
| 59 |
+
* *Note: Make sure your Colab notebook is set to a GPU hardware accelerator (Runtime > Change runtime type > GPU).*
|
| 60 |
+
|
| 61 |
+
#### **Cell 8 & 9: Run Inference & Save Results**
|
| 62 |
+
Processes the orthomosaics, runs sliced inference, plots predictions, and saves the output logs.
|
| 63 |
+
|
| 64 |
+
---
|
| 65 |
+
|
| 66 |
+
## 📂 Outputs Generated
|
| 67 |
+
Once the script runs successfully, the following files will be saved in your `save_dir` (Google Drive root by default):
|
| 68 |
+
1. **`{basename}_pred.png`**: The orthomosaic image with visual bounding boxes drawn around all detected trees.
|
| 69 |
+
2. **`{basename}.xml`**: Standard Pascal VOC XML annotation file.
|
| 70 |
+
3. **`{basename}.json`**: Standard COCO JSON annotation file.
|
| 71 |
+
4. **`{basename}_pred.csv`**: A spreadsheet with:
|
| 72 |
+
- Target bounding box pixel coordinates (`xmin`, `ymin`, `xmax`, `ymax`).
|
| 73 |
+
- Spatial coordinates of each tree center (`lon`, `lat`).
|
| 74 |
+
- Calculated `Crown (m)` width of each tree.
|
| 75 |
+
5. **`{basename}_pred_with_heights.csv`**: Same as above, updated with `Height (m)` for each tree derived from the DEM file.
|
| 76 |
+
6. **`{basename}_pred_with_biomass.csv`**: (Optional) Estimates DBH (cm) and AGB (Above Ground Biomass in kg) for each tree. To enable this, set `calculate_biomass = True` in Cell 9.
|
| 77 |
+
|
| 78 |
+
---
|
| 79 |
+
|
| 80 |
+
## 🛠️ Local Terminal/CLI Execution (Optional)
|
| 81 |
+
If you wish to run this script outside of Colab (e.g. locally in a terminal):
|
| 82 |
+
1. Install Python 3.8+ and install all dependencies:
|
| 83 |
+
```bash
|
| 84 |
+
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118
|
| 85 |
+
python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'
|
| 86 |
+
pip install -U sahi huggingface_hub rasterio scipy pycocotools pandas matplotlib pillow
|
| 87 |
+
```
|
| 88 |
+
2. Comment out Cell 1 (`drive.mount`) in the script.
|
| 89 |
+
3. Update the paths in Cell 2 to point to your local directories.
|
| 90 |
+
4. Execute:
|
| 91 |
+
```bash
|
| 92 |
+
python treelens_ortho_inference.py
|
| 93 |
+
```
|
treelens_ortho_inference.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# %% [markdown]
|
| 2 |
+
# # Cell 1: Mount Google Drive
|
| 3 |
+
# This cell mounts Google Drive to access test TIFF images and save inference output directories.
|
| 4 |
+
# %%
|
| 5 |
+
from google.colab import drive
|
| 6 |
+
drive.mount('/content/drive')
|
| 7 |
+
|
| 8 |
+
# %% [markdown]
|
| 9 |
+
# # Cell 2: Configure Paths and Parameters
|
| 10 |
+
# Define input orthomosaics, DEM path, output save directory, and detection threshold.
|
| 11 |
+
# %%
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
ortho_path = '/content/drive/MyDrive/test.tif'
|
| 15 |
+
dem_path = '/content/drive/MyDrive/test.tif'
|
| 16 |
+
ortho_folder_path = ''
|
| 17 |
+
dem_folder_path = ''
|
| 18 |
+
save_dir = '/content/drive/MyDrive'
|
| 19 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
conf_thresh = 0.7
|
| 22 |
+
plot_ortho = True
|
| 23 |
+
aveg_width = 13
|
| 24 |
+
|
| 25 |
+
# %% [markdown]
|
| 26 |
+
# # Cell 3: Install Hugging Face Hub and Download TreeLens Model
|
| 27 |
+
# Downloads the Detectron2 weights (`Treelens_model.pth`) and configuration (`config.yaml`) from the Hugging Face hub repository.
|
| 28 |
+
# %%
|
| 29 |
+
!pip install huggingface_hub
|
| 30 |
+
from huggingface_hub import snapshot_download
|
| 31 |
+
|
| 32 |
+
repo_id = "farmersforforests/TreeLens-detectron2"
|
| 33 |
+
print(f"Downloading model files from Hugging Face: {repo_id}...")
|
| 34 |
+
model_dir = snapshot_download(repo_id=repo_id)
|
| 35 |
+
|
| 36 |
+
model_path = os.path.join(model_dir, "Treelens_model.pth")
|
| 37 |
+
config_path = os.path.join(model_dir, "config.yaml")
|
| 38 |
+
|
| 39 |
+
# %% [markdown]
|
| 40 |
+
# # Cell 4: Install Core Dependencies
|
| 41 |
+
# Install SAHI (Sliced Aided Hyper Inference) and Detectron2 (Facebook Research object detection engine).
|
| 42 |
+
# %%
|
| 43 |
+
!pip install -U sahi
|
| 44 |
+
!python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'
|
| 45 |
+
|
| 46 |
+
# %% [markdown]
|
| 47 |
+
# # Cell 5: Import Libraries & Settings
|
| 48 |
+
# Import geospatial libraries, image processing, array manipulation, and plotting libraries.
|
| 49 |
+
# %%
|
| 50 |
+
from sahi.predict import get_sliced_prediction, predict, get_prediction
|
| 51 |
+
from sahi import AutoDetectionModel
|
| 52 |
+
|
| 53 |
+
!pip install scipy
|
| 54 |
+
import glob
|
| 55 |
+
import matplotlib.pyplot as plt
|
| 56 |
+
from PIL import Image
|
| 57 |
+
Image.MAX_IMAGE_PIXELS = 13477537680
|
| 58 |
+
import pandas as pd
|
| 59 |
+
import xml.etree.ElementTree as ET
|
| 60 |
+
!pip install rasterio
|
| 61 |
+
import rasterio
|
| 62 |
+
from rasterio.warp import transform as transform_coords
|
| 63 |
+
import numpy as np
|
| 64 |
+
import math
|
| 65 |
+
import json
|
| 66 |
+
from pycocotools.coco import COCO
|
| 67 |
+
import pickle
|
| 68 |
+
from scipy.stats import norm
|
| 69 |
+
|
| 70 |
+
# %% [markdown]
|
| 71 |
+
# # Cell 6: Helper Function Definitions
|
| 72 |
+
# Functions to export SAHI output to VOC XML format, parse VOC XML, convert coordinates to Lon/Lat,
|
| 73 |
+
# read GSD (Ground Sampling Distance), read DEM elevation values, and compute tree heights.
|
| 74 |
+
# %%
|
| 75 |
+
def write_Sahi_results_to_pascalVOCxml(sahi_list, path_to_save_xml, image, filename):
|
| 76 |
+
print(filename + '.xml will be written')
|
| 77 |
+
print(path_to_save_xml)
|
| 78 |
+
|
| 79 |
+
f = open(path_to_save_xml, "w")
|
| 80 |
+
f.writelines("<annotation>" + "\n")
|
| 81 |
+
f.writelines("\t" + "<folder>Orthomosaic</folder>" + "\n")
|
| 82 |
+
f.writelines("\t" + "<filename>" + filename + "</filename>" + '\n')
|
| 83 |
+
f.writelines("\t" + "<path>" + filename + "</path>" + '\n')
|
| 84 |
+
f.writelines("\t" + "<source>" + '\n')
|
| 85 |
+
f.writelines("\t" + "\t" + "<database>Unknown</database>" + '\n')
|
| 86 |
+
f.writelines("\t" + "</source>" + '\n')
|
| 87 |
+
f.writelines("\t" + "<size>" + '\n')
|
| 88 |
+
f.writelines("\t" + "\t" + "<width>" + str(int(image.shape[1])) + "</width>" + '\n')
|
| 89 |
+
f.writelines("\t" + "\t" + "<height>" + str(int(image.shape[0])) + "</height>" + '\n')
|
| 90 |
+
f.writelines("\t" + "\t" + "<depth>3</depth>" + '\n')
|
| 91 |
+
f.writelines("\t" + "</size>" + '\n')
|
| 92 |
+
f.writelines("\t" + "<segmented>0</segmented>" + '\n')
|
| 93 |
+
for annotation in sahi_list:
|
| 94 |
+
x = annotation['bbox'][0]
|
| 95 |
+
y = annotation['bbox'][1]
|
| 96 |
+
width = annotation['bbox'][2]
|
| 97 |
+
height = annotation['bbox'][3]
|
| 98 |
+
f.writelines("\t" + "<object>" + '\n')
|
| 99 |
+
f.writelines("\t" + "\t" + "<name>Tree</name>" + '\n')
|
| 100 |
+
f.writelines("\t" + "\t" + "<pose>Unspecified</pose>" + '\n')
|
| 101 |
+
f.writelines("\t" + "\t" + "<truncated>0</truncated>" + '\n')
|
| 102 |
+
f.writelines("\t" + "\t" + "<difficult>0</difficult>" + '\n')
|
| 103 |
+
f.writelines("\t" + "\t" + "<bndbox>" + '\n')
|
| 104 |
+
f.writelines("\t" + "\t" + "\t" + "<xmin>" + str(x) + "</xmin>" + '\n')
|
| 105 |
+
f.writelines("\t" + "\t" + "\t" + "<ymin>" + str(y) + "</ymin>" + '\n')
|
| 106 |
+
f.writelines("\t" + "\t" + "\t" + "<xmax>" + str(x + width) + "</xmax>" + '\n')
|
| 107 |
+
f.writelines("\t" + "\t" + "\t" + "<ymax>" + str(y + height) + "</ymax>" + '\n')
|
| 108 |
+
f.writelines("\t" + "\t" + "</bndbox>" + '\n')
|
| 109 |
+
f.writelines("\t" + "</object>" + '\n')
|
| 110 |
+
f.writelines("</annotation>")
|
| 111 |
+
f.close()
|
| 112 |
+
return print("Done")
|
| 113 |
+
|
| 114 |
+
def voc_xml_to_df(xml_file):
|
| 115 |
+
tree = ET.parse(xml_file)
|
| 116 |
+
root = tree.getroot()
|
| 117 |
+
|
| 118 |
+
filename = root.find("filename").text
|
| 119 |
+
size = root.find("size")
|
| 120 |
+
width = int(size.find("width").text)
|
| 121 |
+
height = int(size.find("height").text)
|
| 122 |
+
|
| 123 |
+
records = []
|
| 124 |
+
for obj in root.findall("object"):
|
| 125 |
+
label = obj.find("name").text
|
| 126 |
+
bndbox = obj.find("bndbox")
|
| 127 |
+
xmin = float(bndbox.find("xmin").text)
|
| 128 |
+
ymin = float(bndbox.find("ymin").text)
|
| 129 |
+
xmax = float(bndbox.find("xmax").text)
|
| 130 |
+
ymax = float(bndbox.find("ymax").text)
|
| 131 |
+
|
| 132 |
+
records.append({
|
| 133 |
+
"filename": filename,
|
| 134 |
+
"width": width,
|
| 135 |
+
"height": height,
|
| 136 |
+
"label": label,
|
| 137 |
+
"xmin": xmin,
|
| 138 |
+
"ymin": ymin,
|
| 139 |
+
"xmax": xmax,
|
| 140 |
+
"ymax": ymax
|
| 141 |
+
})
|
| 142 |
+
|
| 143 |
+
return pd.DataFrame(records)
|
| 144 |
+
|
| 145 |
+
def GetLonLat(transform, crs, x, y):
|
| 146 |
+
xs, ys = rasterio.transform.xy(transform, y, x, offset='center')
|
| 147 |
+
if crs.is_geographic:
|
| 148 |
+
lon, lat = xs, ys
|
| 149 |
+
else:
|
| 150 |
+
lon, lat = transform_coords(crs, "EPSG:4326", [xs], [ys])
|
| 151 |
+
lon, lat = lon[0], lat[0]
|
| 152 |
+
return lon, lat
|
| 153 |
+
|
| 154 |
+
def GetCrownSize(df, gsd):
|
| 155 |
+
xmin = df.iloc[:,0]
|
| 156 |
+
ymin = df.iloc[:,1]
|
| 157 |
+
xmax = df.iloc[:,2]
|
| 158 |
+
ymax = df.iloc[:,3]
|
| 159 |
+
crown_size = 0.5 * (gsd * (xmax - xmin) + abs(gsd) * (ymax - ymin))
|
| 160 |
+
return crown_size
|
| 161 |
+
|
| 162 |
+
def get_gsd(tiff_path):
|
| 163 |
+
with rasterio.open(tiff_path) as dataset:
|
| 164 |
+
transform = dataset.transform
|
| 165 |
+
crs = dataset.crs
|
| 166 |
+
|
| 167 |
+
gsd_x = abs(transform.a) # Pixel width
|
| 168 |
+
gsd_y = abs(transform.e) # Pixel height
|
| 169 |
+
|
| 170 |
+
if crs and crs.is_geographic: # If CRS is in lat/lon
|
| 171 |
+
# Estimate latitude at the center of the image
|
| 172 |
+
lat_center = dataset.bounds.top - (dataset.height / 2) * gsd_y
|
| 173 |
+
print("In new gsd calculation")
|
| 174 |
+
# Convert degrees to meters
|
| 175 |
+
a = 6378137.0
|
| 176 |
+
b = 6356752.3142
|
| 177 |
+
esq = (a**2 - b**2) / a**2
|
| 178 |
+
long_dist_per_degree = np.pi * a * np.cos(np.radians(lat_center))/(np.sqrt(1 - esq * np.sin(np.radians(lat_center))**2) * 180)
|
| 179 |
+
lat_dist_per_degree = 111132.954 - 559.822 * np.cos( 2.0 * np.radians(lat_center) ) + 1.175 * np.cos( 4.0 * np.radians(lat_center))
|
| 180 |
+
gsd_x_meters = gsd_x * long_dist_per_degree
|
| 181 |
+
gsd_y_meters = gsd_y * lat_dist_per_degree
|
| 182 |
+
|
| 183 |
+
return gsd_x_meters, gsd_y_meters # Return GSD in meters
|
| 184 |
+
|
| 185 |
+
return gsd_x, gsd_y # Already in meters for projected CRS
|
| 186 |
+
|
| 187 |
+
def ReadDEM(dem_file):
|
| 188 |
+
with rasterio.open(dem_file) as dem:
|
| 189 |
+
nodatavalue = dem.nodata
|
| 190 |
+
dem_array = dem.read(1).astype('float64')
|
| 191 |
+
return dem_array, nodatavalue
|
| 192 |
+
|
| 193 |
+
def GetTreeHeight(row, dem_file, image_file, dem_data, padding, middle_frac):
|
| 194 |
+
xmin = row["xmin"]
|
| 195 |
+
ymin = row["ymin"]
|
| 196 |
+
xmax = row["xmax"]
|
| 197 |
+
ymax = row["ymax"]
|
| 198 |
+
|
| 199 |
+
try:
|
| 200 |
+
with rasterio.open(dem_file) as dem:
|
| 201 |
+
with rasterio.open(image_file) as image:
|
| 202 |
+
xdem_min = xmin * (dem.width/image.width)
|
| 203 |
+
ydem_min = ymin * (dem.height/image.height)
|
| 204 |
+
xdem_max = xmax * (dem.width/image.width)
|
| 205 |
+
ydem_max = ymax * (dem.height/image.height)
|
| 206 |
+
|
| 207 |
+
xdem_min_for_min = np.max([0, xdem_min - padding])
|
| 208 |
+
ydem_min_for_min = np.max([0, ydem_min - padding])
|
| 209 |
+
xdem_max_for_min = np.min([dem_data.shape[1], xdem_max + padding])
|
| 210 |
+
ydem_max_for_min = np.min([dem_data.shape[0], ydem_max + padding])
|
| 211 |
+
|
| 212 |
+
xdem_min_for_max = ((xdem_min + xdem_max)/2 - (xdem_max - xdem_min)*middle_frac/2)
|
| 213 |
+
ydem_min_for_max = ((ydem_min + ydem_max)/2 - (ydem_max - ydem_min)*middle_frac/2)
|
| 214 |
+
xdem_max_for_max = ((xdem_min + xdem_max)/2 + (xdem_max - xdem_min)*middle_frac/2)
|
| 215 |
+
ydem_max_for_max = ((ydem_min + ydem_max)/2 + (ydem_max - ydem_min)*middle_frac/2)
|
| 216 |
+
|
| 217 |
+
dem_values_for_max = dem_data[math.floor(ydem_min_for_max):math.ceil(ydem_max_for_max), math.floor(xdem_min_for_min):math.ceil(xdem_max_for_max)]
|
| 218 |
+
dem_values_for_min = dem_data[math.floor(ydem_min_for_min):math.ceil(ydem_max_for_min), math.floor(xdem_min_for_min):math.ceil(xdem_max_for_min)]
|
| 219 |
+
tree_height = np.max(dem_values_for_max) - np.nanmin(dem_values_for_min)
|
| 220 |
+
except:
|
| 221 |
+
tree_height = np.nan
|
| 222 |
+
return tree_height
|
| 223 |
+
|
| 224 |
+
def parse_voc_xml(xml_path):
|
| 225 |
+
"""
|
| 226 |
+
Parse a Pascal VOC XML file and return a dictionary with image info and objects.
|
| 227 |
+
"""
|
| 228 |
+
tree = ET.parse(xml_path)
|
| 229 |
+
root = tree.getroot()
|
| 230 |
+
|
| 231 |
+
filename = root.find('filename').text if root.find('filename') is not None else ""
|
| 232 |
+
size_node = root.find('size')
|
| 233 |
+
width = int(size_node.find('width').text) if size_node is not None else 0
|
| 234 |
+
height = int(size_node.find('height').text) if size_node is not None else 0
|
| 235 |
+
depth = int(size_node.find('depth').text) if size_node is not None else 3
|
| 236 |
+
|
| 237 |
+
objects = []
|
| 238 |
+
for obj in root.findall('object'):
|
| 239 |
+
name = obj.find('name').text
|
| 240 |
+
bndbox = obj.find('bndbox')
|
| 241 |
+
xmin = int(float(bndbox.find('xmin').text))
|
| 242 |
+
ymin = int(float(bndbox.find('ymin').text))
|
| 243 |
+
xmax = int(float(bndbox.find('xmax').text))
|
| 244 |
+
ymax = int(float(bndbox.find('ymax').text))
|
| 245 |
+
objects.append({
|
| 246 |
+
"name": name,
|
| 247 |
+
"bbox": [xmin, ymin, xmax, ymax]
|
| 248 |
+
})
|
| 249 |
+
|
| 250 |
+
return {
|
| 251 |
+
"filename": filename,
|
| 252 |
+
"width": width,
|
| 253 |
+
"height": height,
|
| 254 |
+
"depth": depth,
|
| 255 |
+
"objects": objects
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
def convert_voc_to_coco(voc_xml_path, target_folder):
|
| 259 |
+
"""
|
| 260 |
+
Reads a Pascal VOC XML file, converts it into COCO JSON format,
|
| 261 |
+
and writes the JSON file in target_folder with the same base name.
|
| 262 |
+
"""
|
| 263 |
+
voc_data = parse_voc_xml(voc_xml_path)
|
| 264 |
+
|
| 265 |
+
coco_json = {
|
| 266 |
+
"images": [],
|
| 267 |
+
"annotations": [],
|
| 268 |
+
"categories": []
|
| 269 |
+
}
|
| 270 |
+
image_id = 1
|
| 271 |
+
annotation_id = 1
|
| 272 |
+
|
| 273 |
+
coco_json["images"].append({
|
| 274 |
+
"file_name": voc_data["filename"],
|
| 275 |
+
"height": voc_data["height"],
|
| 276 |
+
"width": voc_data["width"],
|
| 277 |
+
"id": image_id
|
| 278 |
+
})
|
| 279 |
+
|
| 280 |
+
category_mapping = {}
|
| 281 |
+
for obj in voc_data["objects"]:
|
| 282 |
+
cat_name = obj["name"]
|
| 283 |
+
if cat_name not in category_mapping:
|
| 284 |
+
category_mapping[cat_name] = len(category_mapping) + 1
|
| 285 |
+
|
| 286 |
+
for cat_name, cat_id in category_mapping.items():
|
| 287 |
+
coco_json["categories"].append({
|
| 288 |
+
"id": cat_id,
|
| 289 |
+
"name": cat_name,
|
| 290 |
+
"supercategory": "none"
|
| 291 |
+
})
|
| 292 |
+
|
| 293 |
+
for obj in voc_data["objects"]:
|
| 294 |
+
xmin, ymin, xmax, ymax = obj["bbox"]
|
| 295 |
+
bbox_width = xmax - xmin
|
| 296 |
+
bbox_height = ymax - ymin
|
| 297 |
+
area = bbox_width * bbox_height
|
| 298 |
+
coco_json["annotations"].append({
|
| 299 |
+
"id": annotation_id,
|
| 300 |
+
"image_id": image_id,
|
| 301 |
+
"category_id": category_mapping[obj["name"]],
|
| 302 |
+
"bbox": [xmin, ymin, bbox_width, bbox_height],
|
| 303 |
+
"area": area,
|
| 304 |
+
"iscrowd": 0
|
| 305 |
+
})
|
| 306 |
+
annotation_id += 1
|
| 307 |
+
|
| 308 |
+
base_name = os.path.splitext(os.path.basename(voc_xml_path))[0]
|
| 309 |
+
out_path = os.path.join(target_folder, base_name + ".json")
|
| 310 |
+
with open(out_path, "w") as json_file:
|
| 311 |
+
json.dump(coco_json, json_file, indent=4)
|
| 312 |
+
print(f"Created: {out_path}")
|
| 313 |
+
|
| 314 |
+
# %% [markdown]
|
| 315 |
+
# # Cell 7: Load Detection Model
|
| 316 |
+
# Initialize the SAHI wrapper for the Detectron2 model with downloaded configuration and weights.
|
| 317 |
+
# %%
|
| 318 |
+
detection_model = AutoDetectionModel.from_pretrained(
|
| 319 |
+
model_type='detectron2',
|
| 320 |
+
model_path=model_path,
|
| 321 |
+
config_path=config_path,
|
| 322 |
+
confidence_threshold=conf_thresh,
|
| 323 |
+
device='cuda:0',
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
# %% [markdown]
|
| 327 |
+
# # Cell 8: Check and Prepare Input File List
|
| 328 |
+
# Scans input paths and filters files (ensuring 3 or 4 color bands for Orthomosaics, skipping DEMs).
|
| 329 |
+
# %%
|
| 330 |
+
if ortho_path == '':
|
| 331 |
+
orthos = glob.glob(os.path.join(ortho_folder_path, "**", "*.tif"), recursive=True)
|
| 332 |
+
orthos_rgb = []
|
| 333 |
+
skipped = []
|
| 334 |
+
|
| 335 |
+
for p in orthos:
|
| 336 |
+
try:
|
| 337 |
+
with rasterio.open(p) as src:
|
| 338 |
+
b = src.count
|
| 339 |
+
if b in (3, 4):
|
| 340 |
+
orthos_rgb.append(p)
|
| 341 |
+
else:
|
| 342 |
+
skipped.append((p, b, "not 3/4 bands (likely DEM)"))
|
| 343 |
+
except Exception as e:
|
| 344 |
+
skipped.append((p, None, f"read error: {e}"))
|
| 345 |
+
|
| 346 |
+
print("Total:", len(orthos))
|
| 347 |
+
print("Kept (3/4 bands):", len(orthos_rgb))
|
| 348 |
+
print("Skipped:", len(skipped))
|
| 349 |
+
print("A folder of orthos and dems specified")
|
| 350 |
+
orthos = orthos_rgb
|
| 351 |
+
|
| 352 |
+
elif ortho_folder_path == '':
|
| 353 |
+
orthos = [ortho_path]
|
| 354 |
+
dems = [dem_path]
|
| 355 |
+
print("A single Ortho and dem specified")
|
| 356 |
+
elif ortho_path == '' and ortho_folder_path == '':
|
| 357 |
+
print("both ortho_path and ortho_folder_path are empty")
|
| 358 |
+
elif ortho_path != '' and ortho_folder_path != '':
|
| 359 |
+
print("both ortho_path and ortho_folder_path are not empty. Specify only one")
|
| 360 |
+
|
| 361 |
+
# %% [markdown]
|
| 362 |
+
# # Cell 9: Run Sliced Inference and Export Metrics
|
| 363 |
+
# Iterate through each orthomosaic, execute SAHI sliced inference, save results, compute crown sizes, tree heights, and estimate biomass.
|
| 364 |
+
# %%
|
| 365 |
+
orthos = sorted(orthos, key=os.path.getsize)
|
| 366 |
+
for orthomosaic_path in orthos:
|
| 367 |
+
print(orthomosaic_path)
|
| 368 |
+
basename = orthomosaic_path.split('/')[-1].split('.')[0]
|
| 369 |
+
|
| 370 |
+
if os.path.exists("{}/{}_pred.png".format(save_dir, basename)) and os.path.exists("{}/{}_pred.csv".format(save_dir, basename)):
|
| 371 |
+
print("image already analyzed: " + basename)
|
| 372 |
+
continue
|
| 373 |
+
|
| 374 |
+
if plot_ortho:
|
| 375 |
+
img = plt.imread(orthomosaic_path)
|
| 376 |
+
plt.figure(figsize=(30, 30), dpi=150)
|
| 377 |
+
plt.imshow(img)
|
| 378 |
+
plt.show()
|
| 379 |
+
|
| 380 |
+
gsd_x, gsd_y = get_gsd(orthomosaic_path)
|
| 381 |
+
print(gsd_x)
|
| 382 |
+
print(gsd_y)
|
| 383 |
+
gsd = 0.5 * (gsd_x + gsd_y)
|
| 384 |
+
slice_size = int(aveg_width / gsd)
|
| 385 |
+
print(f"Calculated slice size: {slice_size} based on average width {aveg_width} and GSD {gsd}")
|
| 386 |
+
|
| 387 |
+
result = get_sliced_prediction(
|
| 388 |
+
orthomosaic_path,
|
| 389 |
+
detection_model,
|
| 390 |
+
slice_height=slice_size,
|
| 391 |
+
slice_width=slice_size,
|
| 392 |
+
overlap_height_ratio=0.5,
|
| 393 |
+
overlap_width_ratio=0.5,
|
| 394 |
+
perform_standard_pred=False,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
result.export_visuals(export_dir=save_dir, file_name="{}_pred".format(basename), text_size=0.1, rect_th=5)
|
| 398 |
+
img = plt.imread("{}/{}_pred.png".format(save_dir, basename))
|
| 399 |
+
plt.figure(figsize=(30, 30), dpi=150)
|
| 400 |
+
plt.imshow(img)
|
| 401 |
+
plt.show()
|
| 402 |
+
|
| 403 |
+
sahi_list = result.to_coco_annotations()
|
| 404 |
+
prediction_df = pd.DataFrame(sahi_list)
|
| 405 |
+
write_Sahi_results_to_pascalVOCxml(sahi_list, '{}/{}.xml'.format(save_dir, basename), img, basename)
|
| 406 |
+
prediction_df = voc_xml_to_df('{}/{}.xml'.format(save_dir, basename))
|
| 407 |
+
convert_voc_to_coco('{}/{}.xml'.format(save_dir, basename), save_dir)
|
| 408 |
+
|
| 409 |
+
# fill geolocations
|
| 410 |
+
try:
|
| 411 |
+
prediction_df["xcenter"] = (prediction_df["xmin"] + prediction_df["xmax"])/2
|
| 412 |
+
prediction_df["ycenter"] = (prediction_df["ymin"] + prediction_df["ymax"])/2
|
| 413 |
+
with rasterio.open(orthomosaic_path) as src:
|
| 414 |
+
transform = src.transform
|
| 415 |
+
crs = src.crs
|
| 416 |
+
prediction_df[['lon', 'lat']] = prediction_df.apply(lambda row: pd.Series(GetLonLat(transform, crs, row['xcenter'], row['ycenter'])), axis=1)
|
| 417 |
+
except:
|
| 418 |
+
print("possibly no trees detected in the crop")
|
| 419 |
+
|
| 420 |
+
# fill crown size
|
| 421 |
+
try:
|
| 422 |
+
prediction_df["Crown (m)"] = GetCrownSize(prediction_df[['xmin', 'ymin', 'xmax', 'ymax']], gsd)
|
| 423 |
+
except:
|
| 424 |
+
print("Unable to add crown. Likely no predictions")
|
| 425 |
+
|
| 426 |
+
# fill heights
|
| 427 |
+
if ortho_folder_path != '':
|
| 428 |
+
dem_path = "{}/{}_dem.tif".format(dem_folder_path, basename)
|
| 429 |
+
if not os.path.exists(dem_path):
|
| 430 |
+
print("No dem file found/specified. Will write csv file for {} without height information".format(basename))
|
| 431 |
+
prediction_df.to_csv('{}/{}_pred.csv'.format(save_dir, basename))
|
| 432 |
+
else:
|
| 433 |
+
dem_data, nodatavalue = ReadDEM(dem_path)
|
| 434 |
+
dem_data[dem_data == nodatavalue] = np.nan
|
| 435 |
+
plt.imshow(dem_data)
|
| 436 |
+
plt.show()
|
| 437 |
+
padding = 0
|
| 438 |
+
middle_frac = 0.4
|
| 439 |
+
try:
|
| 440 |
+
prediction_df["Height (m)"] = prediction_df[['xmin', 'ymin', 'xmax', 'ymax']].apply(GetTreeHeight, args=(dem_path, orthomosaic_path, dem_data, padding, middle_frac), axis=1)
|
| 441 |
+
except:
|
| 442 |
+
print("cant extract height likely some issue with DEM")
|
| 443 |
+
prediction_df.to_csv('{}/{}_pred.csv'.format(save_dir, basename))
|
| 444 |
+
continue
|
| 445 |
+
prediction_df.to_csv('{}/{}_pred_with_heights.csv'.format(save_dir, basename))
|
| 446 |
+
print("csv file with heights written")
|
| 447 |
+
|
| 448 |
+
# calculate biomass
|
| 449 |
+
calculate_biomass = False
|
| 450 |
+
if calculate_biomass:
|
| 451 |
+
## drop rows witn nans
|
| 452 |
+
prediction_df.dropna(inplace=True)
|
| 453 |
+
|
| 454 |
+
## load saved GPR (look in HF cache directory first, otherwise fall back to Google Drive)
|
| 455 |
+
gpr_path_hf = os.path.join(model_dir, "gp_1_1.pl")
|
| 456 |
+
if os.path.exists(gpr_path_hf):
|
| 457 |
+
print("Loading GPR model from Hugging Face cache...")
|
| 458 |
+
gaussian_process = pickle.load(open(gpr_path_hf, "rb"))
|
| 459 |
+
else:
|
| 460 |
+
gpr_dir = '/content/drive/MyDrive/Colab Notebooks/code_snippets/Gaussian_Processes/for_paper/val_pick_model_no_alpha_log_DBH'
|
| 461 |
+
gpr_path_gd = os.path.join(gpr_dir, 'gp_1_1.pl')
|
| 462 |
+
print(f"Hugging Face GPR model not found. Falling back to Google Drive: {gpr_path_gd}")
|
| 463 |
+
gaussian_process = pickle.load(open(gpr_path_gd, "rb"))
|
| 464 |
+
|
| 465 |
+
X = 3.28084 * np.array(prediction_df[['Crown (m)', 'Height (m)']])
|
| 466 |
+
|
| 467 |
+
## gpr matrices
|
| 468 |
+
K_n_std = gaussian_process.kernel_(gaussian_process.X_train_) + gaussian_process.alpha * np.eye(len(gaussian_process.X_train_)) + gaussian_process.kernel_.k2.get_params()['noise_level']*np.eye(len(gaussian_process.X_train_))
|
| 469 |
+
K_n_mean = gaussian_process.kernel_(gaussian_process.X_train_) + gaussian_process.alpha * np.eye(len(gaussian_process.X_train_)) + gaussian_process.kernel_.k2.get_params()['noise_level']*np.eye(len(gaussian_process.X_train_))
|
| 470 |
+
|
| 471 |
+
K_n_inv_mean = np.linalg.inv(K_n_mean)
|
| 472 |
+
K_n_inv_std = np.linalg.inv(K_n_std)
|
| 473 |
+
alpha_ = np.dot(K_n_inv_mean, gaussian_process.y_train_)
|
| 474 |
+
|
| 475 |
+
# get log_DBH mean and cov matrix
|
| 476 |
+
log_dbh_mean = np.dot(gaussian_process.kernel_(X, gaussian_process.X_train_), alpha_)
|
| 477 |
+
log_dbh_cov = gaussian_process.kernel_(X, X) - np.dot(np.dot(gaussian_process.kernel_(X, gaussian_process.X_train_), K_n_inv_std), gaussian_process.kernel_(gaussian_process.X_train_, X)) + gaussian_process.kernel_.k2.get_params()['noise_level']*np.eye(len(X))
|
| 478 |
+
|
| 479 |
+
# sample and fit norm distribution
|
| 480 |
+
n_samples = 5000
|
| 481 |
+
log_dbh_sampled = np.random.multivariate_normal(log_dbh_mean, log_dbh_cov, size = n_samples)
|
| 482 |
+
|
| 483 |
+
dbh_sampled = np.exp(log_dbh_sampled)
|
| 484 |
+
dbh_means = dbh_sampled.mean(axis=0)
|
| 485 |
+
dbh_stds = dbh_sampled.std(axis=0)
|
| 486 |
+
prediction_df['Mean DBH (cm)'] = dbh_means
|
| 487 |
+
prediction_df['Std DBH (cm)'] = dbh_stds
|
| 488 |
+
|
| 489 |
+
AGB = np.exp(-1.996 + 2.32 * log_dbh_sampled)
|
| 490 |
+
|
| 491 |
+
AGB_means = AGB.mean(axis=0)
|
| 492 |
+
AGB_stds = AGB.std(axis=0)
|
| 493 |
+
prediction_df['Mean AGB (kg)'] = AGB_means
|
| 494 |
+
prediction_df['Std AGB (kg)'] = AGB_stds
|
| 495 |
+
|
| 496 |
+
predicted_AGB = np.sum(AGB, axis = 1)
|
| 497 |
+
AGBmu, AGBstd = norm.fit(predicted_AGB)
|
| 498 |
+
print(AGBmu)
|
| 499 |
+
prediction_df.to_csv('{}/{}_pred_with_biomass.csv'.format(save_dir, basename))
|
| 500 |
+
|
| 501 |
+
# Print final run details
|
| 502 |
+
print("Inference finished successfully.")
|
| 503 |
+
print(dem_path)
|