rivabar.data_io¶
rivabar.data_io
¶
MinimalDataset(crs, transform, shape)
¶
A minimal dataset placeholder that stores essential raster information.
This class provides the same interface as rasterio datasets for the basic attributes needed by river objects (crs, transform, shape).
Initialize a minimal dataset with basic raster information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crs
|
str or CRS
|
Coordinate reference system |
required |
transform
|
Affine
|
Affine transformation matrix |
required |
shape
|
tuple
|
Shape of the raster (height, width) |
required |
Source code in rivabar/data_io.py
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 | |
xy(row, col, offset='center')
¶
Return the (x, y) coordinates of a pixel, like rasterio datasets.
Source code in rivabar/data_io.py
666 667 668 669 | |
process_band(dirname, fname, band_numbers)
¶
Helper function to open and read a specific band.
Args: dirname: Path to folder that conatins the Landsat TIF files. fname: Name of Landsat tile or individual TIF file. band_numbers: Band numbers.
Returns: bands: The band data. dataset: The rasterio dataset.
Source code in rivabar/data_io.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
read_landsat_data(dirname, fname, mndwi_threshold=0.01)
¶
Read Landsat data from multiple TIF files and perform various operations.
Args: dirname (str): Directory name where the TIF files are located. fname (str): File name prefix. mndwi_threshold (float): Threshold value for MNDWI.
Returns: tuple: A tuple containing the processed image, MNDWI mask, and transformation parameters.
Source code in rivabar/data_io.py
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 | |
read_water_index(dirname, fname, mndwi_threshold, type='mndwi')
¶
Read a water index raster file and apply thresholding.
This function opens a water index raster file, applies a threshold to create a binary water mask, and extracts the geospatial information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dirname
|
str
|
Directory path where the water index file is located. |
required |
fname
|
str
|
Filename of the water index raster. |
required |
mndwi_threshold
|
float or str
|
Threshold value for the water index. Values above this threshold will be set to 1 (water), others to 0 (non-water). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
mndwi |
ndarray
|
Binary water mask where 1 represents water and 0 represents non-water. |
left_utm_x |
float
|
The UTM x-coordinate of the left edge of the raster. |
upper_utm_y |
float
|
The UTM y-coordinate of the upper edge of the raster. |
right_utm_x |
float
|
The UTM x-coordinate of the right edge of the raster. |
lower_utm_y |
float
|
The UTM y-coordinate of the lower edge of the raster. |
Source code in rivabar/data_io.py
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 | |
create_mndwi(dirname, fname, file_type, water_index_type='mndwi', mndwi_threshold=0.01, delete_pixels_polys=False, small_hole_threshold=64, remove_smaller_components=True, solidity_filter=False, max_water_fraction=0.15)
¶
Create a Modified Normalized Difference Water Index (MNDWI) binary mask from input data.
This function processes either a water index raster or Landsat data to create a binary water mask. It can filter out small holes, remove small components, and apply solidity filtering to improve the water mask quality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dirname
|
str
|
Directory path where the input file is located. |
required |
fname
|
str
|
Filename of the input raster. |
required |
file_type
|
str
|
Type of input file. Can be 'water_index' for a single water index raster or another value for Landsat TIF files. |
required |
mndwi_threshold
|
float or str
|
Threshold value for the water index. Values above this threshold will be set to 1 (water), others to 0 (non-water). Default is 0.01. |
0.01
|
delete_pixels_polys
|
bool or list
|
List of polygons to mask out from the water index (e.g., bridges), or False to skip this step. Default is False. |
False
|
small_hole_threshold
|
int
|
Minimum size (in pixels) of holes to keep in the water mask. Smaller holes will be filled. Default is 64. |
64
|
remove_smaller_components
|
bool
|
Whether to remove small disconnected water bodies, keeping only the largest component. Default is True. |
True
|
solidity_filter
|
bool
|
Whether to filter objects based on solidity (area/convex hull area). Objects with solidity < 0.2 will be removed. Default is False. |
False
|
max_water_fraction
|
float or None
|
Maximum fraction of valid pixels that can be classified as water. If exceeded, the scene is assumed to be cloud-contaminated (clouds produce positive MNDWI values that get misclassified as water) and the function returns None. Set to None to disable. Default is 0.15 (normal river scenes typically have 1-3% water). |
0.15
|
Returns:
| Name | Type | Description |
|---|---|---|
mndwi |
ndarray
|
Binary water mask where 1 represents water and 0 represents non-water. |
left_utm_x |
float
|
The UTM x-coordinate of the left edge of the raster. |
upper_utm_y |
float
|
The UTM y-coordinate of the upper edge of the raster. |
right_utm_x |
float
|
The UTM x-coordinate of the right edge of the raster. |
lower_utm_y |
float
|
The UTM y-coordinate of the lower edge of the raster. |
delta_x |
float
|
The pixel width in UTM coordinates. |
delta_y |
float
|
The pixel height in UTM coordinates. |
dataset |
DatasetReader
|
The opened raster dataset with metadata. |
Source code in rivabar/data_io.py
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 | |
save_shapefiles(dirname, fname, G_rook, dataset, fname_add_on='')
¶
Save shapefiles for bank polygons and centerline polygons from a graph structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dirname
|
str
|
The directory name where the shapefiles will be saved. |
required |
fname
|
str
|
The base filename for the shapefiles. |
required |
G_rook
|
Graph
|
A graph structure containing nodes with 'bank_polygon' and 'cl_polygon' geometries. |
required |
dataset
|
GeoDataFrame
|
A GeoDataFrame containing the coordinate reference system (CRS) information. |
required |
fname_add_on
|
str
|
An additional string to append to the filenames (default is ''). |
''
|
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in rivabar/data_io.py
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 | |
crop_geotiff(input_file, output_file, row_off, col_off, max_rows=2 ** 16 // 2, max_cols=2 ** 16 // 2)
¶
Crop a GeoTIFF file and save the cropped portion to a new file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_file
|
str
|
Path to the input GeoTIFF file. |
required |
output_file
|
str
|
Path to the output cropped GeoTIFF file. |
required |
row_off
|
int
|
The row offset (starting row) for the cropping window. |
required |
col_off
|
int
|
The column offset (starting column) for the cropping window. |
required |
max_rows
|
int
|
The maximum number of rows in the cropped image (default is 2**16 // 2). |
2 ** 16 // 2
|
max_cols
|
int
|
The maximum number of columns in the cropped image (default is 2**16 // 2). |
2 ** 16 // 2
|
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in rivabar/data_io.py
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 | |
downsample_raster(input_path, output_path, scale_factor=0.5)
¶
Downsample a raster by a given scale factor.
Args:
input_path (str): Path to input raster
output_path (str): Path to output raster
scale_factor (float): Scale factor (0.5 = half size)
Source code in rivabar/data_io.py
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 | |
read_and_plot_im(dirname, fname)
¶
Reads a raster image from a file and plots it using matplotlib.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dirname
|
str
|
The directory name where the raster file is located. |
required |
fname
|
str
|
The filename of the raster file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
im |
ndarray
|
The raster image data. |
dataset |
DatasetReader
|
The dataset object containing metadata and other information about the raster. |
left_utm_x |
float
|
The UTM x-coordinate of the left edge of the raster. |
right_utm_x |
float
|
The UTM x-coordinate of the right edge of the raster. |
lower_utm_y |
float
|
The UTM y-coordinate of the lower edge of the raster. |
upper_utm_y |
float
|
The UTM y-coordinate of the upper edge of the raster. |
Source code in rivabar/data_io.py
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 | |
gdfs_from_D_primal(D_primal, dataset)
¶
Create two GeoDataFrames (one for nodes and one for edges) from a primal graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
D_primal
|
MultiDiGraph
|
The primal graph containing nodes and edges with geometries and attributes. |
required |
dataset
|
GeoDataFrame
|
The dataset containing the coordinate reference system (CRS) information. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
node_df |
GeoDataFrame
|
A GeoDataFrame containing the nodes with their geometries. |
edge_df |
GeoDataFrame
|
A GeoDataFrame containing the edges with their geometries and attributes. |
Notes
If you want to save the edge dataframe as a shapefile, you need to drop the 'widths' column.
Source code in rivabar/data_io.py
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 | |
write_shapefiles_and_graphs(G_rook, D_primal, dataset, dirname, rivername, ch_mouth_poly=None)
¶
Writes shapefiles and graph data to specified directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G_rook
|
Graph
|
The rook graph representing the river network. |
required |
D_primal
|
Graph
|
The primal graph representing the river network. |
required |
dataset
|
GeoDataFrame
|
The dataset containing the river network data. |
required |
dirname
|
str
|
The directory name where the files will be saved. |
required |
rivername
|
str
|
The name of the river, used as a prefix for the filenames. |
required |
ch_mouth_poly
|
Polygon
|
The polygon representing the channel mouth, by default None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in rivabar/data_io.py
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 | |
merge_and_plot_channel_polygons(fnames)
¶
Merges multiple channel polygons from shapefiles and plots the resulting polygon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fnames
|
list of str
|
List of file paths to the shapefiles containing the channel polygons. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
big_poly |
Polygon or MultiPolygon
|
The merged polygon resulting from the union of all input polygons. |
Notes
- The function assumes that each shapefile contains at least one polygon.
- If a shapefile contains multiple polygons, only the first one is considered.
- The resulting merged polygon is plotted using matplotlib with the exterior in 'cornflowerblue' and interiors in white.
Source code in rivabar/data_io.py
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 | |
save_planetscope_river_result(river, source_files, save_dir='planetscope_results', scene_id=None, cloud_cover=None, **extra_metadata)
¶
Convenience function to save PlanetScope river results with automatic metadata extraction.
This function extracts metadata from PlanetScope filenames and saves the river object with all relevant information in the same format as Landsat batch processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
river
|
River
|
The river object to save |
required |
source_files
|
list
|
List of source PlanetScope files used to create the mosaic |
required |
save_dir
|
str
|
Directory to save results (default: 'planetscope_results') |
'planetscope_results'
|
scene_id
|
str
|
Custom scene identifier. If None, will be auto-generated |
None
|
cloud_cover
|
float
|
Cloud cover percentage |
None
|
**extra_metadata
|
dict
|
Additional metadata to store |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Path to saved pickle file |
Examples:
>>> # From your notebook:
>>> fnames = glob.glob('/path/to/20250612*AnalyticMS_SR_8b_clip.tif')
>>> result_file = rb.save_planetscope_river_result(
... river,
... source_files=fnames,
... scene_id='rio_beni_20250612',
... cloud_cover=10.5,
... location='Rio Beni',
... processing_notes='DDWI threshold auto-detected'
... )
Source code in rivabar/data_io.py
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 | |
create_water_mask_from_mapping(G_rook, dataset, output_path=None, include_islands=True, buffer_distance=0, fill_value=1, nodata_value=0)
¶
Create a water mask raster from rivabar mapping results.
This function creates a water mask by: 1. Creating a bounding polygon from the image extent 2. Subtracting all land polygons (main banks and islands) from it 3. The remaining area is water
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G_rook
|
Graph
|
Graph from rivabar mapping containing 'bank_polygon' attributes on nodes. Nodes 0 and 1 are the main channel banks (land), nodes 2+ are islands/bars (land). |
required |
dataset
|
DatasetReader or MinimalDataset
|
Dataset with georeferencing information (crs, transform, shape/bounds). |
required |
output_path
|
str
|
Path to save the water mask as a GeoTIFF. If None, only returns the array. |
None
|
include_islands
|
bool
|
If True, subtract island/bar areas from water (they become land). Default is True. |
True
|
buffer_distance
|
float
|
Buffer distance to apply to land polygons (positive = expand land, negative = shrink). Default is 0. |
0
|
fill_value
|
int
|
Value for water pixels (default is 1). |
1
|
nodata_value
|
int
|
Value for land/nodata pixels (default is 0). |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
water_mask |
ndarray
|
2D binary array where fill_value indicates water and nodata_value indicates land. |
Examples:
>>> # After running rivabar mapping
>>> D_primal, G_rook, G_primal, mndwi, dataset, ... = rb.extract_centerline(...)
>>>
>>> # Create water mask
>>> water_mask = rb.create_water_mask_from_mapping(G_rook, dataset)
>>>
>>> # Save to file
>>> water_mask = rb.create_water_mask_from_mapping(G_rook, dataset,
... output_path='water_mask.tif')
Source code in rivabar/data_io.py
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 | |
create_water_mask_from_river(river, output_path=None, **kwargs)
¶
Create a water mask from a River object.
This is a convenience wrapper around create_water_mask_from_mapping that extracts the necessary data from a River object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
river
|
River
|
A processed River object with G_rook and dataset attributes. |
required |
output_path
|
str
|
Path to save the water mask as a GeoTIFF. |
None
|
**kwargs
|
dict
|
Additional keyword arguments passed to create_water_mask_from_mapping. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
water_mask |
ndarray
|
2D binary array where 1 indicates water and 0 indicates land. |
Examples:
>>> river = rb.River(fname=..., dirname=..., ...)
>>> river.map_river_banks(...)
>>> water_mask = rb.create_water_mask_from_river(river, output_path='mask.tif')
Source code in rivabar/data_io.py
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 | |
normalize_image(image, saturation_factor=0.5, percentile_stretch=True)
¶
Normalize an image for display, optionally with reduced saturation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ndarray
|
Image array (height, width, bands). |
required |
saturation_factor
|
float
|
Factor to reduce saturation (0.0 = grayscale, 1.0 = full saturation). Default 0.5. |
0.5
|
percentile_stretch
|
bool
|
Whether to apply a 2-98 percentile stretch per band for better contrast (default True). |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized image with values in [0, 1], ready for display. |
Source code in rivabar/data_io.py
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 | |
crop_image_to_aoi(image_path, aoi_bounds, n_bands=3)
¶
Read an image cropped to an area of interest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str or Path
|
Path to a georeferenced image file. |
required |
aoi_bounds
|
list or tuple
|
(left, right, bottom, top) in the image's coordinate system. |
required |
n_bands
|
int
|
Number of bands to keep (default 3, for RGB display). |
3
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Cropped image array with shape (height, width, bands). |
Source code in rivabar/data_io.py
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 | |
prepare_image_stack(image_files, aoi_bounds, saturation_factor=0.5, percentile_stretch=True)
¶
Crop and normalize a list of images to a common area of interest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_files
|
list of str or pathlib.Path
|
Image files (e.g., from :func: |
required |
aoi_bounds
|
list or tuple
|
(left, right, bottom, top) in the images' coordinate system. |
required |
saturation_factor
|
float
|
Saturation reduction factor passed to :func: |
0.5
|
percentile_stretch
|
bool
|
Whether to percentile-stretch each band (default True). |
True
|
Returns:
| Type | Description |
|---|---|
list of numpy.ndarray or None
|
One normalized (height, width, bands) array per input file, in the same order. Entries are None for images that failed to load, so the list stays aligned with the input (and with any matched river list). |
Source code in rivabar/data_io.py
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 | |