utils module¶
Data conversion and coordinate transformation utilities.
bbox_to_xy(src_fp, coords, coord_crs='epsg:4326', **kwargs)
¶
Converts a list of coordinates to pixel coordinates, i.e., (col, row) coordinates. Note that map bbox coords is [minx, miny, maxx, maxy] from bottomleft to topright While rasterio bbox coords is [minx, max, maxx, min] from topleft to bottomright
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
coords
|
list
|
A list of coordinates in the format of [[minx, miny, maxx, maxy], [minx, miny, maxx, maxy], ...] |
required |
coord_crs
|
str
|
The coordinate CRS of the input coordinates. Defaults to "epsg:4326". |
'epsg:4326'
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
Optional[Union[List[float], List[List[float]]]]
|
A list of pixel coordinates in the format of [[minx, maxy, maxx, miny], ...] from top left to bottom right. |
Source code in geoai/utils/conversion.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
coords_to_xy(src_fp, coords, coord_crs='epsg:4326', return_out_of_bounds=False, **kwargs)
¶
Converts a list or array of coordinates to pixel coordinates, i.e., (col, row) coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
coords
|
ndarray
|
A 2D or 3D array of coordinates. Can be of shape [[x1, y1], [x2, y2], ...] or [[[x1, y1]], [[x2, y2]], ...]. |
required |
coord_crs
|
str
|
The coordinate CRS of the input coordinates. Defaults to "epsg:4326". |
'epsg:4326'
|
return_out_of_bounds
|
bool
|
Whether to return out-of-bounds coordinates. Defaults to False. |
False
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rasterio.transform.rowcol. |
{}
|
Returns:
| Type | Description |
|---|---|
Union[ndarray, Tuple[ndarray, List[int]]]
|
A 2D or 3D array of pixel coordinates in the same format as the input. |
Source code in geoai/utils/conversion.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
dict_to_image(data_dict, output=None, **kwargs)
¶
Convert a dictionary containing spatial data to a rasterio dataset or save it to a file. The dictionary should contain the following keys: "crs", "bounds", and "image". It can be generated from a TorchGeo dataset sampler.
This function transforms a dictionary with CRS, bounding box, and image data into a rasterio DatasetReader using leafmap's array_to_image utility after first converting to a rioxarray DataArray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dict
|
Dict[str, Any]
|
A dictionary containing: - 'crs': A pyproj CRS object - 'bounds': A BoundingBox object with minx, maxx, miny, maxy attributes and optionally mint, maxt for temporal bounds - 'image': A tensor or array-like object with image data |
required |
output
|
Optional[str]
|
Optional path to save the image to a file. If not provided, the image will be returned as a rasterio DatasetReader object. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to leafmap.array_to_image. Common options include: - colormap: str, name of the colormap (e.g., 'viridis', 'terrain') - vmin: float, minimum value for colormap scaling - vmax: float, maximum value for colormap scaling |
{}
|
Returns:
| Type | Description |
|---|---|
Union[str, Any]
|
A rasterio DatasetReader object that can be used for visualization or |
Union[str, Any]
|
further processing. |
Examples:
1 2 3 4 5 6 | |
Source code in geoai/utils/conversion.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
dict_to_rioxarray(data_dict)
¶
Convert a dictionary to a xarray DataArray. The dictionary should contain the following keys: "crs", "bounds", and "image". It can be generated from a TorchGeo dataset sampler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dict
|
Dict
|
The dictionary containing the data. |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
xr.DataArray: The xarray DataArray. |
Source code in geoai/utils/conversion.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
rowcol_to_xy(src_fp, rows=None, cols=None, boxes=None, zs=None, offset='center', output=None, dst_crs='EPSG:4326', **kwargs)
¶
Converts a list of (row, col) coordinates to (x, y) coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
rows
|
list
|
A list of row coordinates. Defaults to None. |
None
|
cols
|
list
|
A list of col coordinates. Defaults to None. |
None
|
boxes
|
list
|
A list of (row, col) coordinates in the format of [[left, top, right, bottom], [left, top, right, bottom], ...] |
None
|
zs
|
Optional[List[float]]
|
zs (list or float, optional): Height associated with coordinates. Primarily used for RPC based coordinate transformations. |
None
|
offset
|
str
|
Determines if the returned coordinates are for the center of the pixel or for a corner. |
'center'
|
output
|
str
|
The output vector file path. Defaults to None. |
None
|
dst_crs
|
str
|
The destination CRS. Defaults to "EPSG:4326". |
'EPSG:4326'
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rasterio.transform.xy. |
{}
|
Returns:
| Type | Description |
|---|---|
Optional[List[List[float]]]
|
A list of (x, y) coordinates. |
Source code in geoai/utils/conversion.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
Device and environment utilities.
empty_cache()
¶
Empty the cache of the current device.
Source code in geoai/utils/device.py
88 89 90 91 92 93 94 95 | |
get_device()
¶
Returns the best available device for deep learning in the order: CUDA (NVIDIA GPU) > MPS (Apple Silicon GPU) > CPU
Source code in geoai/utils/device.py
73 74 75 76 77 78 79 80 81 82 83 84 85 | |
install_package(package)
¶
Install a Python package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str | list
|
The package name or a GitHub URL or a list of package names or GitHub URLs. |
required |
Source code in geoai/utils/device.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
temp_file_path(ext)
¶
Returns a temporary file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ext
|
str
|
The file extension. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The temporary file path. |
Source code in geoai/utils/device.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
File download utilities.
download_file(url, output_path=None, overwrite=False, unzip=True)
¶
Download a file from a given URL with a progress bar. Optionally unzip the file if it's a ZIP archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL of the file to download. |
required |
output_path
|
str
|
The path where the downloaded file will be saved. If not provided, the filename from the URL will be used. |
None
|
overwrite
|
bool
|
Whether to overwrite the file if it already exists. |
False
|
unzip
|
bool
|
Whether to unzip the file if it is a ZIP archive. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The path to the downloaded file or the extracted directory. |
Source code in geoai/utils/download.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
download_model_from_hf(model_path, repo_id=None)
¶
Download the object detection model from Hugging Face.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the model file. |
required |
repo_id
|
Optional[str]
|
Hugging Face repository ID. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the downloaded model file |
Source code in geoai/utils/download.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
Geometry processing and regularization utilities.
adaptive_regularization(building_polygons, simplify_tolerance=0.5, area_threshold=0.9, preserve_shape=True)
¶
Adaptively regularizes building footprints based on their characteristics.
This approach determines the best regularization method for each building.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
building_polygons
|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons |
required |
simplify_tolerance
|
float
|
Distance tolerance for simplification |
0.5
|
area_threshold
|
float
|
Minimum acceptable area ratio |
0.9
|
preserve_shape
|
bool
|
Whether to preserve overall shape for complex buildings |
True
|
Returns:
| Type | Description |
|---|---|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons with regularized building footprints |
Source code in geoai/utils/geometry.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | |
hybrid_regularization(building_polygons)
¶
A comprehensive hybrid approach to building footprint regularization.
Applies different strategies based on building characteristics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
building_polygons
|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons containing building footprints |
required |
Returns:
| Type | Description |
|---|---|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons with regularized building footprints |
Source code in geoai/utils/geometry.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
orthogonalize(input_path, output_path=None, epsilon=0.2, min_area=10, min_segments=4, area_tolerance=0.7, detect_triangles=True)
¶
Orthogonalizes object masks in a GeoTIFF file.
This function reads a GeoTIFF containing object masks (binary or labeled regions), converts the raster masks to vector polygons, applies orthogonalization to each polygon, and optionally writes the result to a GeoJSON file. The source code is adapted from the Solar Panel Detection algorithm by Esri. See https://www.arcgis.com/home/item.html?id=c2508d72f2614104bfcfd5ccf1429284. Credits to Esri for the original code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Path to the input GeoTIFF file. |
required |
output_path
|
str
|
Path to save the output GeoJSON file. If None, no file is saved. |
None
|
epsilon
|
float
|
Simplification tolerance for the Douglas-Peucker algorithm. Higher values result in more simplification. Default is 0.2. |
0.2
|
min_area
|
float
|
Minimum area of polygons to process (smaller ones are kept as-is). |
10
|
min_segments
|
int
|
Minimum number of segments to keep after simplification. Default is 4 (for rectangular shapes). |
4
|
area_tolerance
|
float
|
Allowed ratio of area change. Values less than 1.0 restrict area change. Default is 0.7 (allows reduction to 70% of original area). |
0.7
|
detect_triangles
|
bool
|
If True, performs additional check to avoid creating triangular shapes. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
A GeoDataFrame containing the orthogonalized features. |
Source code in geoai/utils/geometry.py
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 | |
region_groups(image, connectivity=1, min_size=10, max_size=None, threshold=None, properties=None, intensity_image=None, out_csv=None, out_vector=None, out_image=None, **kwargs)
¶
Segment regions in an image and filter them based on size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Union[str, DataArray, ndarray]
|
Input image, can be a file path, xarray DataArray, or numpy array. |
required |
connectivity
|
int
|
Connectivity for labeling. Defaults to 1 for 4-connectivity. Use 2 for 8-connectivity. |
1
|
min_size
|
int
|
Minimum size of regions to keep. Defaults to 10. |
10
|
max_size
|
Optional[int]
|
Maximum size of regions to keep. Defaults to None. |
None
|
threshold
|
Optional[int]
|
Threshold for filling holes. Defaults to None, which is equal to min_size. |
None
|
properties
|
Optional[List[str]]
|
List of properties to measure. See https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.regionprops Defaults to None. |
None
|
intensity_image
|
Optional[Union[str, DataArray, ndarray]]
|
Intensity image to measure properties. Defaults to None. |
None
|
out_csv
|
Optional[str]
|
Path to save the properties as a CSV file. Defaults to None. |
None
|
out_vector
|
Optional[str]
|
Path to save the vector file. Defaults to None. |
None
|
out_image
|
Optional[str]
|
Path to save the output image. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Union[Tuple[ndarray, DataFrame], Tuple[DataArray, DataFrame]]
|
Union[Tuple[np.ndarray, pd.DataFrame], Tuple[xr.DataArray, pd.DataFrame]]: Labeled image and properties DataFrame. |
Source code in geoai/utils/geometry.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 | |
regularization(building_polygons, angle_tolerance=10, simplify_tolerance=0.5, orthogonalize=True, preserve_topology=True)
¶
Regularizes building footprint polygons with multiple techniques beyond minimum rotated rectangles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
building_polygons
|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons containing building footprints |
required |
angle_tolerance
|
float
|
Degrees within which angles will be regularized to 90/180 degrees |
10
|
simplify_tolerance
|
float
|
Distance tolerance for Douglas-Peucker simplification |
0.5
|
orthogonalize
|
bool
|
Whether to enforce orthogonal angles in the final polygons |
True
|
preserve_topology
|
bool
|
Whether to preserve topology during simplification |
True
|
Returns:
| Type | Description |
|---|---|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons with regularized building footprints |
Source code in geoai/utils/geometry.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
regularize(data, parallel_threshold=1.0, target_crs=None, simplify=True, simplify_tolerance=0.5, allow_45_degree=True, diagonal_threshold_reduction=15, allow_circles=True, circle_threshold=0.9, num_cores=1, include_metadata=False, output_path=None, **kwargs)
¶
Regularizes polygon geometries in a GeoDataFrame by aligning edges.
Aligns edges to be parallel or perpendicular (optionally also 45 degrees) to their main direction. Handles reprojection, initial simplification, regularization, geometry cleanup, and parallel processing.
This function is a wrapper around the regularize_geodataframe function
from the buildingregulariser package. Credits to the original author
Nick Wright. Check out the repo at https://github.com/DPIRD-DMA/Building-Regulariser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[GeoDataFrame, str]
|
Input GeoDataFrame with polygon or multipolygon geometries, or a file path to the GeoDataFrame. |
required |
parallel_threshold
|
float
|
Distance threshold for merging nearly parallel adjacent edges during regularization. Defaults to 1.0. |
1.0
|
target_crs
|
Optional[Union[str, CRS]]
|
Target Coordinate Reference System for processing. If None, uses the input GeoDataFrame's CRS. Processing is more reliable in a projected CRS. Defaults to None. |
None
|
simplify
|
bool
|
If True, applies initial simplification to the geometry before regularization. Defaults to True. |
True
|
simplify_tolerance
|
float
|
Tolerance for the initial simplification step (if |
0.5
|
allow_45_degree
|
bool
|
If True, allows edges to be oriented at 45-degree angles relative to the main direction during regularization. Defaults to True. |
True
|
diagonal_threshold_reduction
|
float
|
Reduction factor in degrees to reduce the likelihood of diagonal edges being created. Larger values reduce the likelihood of diagonal edges. Defaults to 15. |
15
|
allow_circles
|
bool
|
If True, attempts to detect polygons that are nearly circular and replaces them with perfect circles. Defaults to True. |
True
|
circle_threshold
|
float
|
Intersection over Union (IoU) threshold used for circle detection
(if |
0.9
|
num_cores
|
int
|
Number of CPU cores to use for parallel processing. If 1, processing is done sequentially. Defaults to 1. |
1
|
include_metadata
|
bool
|
If True, includes metadata about the regularization process in the output GeoDataFrame. Defaults to False. |
False
|
output_path
|
Optional[str]
|
Path to save the output GeoDataFrame. If None, the output is not saved. Defaults to None. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
gpd.GeoDataFrame: A new GeoDataFrame with regularized polygon geometries. Original attributes are |
Any
|
preserved. Geometries that failed processing might be dropped. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input data is not a GeoDataFrame or a file path, or if the input GeoDataFrame is empty. |
Source code in geoai/utils/geometry.py
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 | |
Segmentation metrics and evaluation utilities.
calc_f1_score(ground_truth, prediction, num_classes=None, ignore_index=None, smooth=1e-06, band=1)
¶
Calculate F1 score between ground truth and prediction masks.
The F1 score is the harmonic mean of precision and recall, computed as: F1 = 2 * (precision * recall) / (precision + recall) where precision = TP / (TP + FP) and recall = TP / (TP + FN).
This function supports both binary and multi-class segmentation, and can handle numpy arrays, PyTorch tensors, or file paths to raster files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ground_truth
|
Union[str, ndarray, Tensor]
|
Ground truth segmentation mask. Can be a file path (str) to a raster file, numpy array, or PyTorch tensor. For binary segmentation: shape (H, W) with values {0, 1}. For multi-class segmentation: shape (H, W) with class indices. |
required |
prediction
|
Union[str, ndarray, Tensor]
|
Predicted segmentation mask. Can be a file path (str) to a raster file, numpy array, or PyTorch tensor. Should have the same shape and format as ground_truth. |
required |
num_classes
|
Optional[int]
|
Number of classes for multi-class segmentation. If None, assumes binary segmentation. Defaults to None. |
None
|
ignore_index
|
Optional[int]
|
Class index to ignore in computation. Useful for ignoring background or unlabeled pixels. Defaults to None. |
None
|
smooth
|
float
|
Smoothing factor to avoid division by zero. Defaults to 1e-6. |
1e-06
|
band
|
int
|
Band index to read from raster file (1-based indexing). Only used when input is a file path. Defaults to 1. |
1
|
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
Union[float, np.ndarray]: For binary segmentation, returns a single float F1 score. For multi-class segmentation, returns an array of F1 scores for each class. |
Examples:
1 2 3 4 5 6 | |
1 2 3 4 5 6 | |
1 2 3 4 5 6 | |
1 2 3 4 | |
Source code in geoai/utils/metrics.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
calc_iou(ground_truth, prediction, num_classes=None, ignore_index=None, smooth=1e-06, band=1)
¶
Calculate Intersection over Union (IoU) between ground truth and prediction masks.
This function computes the IoU metric for segmentation tasks. It supports both binary and multi-class segmentation, and can handle numpy arrays, PyTorch tensors, or file paths to raster files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ground_truth
|
Union[str, ndarray, Tensor]
|
Ground truth segmentation mask. Can be a file path (str) to a raster file, numpy array, or PyTorch tensor. For binary segmentation: shape (H, W) with values {0, 1}. For multi-class segmentation: shape (H, W) with class indices. |
required |
prediction
|
Union[str, ndarray, Tensor]
|
Predicted segmentation mask. Can be a file path (str) to a raster file, numpy array, or PyTorch tensor. Should have the same shape and format as ground_truth. |
required |
num_classes
|
Optional[int]
|
Number of classes for multi-class segmentation. If None, assumes binary segmentation. Defaults to None. |
None
|
ignore_index
|
Optional[int]
|
Class index to ignore in computation. Useful for ignoring background or unlabeled pixels. Defaults to None. |
None
|
smooth
|
float
|
Smoothing factor to avoid division by zero. Defaults to 1e-6. |
1e-06
|
band
|
int
|
Band index to read from raster file (1-based indexing). Only used when input is a file path. Defaults to 1. |
1
|
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
Union[float, np.ndarray]: For binary segmentation, returns a single float IoU score. For multi-class segmentation, returns an array of IoU scores for each class. |
Examples:
1 2 3 4 5 6 | |
1 2 3 4 5 6 | |
1 2 3 4 5 6 | |
1 2 3 4 | |
Source code in geoai/utils/metrics.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
calc_segmentation_metrics(ground_truth, prediction, num_classes=None, ignore_index=None, smooth=1e-06, metrics=['iou', 'f1'], band=1)
¶
Calculate multiple segmentation metrics between ground truth and prediction masks.
This is a convenient wrapper function that computes multiple metrics at once, including IoU (Intersection over Union) and F1 score. It supports both binary and multi-class segmentation, and can handle numpy arrays, PyTorch tensors, or file paths to raster files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ground_truth
|
Union[str, ndarray, Tensor]
|
Ground truth segmentation mask. Can be a file path (str) to a raster file, numpy array, or PyTorch tensor. For binary segmentation: shape (H, W) with values {0, 1}. For multi-class segmentation: shape (H, W) with class indices. |
required |
prediction
|
Union[str, ndarray, Tensor]
|
Predicted segmentation mask. Can be a file path (str) to a raster file, numpy array, or PyTorch tensor. Should have the same shape and format as ground_truth. |
required |
num_classes
|
Optional[int]
|
Number of classes for multi-class segmentation. If None, assumes binary segmentation. Defaults to None. |
None
|
ignore_index
|
Optional[int]
|
Class index to ignore in computation. Useful for ignoring background or unlabeled pixels. Defaults to None. |
None
|
smooth
|
float
|
Smoothing factor to avoid division by zero. Defaults to 1e-6. |
1e-06
|
metrics
|
List[str]
|
List of metrics to calculate. Options: "iou", "f1". Defaults to ["iou", "f1"]. |
['iou', 'f1']
|
band
|
int
|
Band index to read from raster file (1-based indexing). Only used when input is a file path. Defaults to 1. |
1
|
Returns:
| Type | Description |
|---|---|
Dict[str, Union[float, ndarray]]
|
Dict[str, Union[float, np.ndarray]]: Dictionary containing the computed metrics. Keys are metric names ("iou", "f1"), values are the metric scores. For binary segmentation, values are floats. For multi-class segmentation, values are numpy arrays with per-class scores. Also includes "mean_iou" and "mean_f1" for multi-class segmentation (mean computed over valid classes, ignoring NaN values). |
Examples:
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 | |
1 2 3 4 5 6 | |
1 2 3 4 5 6 | |
Source code in geoai/utils/metrics.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
Model inspection and loading utilities.
inspect_pth_file(pth_path)
¶
Inspect a PyTorch .pth model file to determine its architecture.
Logs detailed information about the model's layer structure, architecture indicators, and output classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pth_path
|
str
|
Path to the .pth file to inspect |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If pth_path does not exist. |
Source code in geoai/utils/models.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
try_common_architectures(state_dict)
¶
Try to load the state_dict into common architectures to see which one fits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
Dict[str, Any]
|
The model's state dictionary |
required |
Source code in geoai/utils/models.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
Raster I/O and processing utilities.
RasterMetadata
¶
Bases: NamedTuple
Commonly-needed raster metadata returned by :func:read_raster_metadata.
This avoids repeating the with rasterio.open(...) as src: boilerplate
every time you need CRS, transform, bounds, shape, or nodata.
Source code in geoai/utils/raster.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
batch_vector_to_raster(vector_path, output_dir, attribute_field=None, reference_rasters=None, bounds_list=None, output_filename_pattern='{vector_name}_{index}', pixel_size=1.0, all_touched=False, fill_value=0, dtype=np.uint8, nodata=None)
¶
Batch convert vector data to multiple rasters based on different extents or reference rasters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str or GeoDataFrame
|
Path to the input vector file or a GeoDataFrame. |
required |
output_dir
|
str
|
Directory to save output raster files. |
required |
attribute_field
|
str
|
Field name in the vector data to use for pixel values. |
None
|
reference_rasters
|
list
|
List of paths to reference rasters for dimensions, transform and CRS. |
None
|
bounds_list
|
list
|
List of bounds tuples (left, bottom, right, top) to use if reference_rasters not provided. |
None
|
output_filename_pattern
|
str
|
Pattern for output filenames. Can include {vector_name} and {index} placeholders. |
'{vector_name}_{index}'
|
pixel_size
|
float or tuple
|
Pixel size to use if reference_rasters not provided. |
1.0
|
all_touched
|
bool
|
If True, all pixels touched by geometries will be burned in. |
False
|
fill_value
|
int
|
Value to fill the raster with before burning in features. |
0
|
dtype
|
dtype
|
Data type of the output raster. |
uint8
|
nodata
|
int
|
No data value for the output raster. |
None
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: List of paths to the created raster files. |
Source code in geoai/utils/raster.py
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 | |
calc_stats(dataset, divide_by=1.0)
¶
Calculate the statistics (mean and std) for the entire dataset.
This function is adapted from the plot_batch() function in the torchgeo library at https://torchgeo.readthedocs.io/en/stable/tutorials/earth_surface_water.html. Credit to the torchgeo developers for the original implementation.
Warning: This is an approximation. The correct value should take into account the mean for the whole dataset for computing individual stds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
RasterDataset
|
The dataset to calculate statistics for. |
required |
divide_by
|
float
|
The value to divide the image data by. Defaults to 1.0. |
1.0
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Tuple[np.ndarray, np.ndarray]: The mean and standard deviation for each band. |
Source code in geoai/utils/raster.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
clean_instance_mask(input_path, output_path=None, min_area=50, fill_holes=True, max_hole_area=100, smooth=True, smooth_sigma=1.5, band=1)
¶
Clean an instance segmentation mask raster.
Removes small instances, fills holes within instances, and optionally
smooths instance boundaries using Gaussian contour smoothing. Unlike
clean_raster (which is designed for semantic/classification masks),
this function preserves the unique identity of each instance.
The smoothing works by applying a Gaussian blur to each instance's binary mask and re-thresholding at 0.5, which effectively rounds jagged staircase edges into smooth curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Path to the input GeoTIFF instance mask where each non-zero pixel value is a unique instance ID. |
required |
output_path
|
Optional[str]
|
Path to save the cleaned GeoTIFF. If None, a
|
None
|
min_area
|
int
|
Minimum area in pixels for an instance to be kept. Instances smaller than this are set to 0 (background). Defaults to 50. |
50
|
fill_holes
|
bool
|
Whether to fill holes (background pixels fully enclosed within an instance) with the surrounding instance ID. Defaults to True. |
True
|
max_hole_area
|
int
|
Maximum hole size in pixels to fill. Holes
larger than this are left as background. Only used when
|
100
|
smooth
|
bool
|
Whether to smooth jagged instance boundaries using Gaussian blur and re-thresholding. Defaults to True. |
True
|
smooth_sigma
|
float
|
Standard deviation for the Gaussian blur used in boundary smoothing. Larger values produce smoother boundaries but may shrink small instances. Defaults to 1.5. |
1.5
|
band
|
int
|
Band index to read (1-indexed). Defaults to 1. |
1
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the cleaned output GeoTIFF. |
Example
import geoai geoai.clean_instance_mask( ... "prediction.tif", ... "prediction_cleaned.tif", ... min_area=100, ... smooth_sigma=2.0, ... )
Source code in geoai/utils/raster.py
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 | |
clip_raster_by_bbox(input_raster, output_raster, bbox, bands=None, bbox_type='geo', bbox_crs=None)
¶
Clip a raster dataset using a bounding box and optionally select specific bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_raster
|
str
|
Path to the input raster file. |
required |
output_raster
|
str
|
Path where the clipped raster will be saved. |
required |
bbox
|
tuple
|
Bounding box coordinates either as: - Geographic coordinates (minx, miny, maxx, maxy) if bbox_type="geo" - Pixel indices (min_row, min_col, max_row, max_col) if bbox_type="pixel" |
required |
bands
|
list
|
List of band indices to keep (1-based indexing). If None, all bands will be kept. |
None
|
bbox_type
|
str
|
Type of bounding box coordinates. Either "geo" for geographic coordinates or "pixel" for row/column indices. Default is "geo". |
'geo'
|
bbox_crs
|
str or dict
|
CRS of the bbox if different from the raster CRS. Can be provided as EPSG code (e.g., "EPSG:4326") or as a proj4 string. Only applies when bbox_type="geo". If None, assumes bbox is in the same CRS as the raster. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the clipped output raster. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If required dependencies are not installed. |
ValueError
|
If the bbox is invalid, bands are out of range, or bbox_type is invalid. |
RuntimeError
|
If the clipping operation fails. |
Examples:
Clip using geographic coordinates in the same CRS as the raster
1 2 | |
Clip using WGS84 coordinates when the raster is in a different CRS
1 2 3 | |
Clip using row/column indices
1 2 3 | |
Clip with band selection
1 2 3 | |
Source code in geoai/utils/raster.py
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | |
get_raster_info(raster_path)
¶
Display basic information about a raster dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict[str, Any]
|
Dictionary containing the basic information about the raster |
Source code in geoai/utils/raster.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
get_raster_info_gdal(raster_path)
¶
Get basic information about a raster dataset using GDAL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing the basic information about the raster, or None if the file cannot be opened |
Source code in geoai/utils/raster.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
get_raster_resolution(image_path)
¶
Get pixel resolution from the raster using rasterio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str
|
The path to the raster image. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[float, float]
|
A tuple of (x resolution, y resolution). |
Source code in geoai/utils/raster.py
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 | |
get_raster_stats(raster_path, divide_by=1.0)
¶
Calculate statistics for each band in a raster dataset.
This function computes min, max, mean, and standard deviation values for each band in the provided raster, returning results in a dictionary with lists for each statistic type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
divide_by
|
float
|
Value to divide pixel values by. Defaults to 1.0, which keeps the original pixel |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict[str, Any]
|
Dictionary containing lists of statistics with keys: - 'min': List of minimum values for each band - 'max': List of maximum values for each band - 'mean': List of mean values for each band - 'std': List of standard deviation values for each band |
Source code in geoai/utils/raster.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
masks_to_vector(mask_path, output_path=None, simplify_tolerance=1.0, mask_threshold=0.5, min_object_area=100, max_object_area=None, nms_iou_threshold=0.5)
¶
Convert a building mask GeoTIFF to vector polygons and save as a vector dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_path
|
str
|
Path to the building masks GeoTIFF |
required |
output_path
|
Optional[str]
|
Path to save the output GeoJSON (default: mask_path with .geojson extension) |
None
|
simplify_tolerance
|
float
|
Tolerance for polygon simplification (default: self.simplify_tolerance) |
1.0
|
mask_threshold
|
float
|
Threshold for mask binarization (default: self.mask_threshold) |
0.5
|
min_object_area
|
int
|
Minimum area in pixels to keep a building (default: self.min_object_area) |
100
|
max_object_area
|
Optional[int]
|
Maximum area in pixels to keep a building (default: self.max_object_area) |
None
|
nms_iou_threshold
|
float
|
IoU threshold for non-maximum suppression (default: self.nms_iou_threshold) |
0.5
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
GeoDataFrame
|
GeoDataFrame with building footprints |
Source code in geoai/utils/raster.py
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 | |
mosaic_geotiffs(input_dir, output_file, mask_file=None)
¶
Create a mosaic from all GeoTIFF files as a Cloud Optimized GeoTIFF (COG).
This function identifies all GeoTIFF files in the specified directory, creates a seamless mosaic with proper handling of nodata values, and saves as a Cloud Optimized GeoTIFF format. If a mask file is provided, the output will be clipped to the extent of the mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
str
|
Path to the directory containing GeoTIFF files. |
required |
output_file
|
str
|
Path to the output Cloud Optimized GeoTIFF file. |
required |
mask_file
|
str
|
Path to a mask file to clip the output. If provided, the output will be clipped to the extent of this mask. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
None
|
True if the mosaic was created successfully, False otherwise. |
Examples:
1 2 3 4 | |
Source code in geoai/utils/raster.py
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 | |
print_raster_info(raster_path, show_preview=True, figsize=(10, 8))
¶
Print formatted information about a raster dataset and optionally show a preview.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
show_preview
|
bool
|
Whether to display a visual preview of the raster. Defaults to True. |
True
|
figsize
|
tuple
|
Figure size as (width, height). Defaults to (10, 8). |
(10, 8)
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing raster information if successful, None otherwise |
Source code in geoai/utils/raster.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
raster_to_vector(raster_path, output_path=None, threshold=0, min_area=10, simplify_tolerance=None, class_values=None, attribute_name='class', unique_attribute_value=False, output_format='geojson', plot_result=False)
¶
Convert a raster label mask to vector polygons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the input raster file (e.g., GeoTIFF). |
required |
output_path
|
str
|
Path to save the output vector file. If None, returns GeoDataFrame without saving. |
None
|
threshold
|
int / float
|
Pixel values greater than this threshold will be vectorized. |
0
|
min_area
|
float
|
Minimum polygon area in square map units to keep. |
10
|
simplify_tolerance
|
float
|
Tolerance for geometry simplification. None for no simplification. |
None
|
class_values
|
list
|
Specific pixel values to vectorize. If None, all values > threshold are vectorized. |
None
|
attribute_name
|
str
|
Name of the attribute field for the class values. |
'class'
|
unique_attribute_value
|
bool
|
Whether to generate unique values for each shape within a class. |
False
|
output_format
|
str
|
Format for output file - 'geojson', 'shapefile', 'gpkg'. Auto-detected from the file extension of output_path when possible. |
'geojson'
|
plot_result
|
bool
|
Whether to plot the resulting polygons overlaid on the raster. |
False
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
geopandas.GeoDataFrame: A GeoDataFrame containing the vectorized polygons. |
Source code in geoai/utils/raster.py
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 | |
raster_to_vector_batch(input_dir, output_dir, pattern='*.tif', threshold=0, min_area=10, simplify_tolerance=None, class_values=None, attribute_name='class', output_format='geojson', merge_output=False, merge_filename='merged_vectors')
¶
Batch convert multiple raster files to vector polygons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
str
|
Directory containing input raster files. |
required |
output_dir
|
str
|
Directory to save output vector files. |
required |
pattern
|
str
|
Pattern to match raster files (e.g., '*.tif'). |
'*.tif'
|
threshold
|
int / float
|
Pixel values greater than this threshold will be vectorized. |
0
|
min_area
|
float
|
Minimum polygon area in square map units to keep. |
10
|
simplify_tolerance
|
float
|
Tolerance for geometry simplification. None for no simplification. |
None
|
class_values
|
list
|
Specific pixel values to vectorize. If None, all values > threshold are vectorized. |
None
|
attribute_name
|
str
|
Name of the attribute field for the class values. |
'class'
|
output_format
|
str
|
Format for output files - 'geojson', 'shapefile', 'gpkg'. |
'geojson'
|
merge_output
|
bool
|
Whether to merge all output vectors into a single file. |
False
|
merge_filename
|
str
|
Filename for the merged output (without extension). |
'merged_vectors'
|
Returns:
| Type | Description |
|---|---|
Optional[GeoDataFrame]
|
geopandas.GeoDataFrame or None: If merge_output is True, returns the merged GeoDataFrame. |
Source code in geoai/utils/raster.py
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | |
read_raster(source, band=None, masked=True, **kwargs)
¶
Reads raster data from various formats using rioxarray.
This function reads raster data from local files or URLs into a rioxarray data structure with preserved geospatial metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
String path to the raster file or URL. |
required |
band
|
Optional[Union[int, List[int]]]
|
Integer or list of integers specifying which band(s) to read. Defaults to None (all bands). |
None
|
masked
|
bool
|
Boolean indicating whether to mask nodata values. Defaults to True. |
True
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rioxarray.open_rasterio. |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
xarray.DataArray: A DataArray containing the raster data with geospatial metadata preserved. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file format is not supported or source cannot be accessed. |
Examples:
Read a local GeoTIFF
1 2 3 4 5 6 7 | |
Source code in geoai/utils/raster.py
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 | |
read_raster_metadata(raster_path)
¶
Read common metadata from a raster file without loading pixel data.
This is a thin wrapper around rasterio.open() that extracts the
fields most frequently needed (CRS, transform, bounds, shape, dtype,
nodata) and returns them as a lightweight :class:RasterMetadata
named-tuple. Use it to eliminate repeated with rasterio.open(…)
blocks that only inspect metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
RasterMetadata
|
|
Source code in geoai/utils/raster.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
read_vector(source, layer=None, **kwargs)
¶
Reads vector data from various formats including GeoParquet.
This function dynamically determines the file type based on extension and reads it into a GeoDataFrame. It supports both local files and HTTP/HTTPS URLs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
String path to the vector file or URL. |
required |
layer
|
Optional[str]
|
String or integer specifying which layer to read from multi-layer files (only applicable for formats like GPKG, GeoJSON, etc.). Defaults to None. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the underlying reader. |
{}
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
geopandas.GeoDataFrame: A GeoDataFrame containing the vector data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file format is not supported or source cannot be accessed. |
Examples:
Read a local shapefile
1 2 3 4 5 6 7 | |
Source code in geoai/utils/raster.py
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 | |
stack_bands(input_files, output_file, resolution=None, dtype=None, temp_vrt='stack.vrt', overwrite=False, compress='DEFLATE', output_format='COG', extra_gdal_translate_args=None)
¶
Stack bands from multiple images into a single multi-band GeoTIFF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_files
|
List[str]
|
List of input image paths. |
required |
output_file
|
str
|
Path to the output stacked image. |
required |
resolution
|
float
|
Output resolution. If None, inferred from first image. |
None
|
dtype
|
str
|
Output data type (e.g., "UInt16", "Float32"). |
None
|
temp_vrt
|
str
|
Temporary VRT filename. |
'stack.vrt'
|
overwrite
|
bool
|
Whether to overwrite the output file. |
False
|
compress
|
str
|
Compression method. |
'DEFLATE'
|
output_format
|
str
|
GDAL output format (default is "COG"). |
'COG'
|
extra_gdal_translate_args
|
List[str]
|
Extra arguments for gdal_translate. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the output file. |
Source code in geoai/utils/raster.py
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 | |
vector_to_raster(vector_path, output_path=None, reference_raster=None, attribute_field=None, output_shape=None, transform=None, pixel_size=None, bounds=None, crs=None, all_touched=False, fill_value=0, dtype=np.uint8, nodata=None, plot_result=False)
¶
Convert vector data to a raster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str or GeoDataFrame
|
Path to the input vector file or a GeoDataFrame. |
required |
output_path
|
str
|
Path to save the output raster file. If None, returns the array without saving. |
None
|
reference_raster
|
str
|
Path to a reference raster for dimensions, transform and CRS. |
None
|
attribute_field
|
str
|
Field name in the vector data to use for pixel values. If None, all vector features will be burned with value 1. |
None
|
output_shape
|
tuple
|
Shape of the output raster as (height, width). Required if reference_raster is not provided. |
None
|
transform
|
Affine
|
Affine transformation matrix. Required if reference_raster is not provided. |
None
|
pixel_size
|
float or tuple
|
Pixel size (resolution) as single value or (x_res, y_res). Used to calculate transform if transform is not provided. |
None
|
bounds
|
tuple
|
Bounds of the output raster as (left, bottom, right, top). Used to calculate transform if transform is not provided. |
None
|
crs
|
str or CRS
|
Coordinate reference system of the output raster. Required if reference_raster is not provided. |
None
|
all_touched
|
bool
|
If True, all pixels touched by geometries will be burned in. If False, only pixels whose center is within the geometry will be burned in. |
False
|
fill_value
|
int
|
Value to fill the raster with before burning in features. |
0
|
dtype
|
dtype
|
Data type of the output raster. |
uint8
|
nodata
|
int
|
No data value for the output raster. |
None
|
plot_result
|
bool
|
Whether to plot the resulting raster. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
numpy.ndarray: The rasterized data array if output_path is None, else None. |
Source code in geoai/utils/raster.py
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 | |
write_colormap(image, colormap, output=None)
¶
Write a colormap to an image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Union[str, ndarray]
|
The image to write the colormap to. |
required |
colormap
|
Union[str, Dict]
|
The colormap to write to the image. |
required |
output
|
Optional[str]
|
The output file path. |
None
|
Source code in geoai/utils/raster.py
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 | |
Training data export and augmentation utilities.
export_flipnslide_tiles(in_raster, out_folder, in_class_data=None, tile_size=256, output_format='tif', crop_to_multiple=True, quiet=False)
¶
Export georeferenced tiles using the Flip-n-Slide augmentation strategy.
This function applies the Flip-n-Slide tiling algorithm to an image raster (and optionally a corresponding label/mask raster), preserving spatial relationships and geospatial information. Each tile is saved as an individual GeoTIFF file with proper CRS and geotransform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_raster
|
str
|
Path to the input raster image. |
required |
out_folder
|
str
|
Path to the output folder where tiles will be saved. |
required |
in_class_data
|
str
|
Path to a classification/mask file. Can be a raster file (GeoTIFF, etc.) or vector file (GeoJSON, Shapefile, etc.). When provided, matching mask tiles are generated with identical augmentations. Vector files are rasterized to match the input raster dimensions and CRS. Defaults to None. |
None
|
tile_size
|
int
|
Size of each square tile in pixels. Defaults to 256. |
256
|
output_format
|
str
|
File extension for the output tiles
(e.g., |
'tif'
|
crop_to_multiple
|
bool
|
If |
True
|
quiet
|
bool
|
If |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Statistics dictionary with keys:
|
Example
stats = export_flipnslide_tiles("image.tif", "output_tiles/") print(f"Generated {stats['total_tiles']} tiles")
stats = export_flipnslide_tiles( ... "image.tif", "output_tiles/", ... in_class_data="mask.tif", tile_size=512, ... )
Notes
Both input raster and class data (if provided) must share the same CRS and spatial extent for proper alignment.
Source code in geoai/utils/training.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 | |
export_geotiff_tiles(in_raster, out_folder, in_class_data=None, tile_size=256, stride=128, class_value_field='class', buffer_radius=0, max_tiles=None, quiet=False, all_touched=True, create_overview=False, skip_empty_tiles=False, metadata_format='PASCAL_VOC', apply_augmentation=False, augmentation_count=3, augmentation_transforms=None, tiling_strategy='grid')
¶
Export georeferenced GeoTIFF tiles and labels from raster and classification data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_raster
|
str
|
Path to input raster image |
required |
out_folder
|
str
|
Path to output folder |
required |
in_class_data
|
str
|
Path to classification data - can be vector file or raster. If None, only image tiles will be exported without labels. Defaults to None. |
None
|
tile_size
|
int
|
Size of tiles in pixels (square) |
256
|
stride
|
int
|
Step size between tiles |
128
|
class_value_field
|
str
|
Field containing class values (for vector data) |
'class'
|
buffer_radius
|
float
|
Buffer to add around features (in units of the CRS) |
0
|
max_tiles
|
int
|
Maximum number of tiles to process (None for all) |
None
|
quiet
|
bool
|
If True, suppress non-essential output |
False
|
all_touched
|
bool
|
Whether to use all_touched=True in rasterization (for vector data) |
True
|
create_overview
|
bool
|
Whether to create an overview image of all tiles |
False
|
skip_empty_tiles
|
bool
|
If True, skip tiles with no features |
False
|
metadata_format
|
str
|
Output metadata format (PASCAL_VOC, COCO, YOLO). Default: PASCAL_VOC |
'PASCAL_VOC'
|
apply_augmentation
|
bool
|
If True, generate augmented versions of each tile. This will create multiple variants of each tile using data augmentation techniques. Defaults to False. |
False
|
augmentation_count
|
int
|
Number of augmented versions to generate per tile (only used if apply_augmentation=True). Defaults to 3. |
3
|
augmentation_transforms
|
Compose
|
Custom augmentation transforms. If None and apply_augmentation=True, uses default transforms from get_default_augmentation_transforms(). Should be an albumentations.Compose object. Defaults to None. |
None
|
tiling_strategy
|
str
|
Tiling strategy to use. Options are: - "grid": Regular grid tiling with specified stride (default behavior) - "flipnslide": Flip-n-Slide augmentation strategy with overlapping tiles Defaults to "grid". |
'grid'
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
Tiles and labels are saved to out_folder. |
Example
Export tiles without augmentation¶
export_geotiff_tiles('image.tif', 'output/', 'labels.tif')
Export tiles with default augmentation (3 augmented versions per tile)¶
export_geotiff_tiles('image.tif', 'output/', 'labels.tif', ... apply_augmentation=True)
Export with custom augmentation¶
import albumentations as A custom_transform = A.Compose([ ... A.HorizontalFlip(p=0.5), ... A.RandomBrightnessContrast(p=0.5), ... ]) export_geotiff_tiles('image.tif', 'output/', 'labels.tif', ... apply_augmentation=True, ... augmentation_count=5, ... augmentation_transforms=custom_transform)
Export with Flip-n-Slide tiling strategy¶
export_geotiff_tiles('image.tif', 'output/', 'labels.tif', ... tiling_strategy='flipnslide')
Source code in geoai/utils/training.py
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 | |
export_geotiff_tiles_batch(images_folder, masks_folder=None, masks_file=None, output_folder=None, tile_size=256, stride=128, class_value_field='class', buffer_radius=0, max_tiles=None, quiet=False, all_touched=True, skip_empty_tiles=False, image_extensions=None, mask_extensions=None, match_by_name=False, metadata_format='PASCAL_VOC')
¶
Export georeferenced GeoTIFF tiles from images and optionally masks.
This function supports four modes: 1. Images only (no masks) - when neither masks_file nor masks_folder is provided 2. Single vector file covering all images (masks_file parameter) 3. Multiple vector files, one per image (masks_folder parameter) 4. Multiple raster mask files (masks_folder parameter)
For mode 1 (images only), only image tiles will be exported without labels.
For mode 2 (single vector file), specify masks_file path. The function will use spatial intersection to determine which features apply to each image.
For mode 3/4 (multiple mask files), specify masks_folder path. Images and masks are paired either by matching filenames (match_by_name=True) or by sorted order (match_by_name=False).
All image tiles are saved to a single 'images' folder and all mask tiles (if provided) to a single 'masks' folder within the output directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images_folder
|
str
|
Path to folder containing raster images |
required |
masks_folder
|
str
|
Path to folder containing classification masks/vectors. Use this for multiple mask files (one per image or raster masks). If not provided and masks_file is also not provided, only image tiles will be exported. |
None
|
masks_file
|
str
|
Path to a single vector file covering all images. Use this for a single GeoJSON/Shapefile that covers multiple images. If not provided and masks_folder is also not provided, only image tiles will be exported. |
None
|
output_folder
|
str
|
Path to output folder. If None, creates 'tiles' subfolder in images_folder. |
None
|
tile_size
|
int
|
Size of tiles in pixels (square) |
256
|
stride
|
int
|
Step size between tiles |
128
|
class_value_field
|
str
|
Field containing class values (for vector data) |
'class'
|
buffer_radius
|
float
|
Buffer to add around features (in units of the CRS) |
0
|
max_tiles
|
int
|
Maximum number of tiles to process per image (None for all) |
None
|
quiet
|
bool
|
If True, suppress non-essential output |
False
|
all_touched
|
bool
|
Whether to use all_touched=True in rasterization (for vector data) |
True
|
create_overview
|
bool
|
Whether to create an overview image of all tiles |
required |
skip_empty_tiles
|
bool
|
If True, skip tiles with no features |
False
|
image_extensions
|
list
|
List of image file extensions to process (default: common raster formats) |
None
|
mask_extensions
|
list
|
List of mask file extensions to process (default: common raster/vector formats) |
None
|
match_by_name
|
bool
|
If True, match image and mask files by base filename. If False, match by sorted order (alphabetically). Only applies when masks_folder is used. |
False
|
metadata_format
|
str
|
Annotation format - "PASCAL_VOC" (XML), "COCO" (JSON), or "YOLO" (TXT). Default is "PASCAL_VOC". |
'PASCAL_VOC'
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary containing batch processing statistics |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no images found, or if masks_folder and masks_file are both specified, or if counts don't match when using masks_folder with match_by_name=False. |
Examples:
Images only (no masks)¶
1 2 3 4 | |
Single vector file covering all images¶
1 2 3 4 5 | |
Multiple vector files, matched by filename¶
1 2 3 4 5 6 | |
Multiple mask files, matched by sorted order¶
1 2 3 4 5 6 | |
Source code in geoai/utils/training.py
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 | |
export_training_data(in_raster, out_folder, in_class_data, image_chip_format='GEOTIFF', tile_size_x=256, tile_size_y=256, stride_x=None, stride_y=None, output_nofeature_tiles=True, metadata_format='PASCAL_VOC', start_index=0, class_value_field='class', buffer_radius=0, in_mask_polygons=None, rotation_angle=0, reference_system=None, blacken_around_feature=False, crop_mode='FIXED_SIZE', in_raster2=None, in_instance_data=None, instance_class_value_field=None, min_polygon_overlap_ratio=0.0, all_touched=True, save_geotiff=True, quiet=False)
¶
Export training data for deep learning using TorchGeo with progress bar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_raster
|
str
|
Path to input raster image. |
required |
out_folder
|
str
|
Output folder path where chips and labels will be saved. |
required |
in_class_data
|
str
|
Path to vector file containing class polygons. |
required |
image_chip_format
|
str
|
Output image format (PNG, JPEG, TIFF, GEOTIFF). |
'GEOTIFF'
|
tile_size_x
|
int
|
Width of image chips in pixels. |
256
|
tile_size_y
|
int
|
Height of image chips in pixels. |
256
|
stride_x
|
int
|
Horizontal stride between chips. If None, uses tile_size_x. |
None
|
stride_y
|
int
|
Vertical stride between chips. If None, uses tile_size_y. |
None
|
output_nofeature_tiles
|
bool
|
Whether to export chips without features. |
True
|
metadata_format
|
str
|
Output metadata format (PASCAL_VOC, KITTI, COCO). |
'PASCAL_VOC'
|
start_index
|
int
|
Starting index for chip filenames. |
0
|
class_value_field
|
str
|
Field name in in_class_data containing class values. |
'class'
|
buffer_radius
|
float
|
Buffer radius around features (in CRS units). |
0
|
in_mask_polygons
|
str
|
Path to vector file containing mask polygons. |
None
|
rotation_angle
|
float
|
Rotation angle in degrees. |
0
|
reference_system
|
str
|
Reference system code. |
None
|
blacken_around_feature
|
bool
|
Whether to mask areas outside of features. |
False
|
crop_mode
|
str
|
Crop mode (FIXED_SIZE, CENTERED_ON_FEATURE). |
'FIXED_SIZE'
|
in_raster2
|
str
|
Path to secondary raster image. |
None
|
in_instance_data
|
str
|
Path to vector file containing instance polygons. |
None
|
instance_class_value_field
|
str
|
Field name in in_instance_data for instance classes. |
None
|
min_polygon_overlap_ratio
|
float
|
Minimum overlap ratio for polygons. |
0.0
|
all_touched
|
bool
|
Whether to use all_touched=True in rasterization. |
True
|
save_geotiff
|
bool
|
Whether to save as GeoTIFF with georeferencing. |
True
|
quiet
|
bool
|
If True, suppress most output messages. |
False
|
Source code in geoai/utils/training.py
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 | |
flipnslide_augmentation(image, tile_size=256, output_format='numpy', crop_to_multiple=True)
¶
Apply Flip-n-Slide tiling strategy for geospatial imagery data augmentation.
This function implements the Flip-n-Slide algorithm from "A Concise Tiling Strategy for Preserving Spatial Context in Earth Observation Imagery" by Abrahams et al., presented at the ML4RS workshop at ICLR 2024 (best short paper). The strategy generates overlapping tiles with diverse augmentations while eliminating redundant pixel representations.
The algorithm produces two sets of tiles:
-
Standard overlapping tiles with half-stride (stride = tile_size / 2) and rotational augmentations determined by grid position:
-
Even row, even col: identity (no augmentation)
- Odd row, even col: 180 degree rotation
- Even row, odd col: 90 degree rotation
-
Odd row, odd col: 270 degree rotation
-
Inner offset tiles extracted from the image interior (inset by tile_size / 2 from each edge) with the same half-stride, applying flip and rotation augmentations:
-
Even row, even col: horizontal flip
- Even row, odd col: vertical flip
- Odd row, odd col: 90 degree rotation + horizontal flip
- Odd row, even col: 90 degree rotation + vertical flip
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Union[str, ndarray]
|
Input image as a numpy array of
shape |
required |
tile_size
|
int
|
Size of each square tile in pixels. Defaults to 256. |
256
|
output_format
|
str
|
|
'numpy'
|
crop_to_multiple
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
|
Tuple[Union[numpy.ndarray, torch.Tensor], List[int]]:
- tiles -- Array of shape
|
Example
import numpy as np image = np.random.rand(3, 512, 512) tiles, aug_indices = flipnslide_augmentation(image, tile_size=256) print(f"Generated {tiles.shape[0]} tiles of shape {tiles.shape[1:]}") print(f"Augmentation types used: {sorted(set(aug_indices))}")
References
Abrahams, E., Snow, T., Siegfried, M. R., & Perez, F. (2024). A Concise Tiling Strategy for Preserving Spatial Context in Earth Observation Imagery. ML4RS Workshop @ ICLR 2024. https://doi.org/10.48550/arXiv.2404.10927
Source code in geoai/utils/training.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
get_default_augmentation_transforms(tile_size=256, include_normalize=False, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
¶
Get default data augmentation transforms for geospatial imagery using albumentations.
This function returns a composition of augmentation transforms commonly used for remote sensing and geospatial data. The transforms include geometric transformations (flips, rotations) and photometric adjustments (brightness, contrast, saturation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile_size
|
int
|
Target size for tiles. Defaults to 256. |
256
|
include_normalize
|
bool
|
Whether to include normalization transform. Defaults to False. Set to True if using for training with pretrained models. |
False
|
mean
|
tuple
|
Mean values for normalization (RGB). Defaults to ImageNet values. |
(0.485, 0.456, 0.406)
|
std
|
tuple
|
Standard deviation for normalization (RGB). Defaults to ImageNet values. |
(0.229, 0.224, 0.225)
|
Returns:
| Type | Description |
|---|---|
Any
|
albumentations.Compose: A composition of augmentation transforms. |
Example
import albumentations as A
Get default transforms¶
transform = get_default_augmentation_transforms()
Apply to image and mask¶
augmented = transform(image=image, mask=mask) aug_image = augmented['image'] aug_mask = augmented['mask']
Source code in geoai/utils/training.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
Vector I/O and processing utilities.
add_geometric_properties(data, properties=None, area_unit='m2', length_unit='m')
¶
Calculates geometric properties and adds them to the GeoDataFrame.
This function calculates various geometric properties of features in a GeoDataFrame and adds them as new columns without modifying existing attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
GeoDataFrame
|
GeoDataFrame containing vector features. |
required |
properties
|
Optional[List[str]]
|
List of geometric properties to calculate. Options include: 'area', 'length', 'perimeter', 'centroid_x', 'centroid_y', 'bounds', 'convex_hull_area', 'orientation', 'complexity', 'area_bbox', 'area_convex', 'area_filled', 'major_length', 'minor_length', 'eccentricity', 'diameter_area', 'extent', 'solidity', 'elongation'. Defaults to ['area', 'length'] if None. |
None
|
area_unit
|
str
|
String specifying the unit for area calculation ('m2', 'km2', 'ha'). Defaults to 'm2'. |
'm2'
|
length_unit
|
str
|
String specifying the unit for length calculation ('m', 'km'). Defaults to 'm'. |
'm'
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
geopandas.GeoDataFrame: A copy of the input GeoDataFrame with added |
GeoDataFrame
|
geometric property columns. |
Source code in geoai/utils/vector.py
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 | |
analyze_vector_attributes(vector_path, attribute_name)
¶
Analyze a specific attribute in a vector dataset and create a histogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
attribute_name
|
str
|
Name of the attribute to analyze |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing analysis results for the attribute |
Source code in geoai/utils/vector.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
boxes_to_vector(coords, src_crs, dst_crs='EPSG:4326', output=None, **kwargs)
¶
Convert a list of bounding box coordinates to vector data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
list
|
A list of bounding box coordinates in the format [[left, top, right, bottom], [left, top, right, bottom], ...]. |
required |
src_crs
|
int or str
|
The EPSG code or proj4 string representing the source coordinate reference system (CRS) of the input coordinates. |
required |
dst_crs
|
int or str
|
The EPSG code or proj4 string representing the destination CRS to reproject the data (default is "EPSG:4326"). |
'EPSG:4326'
|
output
|
str or None
|
The full file path (including the directory and filename without the extension) where the vector data should be saved. If None (default), the function returns the GeoDataFrame without saving it to a file. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to geopandas.GeoDataFrame.to_file() when saving the vector data. |
{}
|
Returns:
| Type | Description |
|---|---|
Optional[GeoDataFrame]
|
geopandas.GeoDataFrame or None: The GeoDataFrame with the converted vector data if output is None, otherwise None if the data is saved to a file. |
Source code in geoai/utils/vector.py
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 | |
export_tiles_to_geojson(tile_coordinates, src, output_path, tile_size=None, stride=None)
¶
Export tile rectangles directly to GeoJSON without creating an overview image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile_coordinates
|
list
|
A list of dictionaries containing tile information. |
required |
src
|
DatasetReader
|
The source raster dataset. |
required |
output_path
|
str
|
The path where the GeoJSON will be saved. |
required |
tile_size
|
int
|
The size of each tile in pixels. Only needed if not in tile_coordinates. |
None
|
stride
|
int
|
The stride between tiles in pixels. Used to calculate overlaps between tiles. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the saved GeoJSON file. |
Source code in geoai/utils/vector.py
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | |
geojson_to_coords(geojson, src_crs='epsg:4326', dst_crs='epsg:4326')
¶
Converts a geojson file or a dictionary of feature collection to a list of centroid coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geojson
|
str | dict
|
The geojson file path or a dictionary of feature collection. |
required |
src_crs
|
str
|
The source CRS. Defaults to "epsg:4326". |
'epsg:4326'
|
dst_crs
|
str
|
The destination CRS. Defaults to "epsg:4326". |
'epsg:4326'
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
List[List[float]]
|
A list of centroid coordinates in the format of [[x1, y1], [x2, y2], ...] |
Source code in geoai/utils/vector.py
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 | |
geojson_to_xy(src_fp, geojson, coord_crs='epsg:4326', **kwargs)
¶
Converts a geojson file or a dictionary of feature collection to a list of pixel coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
geojson
|
str
|
The geojson file path or a dictionary of feature collection. |
required |
coord_crs
|
str
|
The coordinate CRS of the input coordinates. Defaults to "epsg:4326". |
'epsg:4326'
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rasterio.transform.rowcol. |
{}
|
Returns:
| Type | Description |
|---|---|
List[List[float]]
|
A list of pixel coordinates in the format of [[x1, y1], [x2, y2], ...] |
Source code in geoai/utils/vector.py
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 | |
get_vector_info(vector_path)
¶
Display basic information about a vector dataset using GeoPandas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing the basic information about the vector dataset |
Source code in geoai/utils/vector.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
get_vector_info_ogr(vector_path)
¶
Get basic information about a vector dataset using OGR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing the basic information about the vector dataset, or None if the file cannot be opened |
Source code in geoai/utils/vector.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
print_vector_info(vector_path, show_preview=True, figsize=(10, 8))
¶
Print formatted information about a vector dataset and optionally show a preview.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
show_preview
|
bool
|
Whether to display a visual preview of the vector data. Defaults to True. |
True
|
figsize
|
tuple
|
Figure size as (width, height). Defaults to (10, 8). |
(10, 8)
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing vector information if successful, None otherwise |
Source code in geoai/utils/vector.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
smooth_vector(vector_data, output_path=None, segment_length=None, smooth_iterations=3, num_cores=0, merge_collection=True, merge_field=None, merge_multipolygons=True, preserve_area=True, area_tolerance=0.01, **kwargs)
¶
Smooth a vector data using the smoothify library. See https://github.com/DPIRD-DMA/Smoothify for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_data
|
Union[str, GeoDataFrame]
|
The vector data to smooth. |
required |
output_path
|
str
|
The path to save the smoothed vector data. If None, returns the smoothed vector data. |
None
|
segment_length
|
float
|
Resolution of the original raster data in map units. If None (default), automatically detects by finding the minimum segment length (from a data sample). Recommended to specify explicitly when known. |
None
|
smooth_iterations
|
int
|
The number of iterations to smooth the vector data. |
3
|
num_cores
|
int
|
Number of cores to use for parallel processing. If 0 (default), uses all available cores. |
0
|
merge_collection
|
bool
|
Whether to merge/dissolve adjacent geometries in collections before smoothing. |
True
|
merge_field
|
str
|
Column name to use for dissolving geometries. Only valid when merge_collection=True. If None, dissolves all geometries together. If specified, dissolves geometries grouped by the column values. |
None
|
merge_multipolygons
|
bool
|
Whether to merge adjacent polygons within MultiPolygons before smoothing |
True
|
preserve_area
|
bool
|
Whether to restore original area after smoothing via buffering (applies to Polygons only) |
True
|
area_tolerance
|
float
|
Percentage of original area allowed as error (e.g., 0.01 = 0.01% error = 99.99% preservation). Only affects Polygons when preserve_area=True |
0.01
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
gpd.GeoDataFrame: The smoothed vector data. |
Examples:
1 2 3 4 5 | |
Source code in geoai/utils/vector.py
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 | |
vector_to_geojson(filename, output=None, **kwargs)
¶
Converts a vector file to a geojson file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
The vector file path. |
required |
output
|
str
|
The output geojson file path. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Union[Dict, str]]
|
The geojson dictionary. |
Source code in geoai/utils/vector.py
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 | |
visualize_vector_by_attribute(vector_path, attribute_name, cmap='viridis', figsize=(10, 8))
¶
Create a thematic map visualization of vector data based on an attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
attribute_name
|
str
|
Name of the attribute to visualize |
required |
cmap
|
str
|
Matplotlib colormap name. Defaults to 'viridis'. |
'viridis'
|
figsize
|
tuple
|
Figure size as (width, height). Defaults to (10, 8). |
(10, 8)
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if visualization was successful, False otherwise |
Source code in geoai/utils/vector.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
Visualization utilities for raster and vector data.
create_overview_image(src, tile_coordinates, output_path, tile_size, stride, geojson_path=None, in_class_data=None)
¶
Create an overview image showing all tiles and their status, with optional GeoJSON export.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
DatasetReader
|
The source raster dataset. |
required |
tile_coordinates
|
list
|
A list of dictionaries containing tile information. |
required |
output_path
|
str
|
The path where the overview image will be saved. |
required |
tile_size
|
int
|
The size of each tile in pixels. |
required |
stride
|
int
|
The stride between tiles in pixels. Controls overlap between adjacent tiles. |
required |
geojson_path
|
str
|
If provided, exports the tile rectangles as GeoJSON to this path. |
None
|
in_class_data
|
str
|
Path to classification data (vector or raster). If provided, shows the mask/label overlay instead of the raw satellite image. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the saved overview image. |
Source code in geoai/utils/visualization.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 | |
create_split_map(left_layer='TERRAIN', right_layer='OpenTopoMap', left_args=None, right_args=None, left_array_args=None, right_array_args=None, zoom_control=True, fullscreen_control=True, layer_control=True, add_close_button=False, left_label=None, right_label=None, left_position='bottomleft', right_position='bottomright', widget_layout=None, draggable=True, center=[20, 0], zoom=2, height='600px', basemap=None, basemap_args=None, m=None, **kwargs)
¶
Adds split map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left_layer
|
str
|
The left tile layer. Can be a local file path, HTTP URL, or a basemap name. Defaults to 'TERRAIN'. |
'TERRAIN'
|
right_layer
|
str
|
The right tile layer. Can be a local file path, HTTP URL, or a basemap name. Defaults to 'OpenTopoMap'. |
'OpenTopoMap'
|
left_args
|
dict
|
The arguments for the left tile layer. Defaults to {}. |
None
|
right_args
|
dict
|
The arguments for the right tile layer. Defaults to {}. |
None
|
left_array_args
|
dict
|
The arguments for array_to_image for the left layer. Defaults to {}. |
None
|
right_array_args
|
dict
|
The arguments for array_to_image for the right layer. Defaults to {}. |
None
|
zoom_control
|
bool
|
Whether to add zoom control. Defaults to True. |
True
|
fullscreen_control
|
bool
|
Whether to add fullscreen control. Defaults to True. |
True
|
layer_control
|
bool
|
Whether to add layer control. Defaults to True. |
True
|
add_close_button
|
bool
|
Whether to add a close button. Defaults to False. |
False
|
left_label
|
str
|
The label for the left layer. Defaults to None. |
None
|
right_label
|
str
|
The label for the right layer. Defaults to None. |
None
|
left_position
|
str
|
The position for the left label. Defaults to "bottomleft". |
'bottomleft'
|
right_position
|
str
|
The position for the right label. Defaults to "bottomright". |
'bottomright'
|
widget_layout
|
dict
|
The layout for the widget. Defaults to None. |
None
|
draggable
|
bool
|
Whether the split map is draggable. Defaults to True. |
True
|
Source code in geoai/utils/visualization.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 | |
display_image_with_vector(image_path, vector_path, figsize=(16, 8), vector_color='red', vector_linewidth=1, vector_facecolor='none', save_path=None)
¶
Display a raster image alongside the same image with vector overlay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str
|
Path to raster image file |
required |
vector_path
|
str
|
Path to vector file (GeoJSON, Shapefile, etc.) |
required |
figsize
|
tuple
|
Figure size as (width, height) in inches (default: (16, 8)) |
(16, 8)
|
vector_color
|
str
|
Edge color for vector features (default: 'red') |
'red'
|
vector_linewidth
|
float
|
Line width for vector features (default: 1) |
1
|
vector_facecolor
|
str
|
Fill color for vector features (default: 'none') |
'none'
|
save_path
|
str
|
If provided, save figure to this path instead of displaying |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(fig, axes, info_dict) where info_dict contains image and vector metadata |
Example
fig, axes, info = display_image_with_vector( ... 'image.tif', ... 'buildings.geojson', ... vector_color='blue' ... ) print(f"Number of features: {info['num_features']}")
Source code in geoai/utils/visualization.py
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
display_training_tiles(output_dir, num_tiles=6, figsize=(18, 6), cmap='gray', show_axes=True, save_path=None, image_subdir=None, mask_subdir=None)
¶
Display image and mask tile pairs from training data output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Path to output directory containing image and mask subdirectories. |
required |
num_tiles
|
int
|
Number of tile pairs to display (default: 6). |
6
|
figsize
|
tuple
|
Figure size as (width, height) in inches (default: (18, 6)). |
(18, 6)
|
cmap
|
str
|
Colormap for mask display (default: 'gray'). |
'gray'
|
show_axes
|
bool
|
Whether to show row/column pixel labels on the axes. When True, axes display pixel-based row and column indices instead of CRS coordinates. Defaults to True. |
True
|
save_path
|
str
|
If provided, save figure to this path instead of displaying. |
None
|
image_subdir
|
str
|
Name of the subdirectory containing image tiles. If None, auto-detects by looking for 'images' or 'image' subdirectories. Defaults to None. |
None
|
mask_subdir
|
str
|
Name of the subdirectory containing mask/label tiles. If None, auto-detects by looking for 'masks', 'mask', 'labels', or 'label' subdirectories. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(fig, axes) matplotlib figure and axes objects. |
Example
fig, axes = display_training_tiles('output/tiles', num_tiles=6)
Show with row/col pixel labels¶
fig, axes = display_training_tiles('output/tiles', show_axes=True)
Use custom subdirectory names¶
fig, axes = display_training_tiles('output/tiles', mask_subdir='labels')
Or save to file¶
display_training_tiles('output/tiles', num_tiles=4, save_path='tiles_preview.png')
Source code in geoai/utils/visualization.py
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 | |
plot_batch(batch, bright=1.0, cols=4, width=5, chnls=[2, 1, 0], cmap='Blues')
¶
Plot a batch of images and masks. This function is adapted from the plot_batch() function in the torchgeo library at https://torchgeo.readthedocs.io/en/stable/tutorials/earth_surface_water.html Credit to the torchgeo developers for the original implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Dict[str, Any]
|
The batch containing images and masks. |
required |
bright
|
float
|
The brightness factor. Defaults to 1.0. |
1.0
|
cols
|
int
|
The number of columns in the plot grid. Defaults to 4. |
4
|
width
|
int
|
The width of each plot. Defaults to 5. |
5
|
chnls
|
List[int]
|
The channels to use for RGB. Defaults to [2, 1, 0]. |
[2, 1, 0]
|
cmap
|
str
|
The colormap to use for masks. Defaults to "Blues". |
'Blues'
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in geoai/utils/visualization.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
plot_images(images, axs, chnls=[2, 1, 0], bright=1.0)
¶
Plot a list of images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Iterable[Tensor]
|
The images to plot. |
required |
axs
|
Iterable[Axes]
|
The axes to plot the images on. |
required |
chnls
|
List[int]
|
The channels to use for RGB. Defaults to [2, 1, 0]. |
[2, 1, 0]
|
bright
|
float
|
The brightness factor. Defaults to 1.0. |
1.0
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in geoai/utils/visualization.py
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
plot_masks(masks, axs, cmap='Blues')
¶
Plot a list of masks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
masks
|
Iterable[Tensor]
|
The masks to plot. |
required |
axs
|
Iterable[Axes]
|
The axes to plot the masks on. |
required |
cmap
|
str
|
The colormap to use. Defaults to "Blues". |
'Blues'
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in geoai/utils/visualization.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
plot_performance_metrics(history_path, figsize=None, verbose=True, save_path=None, csv_path=None, kwargs=None)
¶
Plot performance metrics from a training history object and return as DataFrame.
This function loads training history, plots available metrics (loss, IoU, F1, precision, recall), optionally exports to CSV, and returns all metrics as a pandas DataFrame for further analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history_path
|
str
|
Path to the saved training history (.pth file). |
required |
figsize
|
Optional[Tuple[int, int]]
|
Figure size in inches. If None, automatically determined based on number of metrics. |
None
|
verbose
|
bool
|
Whether to print best and final metric values. Defaults to True. |
True
|
save_path
|
Optional[str]
|
Path to save the plot image. If None, plot is not saved. |
None
|
csv_path
|
Optional[str]
|
Path to export metrics as CSV. If None, CSV is not exported. |
None
|
kwargs
|
Optional[Dict]
|
Additional keyword arguments for plt.savefig(). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame containing all metrics with columns for epoch and each metric. Columns include: 'epoch', 'train_loss', 'val_loss', 'val_iou', 'val_f1', 'val_precision', 'val_recall' (depending on availability in history). |
Example
df = plot_performance_metrics( ... 'training_history.pth', ... save_path='metrics_plot.png', ... csv_path='metrics.csv' ... ) print(df.head())
Source code in geoai/utils/visualization.py
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 | |
plot_prediction_comparison(original_image, prediction_image, ground_truth_image=None, titles=None, figsize=(15, 5), save_path=None, show_plot=True, prediction_colormap='gray', ground_truth_colormap='gray', original_colormap=None, indexes=None, divider=None)
¶
Plot original image, prediction, and optional ground truth side by side.
Supports input as file paths, NumPy arrays, or PIL Images. For multi-band
images, selected channels can be specified via indexes. If the image data
is not normalized (e.g., Sentinel-2 [0, 10000]), the divider can be used
to scale values for visualization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_image
|
Union[str, ndarray, Image]
|
Original input image as a file path, NumPy array, or PIL Image. |
required |
prediction_image
|
Union[str, ndarray, Image]
|
Predicted segmentation mask image. |
required |
ground_truth_image
|
Optional[Union[str, ndarray, Image]]
|
Ground truth mask image. Defaults to None. |
None
|
titles
|
Optional[List[str]]
|
List of titles for the subplots. If not provided, default titles are used. |
None
|
figsize
|
Tuple[int, int]
|
Size of the entire figure in inches. Defaults to (15, 5). |
(15, 5)
|
save_path
|
Optional[str]
|
If specified, saves the figure to this path. Defaults to None. |
None
|
show_plot
|
bool
|
Whether to display the figure using plt.show(). Defaults to True. |
True
|
prediction_colormap
|
str
|
Colormap to use for the prediction mask. Defaults to "gray". |
'gray'
|
ground_truth_colormap
|
str
|
Colormap to use for the ground truth mask. Defaults to "gray". |
'gray'
|
original_colormap
|
Optional[str]
|
Colormap to use for the original image if it's grayscale. Defaults to None. |
None
|
indexes
|
Optional[List[int]]
|
List of band/channel indexes (0-based for NumPy, 1-based for rasterio) to extract from the original image. Useful for multi-band imagery like Sentinel-2. Defaults to None. |
None
|
divider
|
Optional[float]
|
Value to divide the original image by for normalization (e.g., 10000 for reflectance). Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
matplotlib.figure.Figure: The generated matplotlib figure object. |
Source code in geoai/utils/visualization.py
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 | |
view_image(image, transpose=False, bdx=None, clip_percentiles=(2, 98), gamma=None, figsize=(10, 5), axis_off=True, title=None, **kwargs)
¶
Visualize an image using matplotlib.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Union[ndarray, Tensor]
|
The image to visualize. |
required |
transpose
|
bool
|
Whether to transpose the image. Defaults to False. |
False
|
bdx
|
Optional[int]
|
The band index to visualize. Defaults to None. |
None
|
figsize
|
Tuple[int, int]
|
The size of the figure. Defaults to (10, 5). |
(10, 5)
|
axis_off
|
bool
|
Whether to turn off the axis. Defaults to True. |
True
|
title
|
Optional[str]
|
The title of the plot. Defaults to None. |
None
|
**kwargs
|
Any
|
Additional keyword arguments for plt.imshow(). |
{}
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in geoai/utils/visualization.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
view_raster(source, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, layer_name='Raster', layer_index=None, zoom_to_layer=True, visible=True, opacity=1.0, array_args=None, client_args={'cors_all': False}, legend_args=None, basemap='OpenStreetMap', basemap_args=None, backend='folium', **kwargs)
¶
Visualize a raster using leafmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
The source of the raster. |
required |
indexes
|
Optional[int]
|
The band indexes to visualize. Defaults to None. |
None
|
colormap
|
Optional[str]
|
The colormap to apply. Defaults to None. |
None
|
vmin
|
Optional[float]
|
The minimum value for colormap scaling. Defaults to None. |
None
|
vmax
|
Optional[float]
|
The maximum value for colormap scaling. Defaults to None. |
None
|
nodata
|
Optional[float]
|
The nodata value. Defaults to None. |
None
|
attribution
|
Optional[str]
|
The attribution for the raster. Defaults to None. |
None
|
layer_name
|
Optional[str]
|
The name of the layer. Defaults to "Raster". |
'Raster'
|
layer_index
|
Optional[int]
|
The index of the layer. Defaults to None. |
None
|
zoom_to_layer
|
Optional[bool]
|
Whether to zoom to the layer. Defaults to True. |
True
|
visible
|
Optional[bool]
|
Whether the layer is visible. Defaults to True. |
True
|
opacity
|
Optional[float]
|
The opacity of the layer. Defaults to 1.0. |
1.0
|
array_args
|
Optional[Dict]
|
Additional arguments for array processing. Defaults to {}. |
None
|
client_args
|
Optional[Dict]
|
Additional arguments for the client. Defaults to {"cors_all": False}. |
{'cors_all': False}
|
legend_args
|
Optional[Dict]
|
Additional arguments for the legend. Defaults to None. |
None
|
basemap
|
Optional[str]
|
The basemap to use. Defaults to "OpenStreetMap". |
'OpenStreetMap'
|
basemap_args
|
Optional[Dict]
|
Additional arguments for the basemap. Defaults to None. |
None
|
backend
|
Optional[str]
|
The backend to use. Defaults to "folium". |
'folium'
|
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
leafmap.Map: The map object with the raster layer added. |
Source code in geoai/utils/visualization.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
view_vector(vector_data, column=None, cmap='viridis', figsize=(10, 10), title=None, legend=True, basemap=False, basemap_type='streets', alpha=0.7, edge_color='black', classification='quantiles', n_classes=5, highlight_index=None, highlight_color='red', scheme=None, save_path=None, dpi=300, raster_path=None, raster_bands=None, raster_cmap='gray', outline_only=False, outline_linewidth=1.0)
¶
Visualize vector datasets with options for styling, classification, basemaps and more.
This function visualizes GeoDataFrame objects with customizable symbology. It supports different vector types (points, lines, polygons), attribute-based classification, background basemaps, and raster backgrounds with polygon outlines overlaid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_data
|
Union[str, GeoDataFrame]
|
The vector dataset to visualize. Can be a file path or a GeoDataFrame. |
required |
column
|
str
|
Column to use for choropleth mapping. If None, a single color will be used. Ignored when outline_only is True. Defaults to None. |
None
|
cmap
|
str or Colormap
|
Colormap to use for choropleth mapping. Defaults to "viridis". |
'viridis'
|
figsize
|
tuple
|
Figure size as (width, height) in inches. Defaults to (10, 10). |
(10, 10)
|
title
|
str
|
Title for the plot. Defaults to None. |
None
|
legend
|
bool
|
Whether to display a legend. Defaults to True. |
True
|
basemap
|
bool
|
Whether to add a web basemap. Requires contextily. Ignored when raster_path is provided. Defaults to False. |
False
|
basemap_type
|
str
|
Type of basemap to use. Options: 'streets', 'satellite'. Defaults to 'streets'. |
'streets'
|
alpha
|
float
|
Transparency of the vector features, between 0-1. Defaults to 0.7. |
0.7
|
edge_color
|
str
|
Color for feature edges. Defaults to "black". |
'black'
|
classification
|
str
|
Classification method for choropleth maps. Options: "quantiles", "equal_interval", "natural_breaks". Defaults to "quantiles". |
'quantiles'
|
n_classes
|
int
|
Number of classes for choropleth maps. Defaults to 5. |
5
|
highlight_index
|
list
|
List of indices to highlight. Defaults to None. |
None
|
highlight_color
|
str
|
Color to use for highlighted features. Defaults to "red". |
'red'
|
scheme
|
str
|
MapClassify classification scheme. Overrides classification parameter if provided. Defaults to None. |
None
|
save_path
|
str
|
Path to save the figure. If None, the figure is not saved. Defaults to None. |
None
|
dpi
|
int
|
DPI for saved figure. Defaults to 300. |
300
|
raster_path
|
str
|
Path to a raster file to display as the background. The vector data will be reprojected to match the raster CRS if needed. When provided, the basemap option is ignored. Defaults to None. |
None
|
raster_bands
|
int or list of int
|
Band index or list of band indices (1-indexed) to display from the raster. If None, all bands are shown (RGB if 3 bands). Defaults to None. |
None
|
raster_cmap
|
str
|
Colormap for single-band raster display. Defaults to "gray". |
'gray'
|
outline_only
|
bool
|
If True, polygon features are drawn as outlines only (no fill), allowing the raster background to show through. Has no effect on point or line geometries. Defaults to False. |
False
|
outline_linewidth
|
float
|
Line width for polygon outlines when outline_only is True. Defaults to 1.0. |
1.0
|
Returns:
| Type | Description |
|---|---|
Any
|
matplotlib.axes.Axes: The Axes object containing the plot. |
Examples:
1 2 3 | |
1 2 | |
1 2 3 4 5 6 7 8 | |
Source code in geoai/utils/visualization.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
view_vector_interactive(vector_data, layer_name='Vector', tiles_args=None, opacity=0.7, **kwargs)
¶
Visualize vector datasets with options for styling, classification, basemaps and more.
This function visualizes GeoDataFrame objects with customizable symbology. It supports different vector types (points, lines, polygons), attribute-based classification, and background basemaps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_data
|
GeoDataFrame
|
The vector dataset to visualize. |
required |
layer_name
|
str
|
The name of the layer. Defaults to "Vector". |
'Vector'
|
tiles_args
|
dict
|
Additional arguments for the localtileserver client. get_folium_tile_layer function. Defaults to None. |
None
|
opacity
|
float
|
The opacity of the layer. Defaults to 0.7. |
0.7
|
**kwargs
|
Any
|
Additional keyword arguments to pass to GeoDataFrame.explore() function. See https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoDataFrame.explore.html |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
folium.Map: The map object with the vector data added. |
Examples:
1 2 3 | |
1 2 | |
Source code in geoai/utils/visualization.py
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 | |