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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"toc_visible": true
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "markdown",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"# Agroforestry inventory from drone imagery\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"Counts and locates individual plants in an agroforestry system from a drone\n",
|
| 26 |
+
"orthophoto. You upload the image, choose a species, and get a map with every plant\n",
|
| 27 |
+
"marked plus a geographic file for your GIS.\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"**How to run:** *Runtime* menu -> *Run all*, then answer when it asks for the image.\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"> The code is hidden so it does not get in the way of reading. Click **Show code**\n",
|
| 32 |
+
"> on any step to audit it - everything is open, under GPL-3.0.\n",
|
| 33 |
+
"> Source: [github.com/COURAGEOUS-LAND/agroforestry-inventory](https://github.com/COURAGEOUS-LAND/agroforestry-inventory)\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"---\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"### Before trusting a number\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"**These models do not transfer from one place to another without loss.** That is\n",
|
| 40 |
+
"measured, not a disclaimer. One of our coffee models scored well on its own\n",
|
| 41 |
+
"validation set and, applied to held-out areas of the **same orthophoto** a few\n",
|
| 42 |
+
"hundred metres from where it was trained, found **2 of 198** plants. Its precision\n",
|
| 43 |
+
"stayed at 1.00 - the two it found were correct. It invented nothing:\n",
|
| 44 |
+
"**it went blind, and nothing in the output said so.**\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"So when you run it on your imagery: **look at the figure in step 6**. If the boxes\n",
|
| 47 |
+
"do not sit on the plants, the model does not work there. Count a small area by hand\n",
|
| 48 |
+
"and compare. We would rather say this on the first screen than let you find out\n",
|
| 49 |
+
"later."
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "markdown",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"## 1. Set up"
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"metadata": {
|
| 63 |
+
"cellView": "form"
|
| 64 |
+
},
|
| 65 |
+
"outputs": [],
|
| 66 |
+
"source": [
|
| 67 |
+
"# @title Install dependencies 路 *takes 2 to 3 minutes, once per session*\n",
|
| 68 |
+
"%pip install -q rfdetr rasterio geopandas shapely scipy tqdm huggingface_hub folium\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"import torch\n",
|
| 71 |
+
"if torch.cuda.is_available():\n",
|
| 72 |
+
" print(f\"GPU: {torch.cuda.get_device_name(0)} - detection will take about a minute\")\n",
|
| 73 |
+
"else:\n",
|
| 74 |
+
" print(\"No GPU (works the same, just slower: about 4 min per orthophoto)\")\n",
|
| 75 |
+
" print(\"To enable: Runtime -> Change runtime type -> GPU\")"
|
| 76 |
+
]
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "markdown",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"## 2. Choose the species\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"The species and the figures below come from the manifest published alongside the\n",
|
| 85 |
+
"weights - they are not copied into this notebook. What you read is what the model\n",
|
| 86 |
+
"actually is."
|
| 87 |
+
]
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"metadata": {
|
| 93 |
+
"cellView": "form"
|
| 94 |
+
},
|
| 95 |
+
"outputs": [],
|
| 96 |
+
"source": [
|
| 97 |
+
"# @title Species to detect\n",
|
| 98 |
+
"SPECIES = \"coffee\" # @param [\"coffee\", \"avocado\", \"pitaya\", \"banana\"]\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"import json, urllib.request, hashlib\n",
|
| 101 |
+
"from pathlib import Path\n",
|
| 102 |
+
"from huggingface_hub import hf_hub_download\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"REPO = \"JefersonPMS/agroforestry-inventory\"\n",
|
| 105 |
+
"manifest = json.loads(urllib.request.urlopen(\n",
|
| 106 |
+
" f\"https://huggingface.co/{REPO}/resolve/main/models.json\").read())\n",
|
| 107 |
+
"card = next(m for m in manifest[\"models\"] if m[\"species\"] == SPECIES)\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"print(f\"{card['title']}\\n\")\n",
|
| 110 |
+
"print(f\" trained at ........ {card['site']}\")\n",
|
| 111 |
+
"print(f\" precision ......... {card['precision']} of the plants reported, how many are real\")\n",
|
| 112 |
+
"print(f\" recall ............ {card['recall']} of the real plants, how many were found\")\n",
|
| 113 |
+
"print(f\" position error .... {card['position_error_m']} m\")\n",
|
| 114 |
+
"print(f\" median crown ...... {card['median_crown_m']} m\")\n",
|
| 115 |
+
"print(f\" trained on ........ {card['training_labels']} hand-marked plants\")\n",
|
| 116 |
+
"print(f\"\\n WHERE THIS MODEL FAILS:\\n {card['where_it_fails']}\")\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"model_path = hf_hub_download(repo_id=REPO, filename=card[\"file\"])\n",
|
| 119 |
+
"# check the sha256: a download cut short leaves a truncated file that loads and\n",
|
| 120 |
+
"# infers wrongly, without complaining\n",
|
| 121 |
+
"assert hashlib.sha256(Path(model_path).read_bytes()).hexdigest() == card[\"sha256\"], \\\n",
|
| 122 |
+
" \"corrupted file - delete it and run again\"\n",
|
| 123 |
+
"print(f\"\\n model downloaded and verified ({Path(model_path).stat().st_size/1e6:.0f} MB)\")"
|
| 124 |
+
]
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "markdown",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"## 3. Your orthophoto\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"It must be a georeferenced GeoTIFF with at least three bands (RGB).\n",
|
| 133 |
+
"For a large file, Google Drive is much better than uploading through the browser."
|
| 134 |
+
]
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"execution_count": null,
|
| 139 |
+
"metadata": {
|
| 140 |
+
"cellView": "form"
|
| 141 |
+
},
|
| 142 |
+
"outputs": [],
|
| 143 |
+
"source": [
|
| 144 |
+
"# @title Where the image comes from\n",
|
| 145 |
+
"SOURCE = \"example\" # @param [\"example\", \"my computer\", \"Google Drive\"]\n",
|
| 146 |
+
"PATH_IN_DRIVE = \"/content/drive/MyDrive/my_orthophoto.tif\" # @param {type:\"string\"}\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"if SOURCE == \"example\":\n",
|
| 149 |
+
" import urllib.request\n",
|
| 150 |
+
" ORTHOPHOTO = \"example_coffee.tif\"\n",
|
| 151 |
+
" if not Path(ORTHOPHOTO).exists():\n",
|
| 152 |
+
" urllib.request.urlretrieve(\n",
|
| 153 |
+
" f\"https://huggingface.co/{REPO}/resolve/main/exemplo_cafe.tif\", ORTHOPHOTO)\n",
|
| 154 |
+
" print(\"A 34 x 34 m patch of an agroforestry system in Sao Paulo, Brazil, with coffee.\")\n",
|
| 155 |
+
" print(\"For your own image, change SOURCE above.\")\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"elif SOURCE == \"my computer\":\n",
|
| 158 |
+
" from google.colab import files\n",
|
| 159 |
+
" ORTHOPHOTO = list(files.upload().keys())[0]\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"else:\n",
|
| 162 |
+
" from google.colab import drive\n",
|
| 163 |
+
" drive.mount(\"/content/drive\")\n",
|
| 164 |
+
" ORTHOPHOTO = PATH_IN_DRIVE\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"import rasterio\n",
|
| 167 |
+
"with rasterio.open(ORTHOPHOTO) as src:\n",
|
| 168 |
+
" gsd = abs(src.transform.a)\n",
|
| 169 |
+
" print(f\"\\n{ORTHOPHOTO}\")\n",
|
| 170 |
+
" print(f\" {src.width} x {src.height} px 路 {src.count} bands 路 {src.crs}\")\n",
|
| 171 |
+
" print(f\" resolution: {gsd*100:.1f} cm per pixel\")\n",
|
| 172 |
+
" if not 0.005 < gsd < 0.06:\n",
|
| 173 |
+
" print(\" WARNING: the models were trained at about 1.7 cm/px.\"\n",
|
| 174 |
+
" \" A very different resolution degrades the result.\")"
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "markdown",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"## 4. The detection engine\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"An orthophoto does not fit into a vision model in one piece, so it is walked in\n",
|
| 184 |
+
"overlapping tiles. Each box the model returns in pixel space becomes a geographic\n",
|
| 185 |
+
"coordinate through the raster transform. Because the tiles overlap, a plant near an\n",
|
| 186 |
+
"edge is detected twice - the de-duplication step merges those repeats and keeps the\n",
|
| 187 |
+
"most confident one."
|
| 188 |
+
]
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "code",
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"metadata": {
|
| 194 |
+
"cellView": "form"
|
| 195 |
+
},
|
| 196 |
+
"outputs": [],
|
| 197 |
+
"source": [
|
| 198 |
+
"# @title Load the engine 路 *produces no output; only defines the functions*\n",
|
| 199 |
+
"import numpy as np, rasterio, time\n",
|
| 200 |
+
"from PIL import Image\n",
|
| 201 |
+
"from rasterio.windows import Window\n",
|
| 202 |
+
"from rasterio.transform import xy as raster_xy\n",
|
| 203 |
+
"from shapely.geometry import Polygon, Point\n",
|
| 204 |
+
"from scipy.spatial import cKDTree\n",
|
| 205 |
+
"from tqdm.auto import tqdm\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"def to_rgb(tile):\n",
|
| 208 |
+
" \"\"\"Raster bands -> 8-bit RGB, stretched 2%-98% as in training.\"\"\"\n",
|
| 209 |
+
" planes = []\n",
|
| 210 |
+
" for b in range(3):\n",
|
| 211 |
+
" p = tile[b].astype(np.float32)\n",
|
| 212 |
+
" v = p[~np.isnan(p)]\n",
|
| 213 |
+
" if v.size == 0:\n",
|
| 214 |
+
" planes.append(np.zeros(p.shape, np.uint8)); continue\n",
|
| 215 |
+
" lo, hi = np.percentile(v, 2), np.percentile(v, 98)\n",
|
| 216 |
+
" if hi - lo < 1e-3: hi = lo + 1\n",
|
| 217 |
+
" planes.append(np.clip((p - lo) / (hi - lo) * 255, 0, 255).astype(np.uint8))\n",
|
| 218 |
+
" return np.stack(planes, -1)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"def deduplicate(recs, dist_m, crs):\n",
|
| 221 |
+
" \"\"\"Same plant seen in neighbouring tiles: keep the most confident one.\"\"\"\n",
|
| 222 |
+
" if len(recs) <= 1: return recs\n",
|
| 223 |
+
" import geopandas as gpd\n",
|
| 224 |
+
" g = gpd.GeoDataFrame(geometry=[r['centroid'] for r in recs], crs=crs)\n",
|
| 225 |
+
" try: metric = g.estimate_utm_crs()\n",
|
| 226 |
+
" except Exception: metric = crs\n",
|
| 227 |
+
" pts = np.array([[p.x, p.y] for p in g.to_crs(metric).geometry])\n",
|
| 228 |
+
" tree, dead = cKDTree(pts), np.zeros(len(pts), bool)\n",
|
| 229 |
+
" for i in np.argsort([-r['confidence'] for r in recs]):\n",
|
| 230 |
+
" if dead[i]: continue\n",
|
| 231 |
+
" for j in tree.query_ball_point(pts[i], r=dist_m):\n",
|
| 232 |
+
" if j != i: dead[j] = True\n",
|
| 233 |
+
" return [r for k, r in enumerate(recs) if not dead[k]]\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"def detect(orthophoto, model, label, confidence=0.25, dedup_m=0.5, tile_px=640, overlap=0.2):\n",
|
| 236 |
+
" from rfdetr import RFDETRNano\n",
|
| 237 |
+
" net = RFDETRNano(pretrain_weights=model)\n",
|
| 238 |
+
" step = int(tile_px * (1 - overlap))\n",
|
| 239 |
+
" recs, t0 = [], time.time()\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" with rasterio.open(orthophoto) as src:\n",
|
| 242 |
+
" assert src.count >= 3, f'the raster needs 3 RGB bands (it has {src.count})'\n",
|
| 243 |
+
" n_c = max(1, (src.width - tile_px) // step + 1)\n",
|
| 244 |
+
" n_r = max(1, (src.height - tile_px) // step + 1)\n",
|
| 245 |
+
" print(f'{n_r*n_c} tiles of {tile_px} px')\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" for r in tqdm(range(n_r), desc='progress'):\n",
|
| 248 |
+
" for c in range(n_c):\n",
|
| 249 |
+
" cx, cy = c * step, r * step\n",
|
| 250 |
+
" data = src.read(window=Window(cx, cy, tile_px, tile_px))\n",
|
| 251 |
+
" if data.shape[0] < 3: continue\n",
|
| 252 |
+
" h, w = data.shape[1], data.shape[2]\n",
|
| 253 |
+
" rgb = to_rgb(data[:3])\n",
|
| 254 |
+
" if rgb.mean() < 12: continue # outside the footprint\n",
|
| 255 |
+
" buf = np.zeros((tile_px, tile_px, 3), np.uint8)\n",
|
| 256 |
+
" buf[:h, :w] = rgb[:tile_px, :tile_px]\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" det = net.predict(Image.fromarray(buf), threshold=confidence, shape=(384, 384))\n",
|
| 259 |
+
" if det is None or len(det) == 0: continue\n",
|
| 260 |
+
" for k in range(len(det.xyxy)):\n",
|
| 261 |
+
" x1, y1, x2, y2 = det.xyxy[k]\n",
|
| 262 |
+
" x1, x2 = np.clip([x1, x2], 0, w); y1, y2 = np.clip([y1, y2], 0, h)\n",
|
| 263 |
+
" if x2 <= x1 or y2 <= y1: continue\n",
|
| 264 |
+
" cols = np.array([x1, x2, x2, x1]) + cx\n",
|
| 265 |
+
" rows = np.array([y1, y1, y2, y2]) + cy\n",
|
| 266 |
+
" pts = [raster_xy(src.transform, ro, co, offset='ul') for ro, co in zip(rows, cols)]\n",
|
| 267 |
+
" poly = Polygon(pts)\n",
|
| 268 |
+
" if poly.is_empty or not poly.is_valid: continue\n",
|
| 269 |
+
" recs.append({'class': label, 'confidence': float(det.confidence[k]),\n",
|
| 270 |
+
" 'box': poly, 'centroid': Point(poly.centroid.x, poly.centroid.y)})\n",
|
| 271 |
+
" crs = src.crs\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" raw = len(recs)\n",
|
| 274 |
+
" recs = deduplicate(recs, dedup_m, crs)\n",
|
| 275 |
+
" print(f'{raw} raw detections -> {len(recs)} after removing repeats '\n",
|
| 276 |
+
" f'({time.time()-t0:.0f}s)')\n",
|
| 277 |
+
" return recs, crs"
|
| 278 |
+
]
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "markdown",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"## 5. Detect"
|
| 285 |
+
]
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"metadata": {
|
| 291 |
+
"cellView": "form"
|
| 292 |
+
},
|
| 293 |
+
"outputs": [],
|
| 294 |
+
"source": [
|
| 295 |
+
"# @title Run the detection\n",
|
| 296 |
+
"MINIMUM_CONFIDENCE = 0.25 # @param {type:\"slider\", min:0.05, max:0.9, step:0.05}\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"records, crs = detect(ORTHOPHOTO, model_path, card[\"species\"],\n",
|
| 299 |
+
" confidence=MINIMUM_CONFIDENCE,\n",
|
| 300 |
+
" dedup_m=card[\"recommended_dedup_m\"])\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"import geopandas as gpd\n",
|
| 303 |
+
"attrs = {\"class\": [r[\"class\"] for r in records],\n",
|
| 304 |
+
" \"confidence\": [r[\"confidence\"] for r in records]}\n",
|
| 305 |
+
"boxes = gpd.GeoDataFrame(attrs, geometry=[r[\"box\"] for r in records], crs=crs).to_crs(4326)\n",
|
| 306 |
+
"points = gpd.GeoDataFrame(attrs, geometry=[r[\"centroid\"] for r in records], crs=crs).to_crs(4326)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"print(f\"\\n{'='*46}\")\n",
|
| 309 |
+
"print(f\" {len(boxes)} {card['title']} plants\")\n",
|
| 310 |
+
"print(f\" confidence: median {points.confidence.median():.2f} 路 \"\n",
|
| 311 |
+
" f\"min {points.confidence.min():.2f} 路 max {points.confidence.max():.2f}\")\n",
|
| 312 |
+
"print(f\"{'='*46}\")"
|
| 313 |
+
]
|
| 314 |
+
},
|
| 315 |
+
{
|
| 316 |
+
"cell_type": "markdown",
|
| 317 |
+
"metadata": {},
|
| 318 |
+
"source": [
|
| 319 |
+
"## 6. Check the result\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"**This is the step that decides whether the number is worth anything.** Do the boxes\n",
|
| 322 |
+
"sit on the plants? If they do not, the model does not suit your imagery - which is\n",
|
| 323 |
+
"common, for the reason given at the top."
|
| 324 |
+
]
|
| 325 |
+
},
|
| 326 |
+
{
|
| 327 |
+
"cell_type": "code",
|
| 328 |
+
"execution_count": null,
|
| 329 |
+
"metadata": {
|
| 330 |
+
"cellView": "form"
|
| 331 |
+
},
|
| 332 |
+
"outputs": [],
|
| 333 |
+
"source": [
|
| 334 |
+
"# @title The detections over your own image\n",
|
| 335 |
+
"import matplotlib.pyplot as plt\n",
|
| 336 |
+
"from matplotlib.patches import Rectangle\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"PATCH_PX = 1000 # @param {type:\"slider\", min:400, max:2000, step:100}\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"with rasterio.open(ORTHOPHOTO) as src:\n",
|
| 341 |
+
" px = [src.index(p.x, p.y) for p in\n",
|
| 342 |
+
" gpd.GeoSeries([r[\"centroid\"] for r in records], crs=crs).to_crs(src.crs)]\n",
|
| 343 |
+
" rows = [p[0] for p in px]; cols = [p[1] for p in px]\n",
|
| 344 |
+
" side = min(PATCH_PX, src.width, src.height)\n",
|
| 345 |
+
" c0 = int(np.clip(np.median(cols) - side//2, 0, max(0, src.width - side)))\n",
|
| 346 |
+
" r0 = int(np.clip(np.median(rows) - side//2, 0, max(0, src.height - side)))\n",
|
| 347 |
+
" patch = to_rgb(src.read(window=Window(c0, r0, side, side))[:3])\n",
|
| 348 |
+
" gsd = abs(src.transform.a)\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"fig, ax = plt.subplots(figsize=(12, 12))\n",
|
| 351 |
+
"ax.imshow(patch); ax.axis(\"off\")\n",
|
| 352 |
+
"n = 0\n",
|
| 353 |
+
"for (ro, co), r in zip(px, records):\n",
|
| 354 |
+
" if r0 <= ro < r0+side and c0 <= co < c0+side:\n",
|
| 355 |
+
" half = max(6, (card[\"median_crown_m\"] / gsd) / 2)\n",
|
| 356 |
+
" ax.add_patch(Rectangle((co-c0-half, ro-r0-half), half*2, half*2,\n",
|
| 357 |
+
" fill=False, edgecolor=\"#f97316\", linewidth=1.6))\n",
|
| 358 |
+
" n += 1\n",
|
| 359 |
+
"ax.set_title(f\"{n} detections in this {int(side*gsd)} x {int(side*gsd)} m patch\", pad=14)\n",
|
| 360 |
+
"plt.tight_layout(); plt.show()"
|
| 361 |
+
]
|
| 362 |
+
},
|
| 363 |
+
{
|
| 364 |
+
"cell_type": "code",
|
| 365 |
+
"execution_count": null,
|
| 366 |
+
"metadata": {
|
| 367 |
+
"cellView": "form"
|
| 368 |
+
},
|
| 369 |
+
"outputs": [],
|
| 370 |
+
"source": [
|
| 371 |
+
"# @title Navigable map 路 *satellite background, to locate the area*\n",
|
| 372 |
+
"import folium\n",
|
| 373 |
+
"\n",
|
| 374 |
+
"c = points.geometry.union_all().centroid\n",
|
| 375 |
+
"m = folium.Map(location=[c.y, c.x], zoom_start=19, max_zoom=22,\n",
|
| 376 |
+
" tiles=\"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}\",\n",
|
| 377 |
+
" attr=\"Esri, Maxar\")\n",
|
| 378 |
+
"folium.GeoJson(\n",
|
| 379 |
+
" boxes,\n",
|
| 380 |
+
" style_function=lambda _: {\"color\": \"#f97316\", \"weight\": 2, \"fillOpacity\": 0.15},\n",
|
| 381 |
+
" tooltip=folium.GeoJsonTooltip([\"class\", \"confidence\"]),\n",
|
| 382 |
+
").add_to(m)\n",
|
| 383 |
+
"b = boxes.total_bounds\n",
|
| 384 |
+
"m.fit_bounds([[b[1], b[0]], [b[3], b[2]]])\n",
|
| 385 |
+
"print(\"The satellite image is from a different date than your orthophoto -\")\n",
|
| 386 |
+
"print(\"use it to locate the area, not to judge the detections.\")\n",
|
| 387 |
+
"m"
|
| 388 |
+
]
|
| 389 |
+
},
|
| 390 |
+
{
|
| 391 |
+
"cell_type": "markdown",
|
| 392 |
+
"metadata": {},
|
| 393 |
+
"source": [
|
| 394 |
+
"## 7. Download"
|
| 395 |
+
]
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"cell_type": "code",
|
| 399 |
+
"execution_count": null,
|
| 400 |
+
"metadata": {
|
| 401 |
+
"cellView": "form"
|
| 402 |
+
},
|
| 403 |
+
"outputs": [],
|
| 404 |
+
"source": [
|
| 405 |
+
"# @title Save GeoJSON and CSV\n",
|
| 406 |
+
"base = Path(ORTHOPHOTO).stem + \"_\" + card[\"species\"]\n",
|
| 407 |
+
"boxes.to_file(base + \"_boxes.geojson\", driver=\"GeoJSON\")\n",
|
| 408 |
+
"points.to_file(base + \"_centroids.geojson\", driver=\"GeoJSON\")\n",
|
| 409 |
+
"tab = points.copy()\n",
|
| 410 |
+
"tab[\"longitude\"], tab[\"latitude\"] = tab.geometry.x, tab.geometry.y\n",
|
| 411 |
+
"tab.drop(columns=\"geometry\").to_csv(base + \".csv\", index=False)\n",
|
| 412 |
+
"\n",
|
| 413 |
+
"print(\"All in EPSG:4326, ready for QGIS:\\n\")\n",
|
| 414 |
+
"for ext in (\"_boxes.geojson\", \"_centroids.geojson\", \".csv\"):\n",
|
| 415 |
+
" print(\" \" + base + ext)\n",
|
| 416 |
+
"\n",
|
| 417 |
+
"try:\n",
|
| 418 |
+
" from google.colab import files\n",
|
| 419 |
+
" for ext in (\"_boxes.geojson\", \"_centroids.geojson\", \".csv\"):\n",
|
| 420 |
+
" files.download(base + ext)\n",
|
| 421 |
+
"except Exception:\n",
|
| 422 |
+
" pass"
|
| 423 |
+
]
|
| 424 |
+
},
|
| 425 |
+
{
|
| 426 |
+
"cell_type": "markdown",
|
| 427 |
+
"metadata": {},
|
| 428 |
+
"source": [
|
| 429 |
+
"---\n",
|
| 430 |
+
"\n",
|
| 431 |
+
"### Running it on your own machine\n",
|
| 432 |
+
"\n",
|
| 433 |
+
"This notebook is a convenience. The full tool runs **offline, without a GPU and\n",
|
| 434 |
+
"without sending your imagery anywhere** - which matters when the orthophoto covers a\n",
|
| 435 |
+
"property whose location is sensitive information:\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"```bash\n",
|
| 438 |
+
"git clone https://github.com/COURAGEOUS-LAND/agroforestry-inventory\n",
|
| 439 |
+
"cd agroforestry-inventory\n",
|
| 440 |
+
"pip install -r requirements.txt\n",
|
| 441 |
+
"python download_models.py\n",
|
| 442 |
+
"python inventory.py my_orthophoto.tif --species coffee\n",
|
| 443 |
+
"```\n",
|
| 444 |
+
"\n",
|
| 445 |
+
"There the map uses **your orthophoto** as the background, rather than a satellite\n",
|
| 446 |
+
"image from another date.\n",
|
| 447 |
+
"\n",
|
| 448 |
+
"Models: <https://huggingface.co/JefersonPMS/agroforestry-inventory> 路\n",
|
| 449 |
+
"Code: <https://github.com/COURAGEOUS-LAND/agroforestry-inventory>\n",
|
| 450 |
+
"\n",
|
| 451 |
+
"Developed by **Courageous Land** 路 code GPL-3.0 路 models CC-BY-4.0"
|
| 452 |
+
]
|
| 453 |
+
}
|
| 454 |
+
]
|
| 455 |
+
}
|