Classes of rastereasy
- class rastereasy.Geoimage(source_name=None, names=None, history=False, data=None, meta=None, georef=None, target_crs='EPSG:4326')[source]
Bases:
object
Main class for manipulating georeferenced raster images.
This class provides a comprehensive toolkit for working with geospatial raster data, supporting operations such as image creation, visualization, band manipulation, reprojection, resampling, cropping, and more.
Parameters
- source_namestr, optional
Path to a GeoTIFF image file to load. If provided, the image data and metadata will be read from this file.
- namesdict, optional
Dictionary mapping band names to band indices (e.g., {‘NIR’: 1, ‘R’: 2, ‘G’: 3}). If not provided, bands will be named numerically (‘1’, ‘2’, ‘3’, …).
- historybool, optional
Whether to track modification history for the image. Default is False.
- datanumpy.ndarray, optional
Image data to initialize the object with. Must be provided with meta. Shape should be (bands, rows, cols).
- metadict, optional
Metadata dictionary containing rasterio metadata fields (e.g., crs, transform). Required if data is provided.
- georefbool, optional
Whether the image is georeferenced. If None, will be determined from metadata.
- target_crsstr, optional
Target coordinate reference system if reprojection is needed during loading. Default is “EPSG:4326”.
Attributes
- imagenumpy.ndarray
The image data array with shape (bands, rows, cols).
- shapetuple
The dimensions of the image as (rows, cols).
- nb_bandsint
The number of spectral bands in the image.
- resolutionfloat
The spatial resolution of the image (pixel size in map units).
- namesdict
Dictionary mapping band names to band indices.
- nodatafloat or int
Value used to represent no data or invalid pixels.
Examples
>>> # Create a Geoimage from a file >>> img = Geoimage("landsat_image.tif") >>> img.info() >>> # Create a Geoimage from a NumPy array with metadata >>> meta = {'driver': 'GTiff', 'width': 100, 'height': 100, 'count': 3, >>> ... 'crs': CRS.from_epsg(4326), 'transform': Affine(0.1, 0, 0, 0, -0.1, 0)} >>> data = np.zeros((3, 100, 100)) >>> img = Geoimage(data=data, meta=meta) >>> # Create a Geoimage with custom band names >>> img = Geoimage("landsat_image.tif", names={'R': 1, 'G': 2, 'B': 3, 'NIR': 4})
- __init__(source_name=None, names=None, history=False, data=None, meta=None, georef=None, target_crs='EPSG:4326')[source]
Initialize a Geoimage object from a file or data array with metadata.
- where(condition, value1, value2)[source]
Select values based on a condition, similar to numpy.where().
This method allows for conditional operations, selecting values from value1 where condition is True, and from value2 where it’s False.
Parameters
- conditionGeoimage
Boolean mask indicating where to select values from value1
- value1Geoimage or scalar
Values to use where condition is True
- value2Geoimage or scalar
Values to use where condition is False
Returns
- Geoimage
New Geoimage containing the result of the conditional selection
Examples
>>> # Create a cloud-free composite from two images >>> cloud_free = image1.where(cloud_mask, image2, image1) >>> >>> # Threshold an image >>> thresholded = image.where(image > 100, 255, 0)
- update_from(other)[source]
Update the current Geoimage with the attributes from another Geoimage.
This method copies all attributes from the other Geoimage to this one, effectively replacing this image’s content with that of other.
Parameters
- otherGeoimage
The Geoimage to copy attributes from
Returns
- None
This method modifies the current object in place
Examples
>>> result = image1.where(mask, 0, image1) # Create a masked copy >>> image1.update_from(result) # Update the original with the masked version
- reset_names()[source]
Reset the band names to sequential numbers (“1”, “2”, …).
This method is useful when multiple stacks, removals, or additions of bands have left the band naming confusing or inconsistent.
Returns
- selfGeoimage
The method returns the object itself to allow method chaining
Examples
>>> stacked_image = image1.apply_stack(image2) >>> stacked_image.reset_names() >>> stacked_image.info() # Shows bands renamed to "1", "2", ...
- change_nodata(nodatavalue)[source]
Modify the no-data value of the image.
Parameters
- nodatavaluefloat or int
The new no-data value to assign
Returns
- selfGeoimage
The method returns the object itself to allow method chaining
Examples
>>> image.change_nodata(np.nan) # Use NaN as nodata >>> image.change_nodata(-9999) # Use -9999 as nodata
- change_names(names)[source]
Modify the names of spectral bands.
Parameters
- namesdict
Dictionary mapping band names to band indices (e.g., {‘R’: 1, ‘G’: 2, ‘B’: 3, ‘NIR’: 4})
Returns
- selfGeoimage
The method returns the object itself to allow method chaining
Raises
- ValueError
If the number of provided names doesn’t match the number of bands
Examples
>>> sentinel2_names = {'B': 1, 'G': 2, 'R': 3, 'NIR': 4, 'SWIR1': 5, 'SWIR2': 6} >>> image.change_names(sentinel2_names) >>> image.info() # Shows updated band names
- activate_history()[source]
Activate history tracking for the image object.
This method enables logging of operations performed on the image, which can be useful for tracking processing steps and debugging.
Returns
- selfGeoimage
The method returns the object itself to allow method chaining
Examples
>>> image = Geoimage("landsat_image.tif") >>> image.activate_history() >>> image.resampling(30,inplace=True) # This operation will be tracked in history >>> image.info() # The history section will show the resampling operation
See Also
deactivate_history : Disable history tracking info : Display image information including history
- deactivate_history()[source]
Deactivate history tracking for the image object.
This method disables logging of operations performed on the image.
Returns
- selfGeoimage
The method returns the object itself to allow method chaining
Examples
>>> image.deactivate_history() >>> image.resampling(15) # This operation won't be tracked in history
See Also
activate_history : Enable history tracking
- copy()[source]
Create a deep copy of the Geoimage object.
Returns
- Geoimage
A new Geoimage instance that is a complete copy of the current object
Examples
>>> original = Geoimage("landsat_image.tif") >>> duplicate = original.copy() >>> duplicate.resampling(15,inplace=True) # This won't affect the original image
Notes
This method creates a completely independent copy. Changes to the copy won’t affect the original image, and vice versa.
- info()[source]
Print detailed information about the image.
This method displays a comprehensive overview of the image’s properties, including: - Dimensions (rows, columns, bands) - Spatial resolution - Geographic coordinates of the center - Projection system - Data type - Nodata value - Band names - Processing history (if history tracking is enabled)
Examples
>>> image = Geoimage("landsat_image.tif") >>> image.info() >>> - Size of the image: >>> - Rows (height): 1024 >>> - Col (width): 1024 >>> - Bands: 4 >>> - Spatial resolution: 30.0 meters / degree >>> - Central point latitude - longitude coordinates: (36.12345, -118.67890) >>> - Driver: GTiff >>> - Data type: uint16 >>> - Projection system: EPSG:32611 >>> - Nodata: 0 >>> - Given names for spectral bands: >>> {'B': 1, 'G': 2, 'R': 3, 'NIR': 4} >>> --- History of modifications--- >>> [2023-09-15 10:30:22] - Read image landsat_image.tif >>> [2023-09-15 10:31:45] - Apply resampling at 30.000000 meters
- get_type()[source]
Get the data type of the image.
Returns
- str
The NumPy data type of the image (e.g., ‘uint8’, ‘float32’)
Examples
>>> data_type = image.get_type() >>> print(f"Image has data type: {data_type}")
- get_spatial_resolution()[source]
Get the spatial resolution of the image.
Returns
- float
The spatial resolution in meters or degrees (depending on the projection)
Examples
>>> resolution = image.get_spatial_resolution() >>> print(f"Image has {resolution} meter resolution")
- get_latlon_coordinates()[source]
Get the latitude and longitude coordinates of the central point of the image.
Returns
- tuple of float
The (latitude, longitude) of the center of the image
Examples
>>> lat, lon = image.get_latlon_coordinates() >>> print(f"Image center is at latitude {lat}, longitude {lon}")
- get_size()[source]
Get the size (dimensions) of the image.
Returns
- tuple of int
The (rows, columns) dimensions of the image
Examples
>>> rows, cols = image.get_size() >>> print(f"Image has {rows} rows and {cols} columns")
- get_nb_bands()[source]
Get the number of spectral bands in the image.
Returns
- int
The number of bands
Examples
>>> nb_bands = image.get_nb_bands() >>> print(f"Image has {nb_bands} spectral bands")
- get_meta()[source]
Get the metadata dictionary.
Returns
- dict
A copy of the rasterio metadata dictionary
Examples
>>> metadata = image.get_meta() >>> print(f"Image CRS: {metadata['crs']}")
- get_nodata()[source]
Get the nodata value of the image.
Returns
- float, int, or None
The nodata value if it exists, otherwise None
Examples
>>> nodata = image.get_nodata() >>> print(f"Nodata value: {nodata}")
- get_bounds()[source]
Get the geographic bounds of the image.
Returns
- rasterio.coords.BoundingBox
The bounding box of the image (left, bottom, right, top)
Examples
>>> bounds = image.get_bounds() >>> print(f"Image covers from ({bounds.left}, {bounds.bottom}) to ({bounds.right}, {bounds.top})")
- get_names()[source]
Get the band names dictionary.
Returns
- dict
A copy of the dictionary mapping band names to band indices
Examples
>>> names = image.get_names() >>> print(f"Red band is at index {names.get('R', 'unknown')}")
- get_georef()[source]
Check if the image is georeferenced.
Returns
- bool
True if the image is georeferenced, False otherwise
Examples
>>> is_georeferenced = image.get_georef() >>> if not is_georeferenced: ... print("Warning: Image is not georeferenced")
- unique()[source]
Get the unique values in the image.
Returns
- numpy.ndarray
Array of unique values found in the image
Examples
>>> unique_values = image.unique() >>> print(f"Image contains {len(unique_values)} unique values") >>> print(f"Values: {unique_values}")
Notes
This method is particularly useful for categorical data or classified images to see how many classes are present.
- abs(axis=None, inplace=False)[source]
Calculate the absolute value of the image data.
This method modifies the image content directly by replacing all values with their absolute values.
Parameters
- axisstr or None, optional
Not used, kept for API consistency with other statistical methods. Default is None.
- inplacebool, default False
If False, return a copy. Otherwise, do absolute value in place and return None.
Returns
- Geoimage
The absolute value image or None if inplace=True
Examples
>>> difference = image1 - image2 # May contain negative values >>> diff_abs = difference.abs() # Compute absolute values of `differences` >>> difference.abs(inplace = True) # Directly convert differences to absolute values >>> difference.info()
- sum(axis=None)[source]
Calculate the sum of image values along a specified axis.
Parameters
- axis{‘band’, ‘row’, ‘col’, None}, optional
The axis along which to compute the sum: - ‘band’: Sum across spectral bands for each pixel - ‘row’: Sum across rows (lines) for each band and column - ‘col’: Sum across columns for each band and row - None: Sum of all values in the image Default is None.
Returns
- float or numpy.ndarray
If axis=None: A single value representing the sum of the entire image
If axis=’band’: Array with shape (nb_rows,nb_cols) containing sums along bands
If axis=’row’: Array with shape (nb_bands,nb_cols) containing sums along rows
If axis=’col’: Array with shape (nb_bands,nb_rows) containing sums along cols
If axis=’pixel’: Array with shape (nb_bands) containing sums along all pixels for each band
Raises
- ValueError
If an invalid axis is specified
Examples
>>> total = image.sum() # Sum of all pixel values >>> print(f"Total pixel sum: {total}") >>> >>> band_sums = image.sum(axis='pixel') # Sum along all pixels for each band
- min(axis=None)[source]
Calculate the minimum value along a specified axis.
Parameters
- axis{‘band’, ‘row’, ‘col’, None}, optional
The axis along which to compute the minimum: - ‘band’: Minimum across spectral bands for each pixel - ‘row’: Minimum across rows (lines) for each band and column - ‘col’: Minimum across columns for each band and row - None: Global minimum of the entire image Default is None.
Returns
- float or numpy.ndarray
If axis=None: A single value representing the global minimum
If axis=’band’: Array with shape (nb_rows,nb_cols) containing mins along bands
If axis=’row’: Array with shape (nb_bands,nb_cols) containing mins along rows
If axis=’col’: Array with shape (nb_bands,nb_rows) containing mins along cols
If axis=’pixel’: Array with shape (nb_bands) containing mins along all pixels for each band
Raises
- ValueError
If an invalid axis is specified
Examples
>>> min_value = image.min() # Global minimum value >>> print(f"Minimum pixel value: {min_value}") >>> >>> band_mins = image.min(axis='pixel') # Minimum along all pixels for each band
- max(axis=None)[source]
Calculate the maximum value along a specified axis.
Parameters
- axis{‘band’, ‘row’, ‘col’, None}, optional
The axis along which to compute the maximum: - ‘band’: Maximum across spectral bands for each pixel - ‘row’: Maximum across rows (lines) for each band and column - ‘col’: Maximum across columns for each band and row - None: Global maximum of the entire image Default is None.
Returns
- float or numpy.ndarray
If axis=None: A single value representing the global maximum
If axis=’band’: Array with shape (nb_rows,nb_cols) containing max along bands
If axis=’row’: Array with shape (nb_bands,nb_cols) containing max along rows
If axis=’col’: Array with shape (nb_bands,nb_rows) containing max along cols
If axis=’pixel’: Array with shape (nb_bands) containing maxs along all pixels for each band
Raises
- ValueError
If an invalid axis is specified
Examples
>>> max_value = image.max() # Global maximum value >>> print(f"Maximum pixel value: {max_value}") >>> >>> band_maxs = image.max(axis='pixel') # Maximum along all pixels for each band
- mean(axis=None)[source]
Calculate the mean value along a specified axis.
Parameters
- axis{‘band’, ‘row’, ‘col’, None}, optional
The axis along which to compute the mean: - ‘band’: Mean across spectral bands for each pixel - ‘row’: Mean across rows (lines) for each band and column - ‘col’: Mean across columns for each band and row - None: Global mean of the entire image Default is None.
Returns
- float or numpy.ndarray
If axis=None: A single value representing the global mean
If axis=’band’: Array with shape (nb_rows,nb_cols) containing mean along bands
If axis=’row’: Array with shape (nb_bands,nb_cols) containing mean along rows
If axis=’col’: Array with shape (nb_bands,nb_rows) containing mean along cols
If axis=’pixel’: Array with shape (nb_bands) containing mean along all pixels for each band
Raises
- ValueError
If an invalid axis is specified
Examples
>>> mean_value = image.mean() # Global mean value >>> print(f"Mean pixel value: {mean_value}") >>> >>> band_means = image.mean(axis='pixel') # Mean along all pixels for each band
Notes
This method uses np.nanmean, which ignores NaN values in the calculation. If you have NaN values as nodata, they won’t affect the mean calculation.
- std(axis=None)[source]
Calculate the standard deviation along a specified axis.
Parameters
- axis{‘band’, ‘row’, ‘col’, None}, optional
The axis along which to compute the standard deviation: - ‘band’: Std dev across spectral bands for each pixel - ‘row’: Std dev across rows (lines) for each band and column - ‘col’: Std dev across columns for each band and row - None: Global standard deviation of the entire image Default is None.
Returns
- float or numpy.ndarray
If axis=None: A single value representing the global std
If axis=’band’: Array with shape (nb_rows,nb_cols) containing std along bands
If axis=’row’: Array with shape (nb_bands,nb_cols) containing std along rows
If axis=’col’: Array with shape (nb_bands,nb_rows) containing std along cols
If axis=’pixel’: Array with shape (nb_bands) containing std along all pixels for each band
Raises
- ValueError
If an invalid axis is specified
Examples
>>> std_value = image.std() # Global standard deviation >>> print(f"Standard deviation of pixel values: {std_value}") >>> >>> band_stds = image.std(axis='pixel') # Standard deviation along all pixels for each band
- median(axis=None)[source]
Calculate the median value along a specified axis.
Parameters
- axis{‘band’, ‘row’, ‘col’, None}, optional
The axis along which to compute the median: - ‘band’: Median across spectral bands for each pixel - ‘row’: Median across rows (lines) for each band and column - ‘col’: Median across columns for each band and row - None: Global median of the entire image Default is None.
Returns
- float or numpy.ndarray
If axis=None: A single value representing the global median
If axis=’band’: Array with shape (nb_rows,nb_cols) containing median along bands
If axis=’row’: Array with shape (nb_bands,nb_cols) containing median along rows
If axis=’col’: Array with shape (nb_bands,nb_rows) containing median along cols
If axis=’pixel’: Array with shape (nb_bands) containing median along all pixels for each band
Raises
- ValueError
If an invalid axis is specified
Examples
>>> median_value = image.median() # Global median value >>> print(f"Median pixel value: {median_value}") >>> >>> band_medians = image.median(axis='pixel') # Median along all pixels for each band
Notes
The median is the value separating the higher half from the lower half of the data. It’s less sensitive to outliers than the mean, making it useful for images with extreme values or noise.
- replace_values(value_to_replace, new_value)[source]
Replace all pixels that match a specified value across all bands.
Parameters
- value_to_replacefloat, int, or array-like
The value(s) to search for in each pixel across all bands: - If a single value: Looks for pixels where all bands equal this value - If an array: Looks for pixels where each band matches the corresponding value
in the array (must have the same length as the number of bands)
- new_valuefloat, int, or array-like
The value(s) to assign to the matching pixels: - If a single value: Assigns this value to all bands of matching pixels - If an array: Assigns each value to the corresponding band of matching pixels
(must have the same length as the number of bands)
Returns
- selfGeoimage
The modified image, allowing method chaining
Examples
>>> # Replace all nodata (0) values with NaN >>> image.replace_values(0, np.nan) >>> >>> # Replace a specific RGB color [255, 0, 0] with [0, 0, 0] (black) >>> image.replace_values([255, 0, 0], [0, 0, 0])
Notes
This method is useful for replacing nodata values, specific classes in a classification, or adjusting specific spectral signatures in an image.
- percentage_pixels(value=None)[source]
Calculate the percentage of pixels with a specified value across all bands.
This method calculates what percentage of the total pixels have the specified value in all bands. It’s particularly useful for calculating coverage of nodata values, specific land cover classes, or other categorical values.
Parameters
- valueint, float, list, or array-like, optional
The value to check for in each band of a pixel: - If a single number: Checks for pixels where all bands equal this value - If a vector: Checks for pixels where each band matches the corresponding
value in the vector (must have same length as number of bands)
If None: Uses the image’s nodata value (default)
Returns
- float
The percentage of pixels (from 0 to 100) where all bands have the specified value
Examples
>>> # Calculate percentage of nodata pixels >>> pct_nodata = image.percentage_pixels() # Uses image's nodata value >>> print(f"Image contains {pct_nodata:.2f}% nodata pixels") >>> >>> # Calculate percentage of pixels with a specific class value >>> pct_water = image.percentage_pixels(1) # Assuming 1 = water class >>> print(f"Water covers {pct_water:.2f}% of the image") >>> >>> # Calculate percentage of pixels with a specific spectral signature >>> pct_rgb_black = image.percentage_pixels([0, 0, 0]) # RGB black pixels >>> print(f"Black pixels (RGB=0,0,0) cover {pct_rgb_black:.2f}% of the image")
Notes
This method handles both single values and vectors for the value parameter. The calculation correctly handles NaN values by considering NaN equal to NaN.
- hist(**args)[source]
Display histograms of the image data.
This method provides a flexible way to visualize the distribution of pixel values in one or more bands of the image. It supports various customization options for the histogram display.
Parameters
- bandsstr, int, list, optional
The bands to visualize. If not specified, all bands are included. This can be band names (e.g., [“NIR”, “R”, “G”]) or indices (e.g., [4, 3, 2]).
- superposebool, optional
If True, all histograms are plotted on the same figure. If False (default), each band gets its own separate histogram figure.
- binsint, optional
The number of bins for computing the histogram. Default is 100.
- xminfloat, optional
The minimum value to plot on the x-axis. Values lower than this won’t be displayed.
- xmaxfloat, optional
The maximum value to plot on the x-axis. Values higher than this won’t be displayed.
- titlestr, optional
The title for the histogram figure.
- histtypestr, optional
The type of histogram to draw. Default is ‘stepfilled’. Other options include ‘bar’, ‘step’, ‘barstacked’, etc.
- alphafloat, optional
The transparency of the histogram bars (0.0 to 1.0). Default is 0.6.
- fig_sizetuple, optional
The size of the figure in inches as (width, height). Default is DEF_FIG_SIZE.
- labelstr or list of str, optional
The labels for the histogram. If not provided, default labels will be created.
- **argsdict, optional
Additional keyword arguments passed to matplotlib’s hist function.
Returns
- None
This method displays the histogram(s) but doesn’t return any values.
Examples
>>> # Display histograms for all bands >>> image.hist(bins=100) >>> >>> # Display histogram for a single band with customization >>> image.hist(bands="NIR", bins=150, histtype='stepfilled', >>> title="NIR Band Distribution", xmin=0, xmax=10000) >>> >>> # Superpose histograms from multiple bands >>> image.hist(bands=["NIR", "R", "G"], bins=100, superpose=True, >>> alpha=0.7, fig_size=(10, 6))
Notes
This method is based on rasterio’s show_hist function and supports most of matplotlib’s histogram customization options. It’s useful for understanding the distribution of values in your image and identifying potential issues like saturation, quantization, or outliers.
- colorcomp(bands=None, dest_name='', percentile=2, fig_size=(5, 5), title='', extent='latlon')[source]
Create and display a color composite image from selected bands.
This method creates an RGB color composite by assigning three bands to the red, green, and blue channels. It’s useful for creating false color compositions, natural color images, or any three-band visualization.
Parameters
- bandslist of str, optional
List of three band identifiers to use for the RGB composite (in order: R, G, B). Can be band names (e.g., [“NIR”, “R”, “G”]) or indices (e.g., [“4”, “3”, “2”]). If None, uses the first three bands in the image. Default is None.
- dest_namestr, optional
Path to save the color composite image. If empty, the image is not saved. Default is ‘’.
- percentileint, optional
Percentile value for contrast stretching (e.g., 2 for a 2-98% stretch). This enhances the visual contrast of the image. Default is 2.
- fig_sizetuple, optional
Size of the figure in inches as (width, height). Default is DEF_FIG_SIZE.
- titlestr, optional
Title for the visualization. Default is ‘’.
- extent{‘latlon’, ‘pixel’, None}, optional
Type of extent to use for the plot: - ‘latlon’: Use latitude/longitude coordinates (default) - ‘pixel’: Use pixel coordinates - None: Don’t show coordinate axes
Returns
- None
This method displays and/or saves the color composite but doesn’t return any values.
Raises
- ValueError
If the image has only 2 bands, which is not enough for an RGB composite. If an invalid extent value is provided.
Examples
>>> # Create a natural color composite (for Landsat/Sentinel-2 style ordering) >>> image.colorcomp(bands=["R", "G", "B"]) >>> >>> # Create a color-infrared composite (vegetation appears red) >>> image.colorcomp(bands=["NIR", "R", "G"], title="Color-Infrared Composite") >>> >>> # Create and save a false color composite >>> image.colorcomp(bands=["SWIR1", "NIR", "G"], dest_name="false_color.tif") >>> >>> # Change the contrast stretch >>> image.colorcomp(bands=["R", "G", "B"], percentile=5) # More aggressive stretch
Notes
Common band combinations for satellite imagery include: - Natural color: R, G, B (shows the scene as human eyes would see it) - Color-infrared: NIR, R, G (vegetation appears red, useful for vegetation analysis) - Agriculture: SWIR, NIR, B (highlights crop health and soil moisture) - Urban: SWIR, NIR, R (emphasizes urban areas and bare soil)
- convert_3bands(bands=None, dest_name=None, percentile=2, reformat_names=False)[source]
Convert an image to a 3-band 8-bit RGB composite.
This method creates a new Geoimage with exactly 3 bands in 8-bit format (0-255), suitable for standard RGB visualization or export to conventional image formats.
Parameters
- bandslist of str, optional
List of three band identifiers to use for the RGB composite (in order: R, G, B). Can be band names (e.g., [“NIR”, “R”, “G”]) or indices (e.g., [“4”, “3”, “2”]). If None, uses the first three bands in the image. Default is None.
- dest_namestr, optional
Path to save the 3-band image. If None, the image is not saved. Default is None.
- percentileint, optional
Percentile value for contrast stretching (e.g., 2 for a 2-98% stretch). This enhances the visual contrast of the image. Default is 2.
- reformat_namesbool, optional
Whether to reset band names to a simple numeric format (“1”, “2”, “3”). If False, keeps the original names of the selected bands. Default is False.
Returns
- Geoimage
A new Geoimage with 3 bands (R, G, B) in 8-bit format.
Examples
>>> # Create a natural color composite >>> rgb_image = image.convert_3bands(bands=["R", "G", "B"]) >>> rgb_image.info() # Should show 3 bands, uint8 data type >>> >>> # Create a false color composite with custom names >>> false_color = image.convert_3bands( >>> bands=["SWIR", "NIR", "R"], dest_name="false_color.tif", >>> reformat_names=True)
Notes
This method is useful for: - Creating standardized RGB exports - Preparing data for conventional image viewers that expect 3-band 8-bit data - Reducing file size by converting to 8-bit - Creating visually enhanced compositions with contrast stretching
- plot_spectra(bands=None, fig_size=(15, 5), percentile=2, title='', title_im='Original image (click outside to stop)', title_spectra='Spectra', xlabel='Bands', ylabel='Value')[source]
Interactive tool to explore and plot spectral values from user-selected pixels.
This method displays the image and allows the user to click on pixels to see their spectral values across all bands plotted as a line graph. Multiple pixels can be selected to compare different spectral signatures.
Parameters
- bandslist of str, optional
List of three band identifiers to use for the background image display. If None, uses the first three bands in the image. Default is None.
- fig_sizetuple, optional
Size of the figure in inches as (width, height). Default is (15, 5).
- percentileint, optional
Percentile value for contrast stretching of the background image. Default is 2.
- titlestr, optional
Main title for the figure. Default is ‘’.
- title_imstr, optional
Title for the image panel. Default is “Original image (click outside to stop)”.
- title_spectrastr, optional
Title for the spectral plot panel. Default is “Spectra”.
- xlabelstr, optional
X-axis label for the spectral plot. Default is “Bands”.
- ylabelstr, optional
Y-axis label for the spectral plot. Default is “Value”.
Returns
- tuple
A tuple containing: - series : list of lists - Spectral values for each selected pixel - pixel_i : list of int - Row coordinates of selected pixels - pixel_j : list of int - Column coordinates of selected pixels
Examples
>>> # Explore spectral signatures in the image >>> spectra, rows, cols = image.plot_spectra() >>> print(f"Selected {len(spectra)} pixels") >>> >>> # Customize the display >>> spectra, rows, cols = image.plot_spectra( >>> bands=["NIR", "R", "G"], >>> title_im="Click on different vegetation types", >>> title_spectra="Vegetation Spectral Signatures")
Notes
To end pixel selection, click outside the image area or on the “Finish” button. This tool is particularly useful for: - Exploring spectral differences between land cover types - Identifying spectral anomalies - Training classification algorithms - Building spectral libraries
- visu(bands=None, title='', percentile=2, fig_size=(5, 5), cmap=None, colorbar=False, extent='latlon')[source]
Visualize one or more bands of the image.
This method provides a flexible way to display individual bands or multiple bands as separate figures. Unlike colorcomp, which creates RGB composites, this method displays each band in grayscale or with a specified colormap.
Parameters
- bandsstr, list of str, or None, optional
The bands to visualize: - If None: Displays all bands separately - If a string: Displays a single specified band - If a list: Displays each specified band separately Default is None.
- titlestr, optional
Base title for the visualization. Band names will be appended. Default is ‘’.
- percentileint, optional
Percentile value for contrast stretching (e.g., 2 for a 2-98% stretch). Default is 2.
- fig_sizetuple, optional
Size of the figure in inches as (width, height). Default is DEF_FIG_SIZE.
- cmapstr, optional
Matplotlib colormap name to use for display. Examples: ‘viridis’, ‘plasma’, ‘gray’, ‘RdYlGn’ Default is None (uses matplotlib default).
- colorbarbool, optional
Whether to display a colorbar next to each image. Default is False.
- extent{‘latlon’, ‘pixel’, None}, optional
Type of extent to use for the plot: - ‘latlon’: Use latitude/longitude coordinates (default) - ‘pixel’: Use pixel coordinates - None: Don’t show coordinate axes
Examples
>>> # Visualize all bands >>> image.visu() >>> >>> # Visualize a single band with a colormap and colorbar >>> image.visu("NIR", cmap='plasma', colorbar=True, title="Near Infrared Band") >>> >>> # Visualize selected bands >>> image.visu(["Red", "NIR", "NDVI"], fig_size=(10, 8))
Notes
This method is useful for: - Examining individual spectral bands in detail - Comparing several derived indices side by side - Applying different colormaps to highlight specific features - Visualizing single-band thematic data (e.g., elevation, classification results)
- numpy_channel_first(bands=None)[source]
Extract image data as a NumPy array in channel-first format.
This method returns a NumPy array representation of the image data with bands as the first dimension (bands, rows, cols), which is the format used by rasterio.
Parameters
- bandsstr, list of str, or None, optional
The bands to include in the output: - If None: Returns all bands - If a string: Returns a single specified band - If a list: Returns the specified bands in the given order Default is None.
Returns
- numpy.ndarray
Image data as a NumPy array with shape (bands, rows, cols)
Examples
>>> # Get the complete image as a NumPy array >>> array = image.numpy_channel_first() >>> print(f"Array shape: {array.shape}") >>> print(f"Data type: {array.dtype}") >>> >>> # Extract specific bands >>> rgb_array = image.numpy_channel_first(bands=["R", "G", "B"]) >>> print(f"RGB array shape: {rgb_array.shape}")
Notes
This format (bands, rows, cols) is commonly used with rasterio and some other geospatial libraries. For libraries that expect channel-last format (like most image processing libraries), use numpy_channel_last() instead.
- numpy_channel_last(bands=None)[source]
Extract image data as a NumPy array in channel-last format.
This method returns a NumPy array representation of the image data with bands as the last dimension (rows, cols, bands), which is the format used by most image processing libraries and frameworks.
Parameters
- bandsstr, list of str, or None, optional
The bands to include in the output: - If None: Returns all bands - If a string: Returns a single specified band - If a list: Returns the specified bands in the given order Default is None.
Returns
- numpy.ndarray
Image data as a NumPy array with shape (rows, cols, bands)
Examples
>>> # Get the complete image as a NumPy array >>> array = image.numpy_channel_last() >>> print(f"Array shape: {array.shape}") >>> >>> # Extract RGB bands for use with image processing libraries >>> rgb = image.numpy_channel_last(bands=["R", "G", "B"]) >>> import cv2 >>> blurred = cv2.GaussianBlur(rgb, (5, 5), 0)
Notes
This format (rows, cols, bands) is commonly used with image processing libraries like OpenCV, scikit-image, PIL, and deep learning frameworks. For libraries that expect channel-first format (like rasterio), use numpy_channel_first() instead.
- numpy_table(bands=None)[source]
Extract image data as a 2D table of shape (pixels, bands).
This method reshapes the image into a 2D table where each row represents a pixel and each column represents a band. This format is useful for machine learning, statistical analysis, or any operation that treats pixels as independent samples.
Parameters
- bandsstr, list of str, or None, optional
The bands to include in the output: - If None: Returns all bands - If a string: Returns a single specified band - If a list: Returns the specified bands in the given order Default is None.
Returns
- numpy.ndarray
Image data as a 2D table with shape (rows*cols, bands)
Examples
>>> # Convert the entire image to a table >>> table = image.numpy_table() >>> print(f"Table shape: {table.shape}") >>> >>> # Process specific bands as a table >>> nir_red = image.numpy_table(bands=["NIR", "R"]) >>> print(f"Shape: {nir_red.shape}") >>> ndvi = (nir_red[:, 0] - nir_red[:, 1]) / (nir_red[:, 0] + nir_red[:, 1]) >>> print(f"Mean NDVI: {ndvi.mean()}")
Notes
This format is particularly useful for: - Machine learning where each pixel is a sample and each band is a feature - Clustering algorithms like K-means - Statistical analysis across bands - Vectorized operations on pixels
- image_from_table(table, names=None, dest_name=None)[source]
Create a new Geoimage from a 2D table of shape (pixels, bands).
This method converts a 2D table where each row represents a pixel and each column represents a band into a new Geoimage object. It essentially performs the inverse operation of numpy_table().
Parameters
- tablenumpy.ndarray
The 2D table to convert, with shape (rows*cols, bands) or (rows*cols,) for a single band.
- namesdict, optional
Dictionary mapping band names to band indices. If None, bands will be named sequentially (“1”, “2”, “3”, …). Default is None.
- dest_namestr, optional
Path to save the new image. If None, the image is not saved. Default is None.
Returns
- Geoimage
A new Geoimage created from the reshaped table
Raises
- ValueError
If the number of rows in the table doesn’t match the dimensions of the original image
Examples
>>> # Create a modified image from a processed table >>> table = image.numpy_table() >>> normalized = (table - table.mean()) / table.std() # Standardize >>> normalized_image = image.image_from_table(normalized) >>> normalized_image.visu() >>> >>> # Save the result >>> table = image.numpy_table(bands=["NIR", "R"]) >>> ndvi = np.zeros((table.shape[0], 1)) # Create single-band output >>> ndvi[:, 0] = (table[:, 0] - table[:, 1]) / (table[:, 0] + table[:, 1]) >>> ndvi_image = image.image_from_table(ndvi, names={"NDVI": 1}, dest_name="ndvi.tif")
Notes
The dimensions of the original image (rows, cols) are preserved, so the table must have exactly rows*cols rows. The number of bands can be different from the original image.
- upload_table(table, names=None, dest_name=None)[source]
Update the image data with a 2D table of shape (pixels, bands).
This method replaces the current image data with the content of a 2D table where each row represents a pixel and each column represents a band. The table is reshaped to match the image dimensions.
Parameters
- tablenumpy.ndarray
The 2D table to upload, with shape (rows*cols, bands) or (rows*cols,) for a single band.
- namesdict, optional
Dictionary mapping band names to band indices. If None, bands will be named sequentially (“1”, “2”, “3”, …). Default is None.
- dest_namestr, optional
Path to save the updated image. If None, the image is not saved. Default is None.
Returns
- selfGeoimage
The updated image, allowing method chaining
Raises
- ValueError
If the number of rows in the table doesn’t match the dimensions of the original image
Examples
>>> # Update an image with processed data >>> table = image.numpy_table() >>> table = np.log(table + 1) # Log transform >>> image.upload_table(table) >>> image.visu() >>> >>> # Upload a single-band result and save >>> ndvi_table = (nir - red) / (nir + red) # Assuming nir and red are numpy arrays >>> image.upload_table(ndvi_table, names={"NDVI": 1}, dest_name="ndvi.tif")
Notes
Unlike image_from_table() which creates a new image, this method modifies the current image in place. The dimensions of the image (rows, cols) are preserved, but the number of bands can change if the table has a different number of columns.
- upload_image(image, names=None, dest_name=None, channel_first=True, inplace=False)[source]
Update the image data with a new image array.
This method replaces the current image data with a new image array. The new image must have compatible dimensions with the current image.
- imagenumpy.ndarray
The new image data to upload, with shape: - (bands, rows, cols) if channel_first=True - (rows, cols, bands) if channel_first=False - (rows, cols) for a single band
- namesdict, optional
Dictionary mapping band names to band indices. If None, bands will be named
- sequentially (“1”, “2”, “3”, …).
Default is None.
- dest_namestr, optional
Path to save the updated image. If None, the image is not saved. Default is None.
- channel_firstbool, optional
Whether the input image has channels in the first dimension (True) or the last dimension (False). Default is True.
- inplacebool, default False
If False, return a copy. Otherwise, upload image in place and return None.
- Geoimage
The updated image or None if inplace=True
- ValueError
If the spatial dimensions of the new image don’t match the original image
>>> # Create a new filtered image without modifying the original >>> array = image.numpy_channel_first() >>> filtered = apply_some_filter(array) # Apply some processing >>> filtered_image = image.upload_image(filtered) >>> filtered_image.visu() >>> image.visu() # Original remains unchanged >>> >>> # Create a single-band image from NDVI calculation >>> nir = image.numpy_channel_first(bands=["NIR"]) >>> red = image.numpy_channel_first(bands=["Red"]) >>> ndvi = (nir - red) / (nir + red) >>> ndvi_image = image.upload_image(ndvi, names={"NDVI": 1}, >>> dest_name="ndvi.tif") >>> # Update an image with processed data >>> array = image.numpy_channel_first() >>> filtered = some_filter_function(array) # Apply some processing >>> image.upload_image(filtered, inplace=True) >>> image.visu() >>> >>> # Upload an image in channel-last format >>> import cv2 >>> bgr = cv2.imread('rgb.jpg') # OpenCV uses BGR order >>> rgb = bgr[:, :, ::-1] # Convert BGR to RGB >>> image.upload_image(rgb, channel_first=False, dest_name="from_jpeg.tif", inplace=True))
The spatial dimensions (rows, cols) must match the original image, but the number of bands can change.
- astype(dtype)[source]
Convert the image data to a specified data type.
This method changes the data type of the image pixels (e.g., from float32 to uint8). This can be useful for reducing memory usage or preparing data for specific operations.
Parameters
- dtypestr or numpy.dtype
The target data type (e.g., ‘uint8’, ‘float32’, ‘int16’)
Returns
- selfGeoimage
The modified image with the new data type, allowing method chaining
Examples
>>> # Convert to 8-bit unsigned integer >>> image.astype('uint8') >>> image.info() # Should show dtype: uint8 >>> >>> # Convert to 32-bit floating point >>> image.astype('float32') >>> image.visu()
Notes
Common data types for geospatial data: - uint8: 8-bit unsigned integer (0-255), useful for RGB display - int16: 16-bit signed integer (-32768 to 32767), common for satellite data - uint16: 16-bit unsigned integer (0-65535), common for satellite data - float32: 32-bit floating point, useful for continuous values and calculations - float64: 64-bit floating point, highest precision but more memory usage
Warning: Converting to a smaller data type may result in loss of information or precision. For example, converting float32 to uint8.
- reproject(projection='EPSG:3857', inplace=False, dest_name=None)[source]
Reproject the image to a different coordinate reference system (CRS).
This method transforms the image to a new projection system, which changes how the image’s coordinates are interpreted. This can be useful for aligning data from different sources or preparing data for specific analyses.
Parameters
- projectionstr, optional
The target projection as an EPSG code or PROJ string. Examples:
“EPSG:4326”: WGS84 geographic (lat/lon)
“EPSG:3857”: Web Mercator (used by web maps)
“EPSG:32619”: UTM Zone 19N
Default is “EPSG:3857” (Web Mercator).
- inplacebool, default False
If False, return a copy. Otherwise, do reprojection in place and return None.
- dest_namestr, optional
Path to save the reprojected image. If None, the image is not saved. Default is None.
Returns
- Geoimage
The reprojected image or None if inplace=True
Examples
>>> # Reproject to WGS84 (latitude/longitude) >>> image_reprojected = image.reproject("EPSG:4326") >>> image_reprojected.info() # Shows new projection >>> >>> # Reproject to UTM Zone 17N and save >>> image_reprojected = image.reproject("EPSG:32617", dest_name="utm.tif") >>> >>> >>> # Reproject to WGS84 (latitude/longitude) and modify inplace the image >>> image.reproject("EPSG:4326", inplace=True) >>> image.info() # Shows new projection >>> >>> # Reproject to UTM Zone 17N and save >>> image.reproject("EPSG:32617", dest_name="utm.tif", inplace=True)
Notes
Reprojection can change the pixel values due to resampling
The dimensions of the image will typically change during reprojection
Common projection systems include:
EPSG:4326 - WGS84 geographic coordinates (latitude/longitude)
EPSG:3857 - Web Mercator (used by Google Maps, OpenStreetMap)
EPSG:326xx - UTM Zone xx North (projected coordinate system)
EPSG:327xx - UTM Zone xx South (projected coordinate system)
- latlon2pixel(coord_lat, coord_lon)[source]
Convert geographic coordinates (latitude, longitude) to pixel coordinates.
This method transforms a point defined by its latitude and longitude to the corresponding pixel location (row, col) in the image.
Parameters
- coord_latfloat
Latitude of the point
- coord_lonfloat
Longitude of the point
Returns
- tuple of int
The pixel coordinates as (row, col) or (i, j)
Examples
>>> # Convert a geographic location to pixel coordinates >>> latitude, longitude = 42.36, -71.06 # Boston, MA >>> row, col = image.latlon2pixel(latitude, longitude) >>> print(f"This location is at pixel ({row}, {col})") >>> >>> # Check if a specific location is within the image extent >>> row, col = image.latlon2pixel(latitude, longitude) >>> in_bounds = (0 <= row < image.shape[0]) and (0 <= col < image.shape[1]) >>> print(f"Location is within image: {in_bounds}")
Notes
The image must be georeferenced (have valid CRS and transform)
If the point is outside the image extent, the function will still return pixel coordinates, but they may be outside the valid image dimensions
Row (i) corresponds to the vertical position (along latitude)
Column (j) corresponds to the horizontal position (along longitude)
- pixel2latlon(i, j)[source]
Convert pixel coordinates to geographic coordinates (latitude, longitude).
This method transforms a pixel location (row, col) in the image to the corresponding point defined by its latitude and longitude.
Parameters
- iint
Row index (vertical position) in the image
- jint
Column index (horizontal position) in the image
Returns
- tuple of float
The geographic coordinates as (latitude, longitude)
Examples
>>> # Convert pixel coordinates to geographic location >>> row, col = 500, 700 >>> latitude, longitude = image.pixel2latlon(row, col) >>> print(f"Pixel ({row}, {col}) is at lat/lon: ({latitude}, {longitude})") >>> >>> # Find coordinates of image corners >>> nw_lat, nw_lon = image.pixel2latlon(0, 0) # Northwest corner >>> se_lat, se_lon = image.pixel2latlon(image.shape[0]-1, image.shape[1]-1) # Southeast >>> print(f"Image covers from ({nw_lat}, {nw_lon}) to ({se_lat}, {se_lon})")
Notes
The image must be georeferenced (have valid CRS and transform)
Pixel coordinates typically start at (0, 0) in the upper-left corner of the image
For most projections, latitude increases going north and longitude increases going east
- save(dest_name)[source]
Save the image to a GeoTIFF or JPEG2000 file.
This method writes the image data and all its metadata (projection, transform, etc.) to a georeferenced file that can be read by most geospatial software.
Parameters
- dest_namestr
Path to save the image. File format is determined by the extension: - .tif or .tiff: GeoTIFF format - .jp2: JPEG2000 format
Returns
None
Examples
>>> # Save as GeoTIFF >>> image.save("output.tif") >>> >>> # Save as JPEG2000 >>> image.save("output.jp2")
Notes
GeoTIFF (.tif) is the most widely supported format
JPEG2000 (.jp2) offers compression and is good for large images
The saved file will include all metadata (projection, transform, etc.)
To save a subset of bands, first use select_bands() to create a new image with only the desired bands, then save that image
- extract_from_shapefile(name_shp, value, attribute='code', nodata_value=0, inplace=False, keep_size=False)[source]
Extract data from areas matching a shapefile attribute value.
This method modifies the image by keeping only data where the shapefile has polygons with the specified attribute value. All other areas are set to nodata_value.
Parameters
- name_shpstr
Path to the shapefile (.shp) to use for extraction
- valueint or float
The attribute value to extract (e.g., extract only areas with code=3)
- attributestr, optional
The name of the attribute field in the shapefile to use. Default is ‘code’.
- nodata_valueint or float, optional
Value to assign to areas outside the extracted regions. Default is 0.
- inplacebool, default False
If False, return a copy. Otherwise, do the extraction in place
- keep_sizebool, optional
If True, output has the same dimensions as input. If False, output is cropped to the shapefile extent. Default is False.
Returns
- Geoimage
The image containing only the extracted regions or None if inplace = True
Examples
>>> # Extract only forest areas (assuming forest has code 3 in the shapefile) >>> image_forest = image.extract_from_shapefile("landcover.shp", 3) >>> image.visu() >>> >>> # Keep only urban areas and preserve the original image size >>> image.extract_from_shapefile( >>> "landcover.shp", 1, attribute="class", >>> nodata_value=-9999, keep_size=True, inplace=True) >>> image.save("urban_areas.tif")
Notes
The shapefile must be in the same CRS as the image, or reprojection may be necessary
Use shpfiles.get_shapefile_attributes(name_shp) to view available attributes
- extract_from_shapeimage(shp, value, attribute='code', inplace=False, nodata_value=0, keep_size=False)[source]
Extract data from areas matching a shape image value.
This method modifies the image by keeping only data where another Geoimage (typically created from a shapefile) has the specified value. All other areas are set to nodata_value.
Parameters
- shpGeoimage
A Geoimage object, typically created from a shapefile, to use for extraction
- valueint or float
The pixel value to extract from (e.g., extract only where shp has value 3)
- attributestr, optional
Not used for this method, kept for API consistency with extract_from_shapefile. Default is ‘code’.
- nodata_valueint or float, optional
Value to assign to areas outside the extracted regions. Default is 0.
- inplacebool, default False
If False, return a copy. Otherwise, do the extraction in place
- keep_sizebool, optional
If True, output has the same dimensions as input. If False, output is cropped to the shape image extent. Default is False.
Returns
- Geoimage
A new Geoimage containing only the extracted regions or None if inplace=True
Examples
>>> # First create a shape image from a shapefile >>> landcover = shpfiles.shp2geoim("landcover.shp", attribute="class") >>> >>> # Keep only forest areas (assuming forest has value 3) >>> image_forest = image.extract_from_shapeimage(landcover, 3) >>> image_forest.visu()
Notes
The shape image must have the same CRS as the target image,or it will be resampled to match
- kmeans(n_clusters=4, bands=None, random_state=None, dest_name=None, standardization=True, nb_points=1000)[source]
Perform K-means clustering on the image data.
This method performs an unsupervised classification using K-means clustering, which groups pixels with similar spectral characteristics into a specified number of clusters.
Parameters
- n_clustersint, optional
Number of clusters (classes) to create. Default is 4.
- bandslist of str or None, optional
List of bands to use for clustering. If None, all bands are used. Default is None.
- random_stateint or None, optional
Random seed for reproducible results. If None, results may vary between runs. Default is RANDOM_STATE (defined globally).
- dest_namestr, optional
Path to save the clustered image. If None, the image is not saved. Default is None.
- standardizationbool, optional
Whether to standardize bands before clustering (recommended). Default is True.
- nb_pointsint or None, optional
Number of random points to sample for training the model. If None, all valid pixels are used (may be slow for large images). Default is 1000.
Returns
- Geoimage
A new Geoimage containing the cluster IDs (0 to n_clusters-1)
- tuple
A tuple containing (kmeans_model, scaler) for reusing the model on other images
Examples
>>> # Basic K-means clustering with 5 clusters >>> classified, model = image.kmeans(n_clusters=5) >>> classified.visu(colorbar=True, cmap='viridis') >>> >>> # Cluster using only specific bands and save result >>> classified, model = image.kmeans( >>> n_clusters=3, bands=["NIR", "Red", "Green"], >>> dest_name="clusters.tif") >>> >>> # Apply same model to another image >>> other_classified = other_image.apply_ML_model(model)
Notes
Standardization is recommended, especially when bands have different ranges
The returned model can be used with apply_ML_model() on other images
- apply_ML_model(model, bands=None)[source]
Apply a pre-trained machine learning model to the image.
This method applies a machine learning model (such as one created by kmeans()) to the image data, creating a new classified or transformed image.
Parameters
- modeltuple
A tuple containing (ml_model, scaler) where: - ml_model: A trained scikit-learn model with a predict() method - scaler: The scaler used for standardization (or None if not used)
- bandslist of str or None, optional
List of bands to use as input for the model. If None, all bands are used. Default is None.
Returns
- Geoimage
A new Geoimage containing the model output
Examples
>>> # Train a model on one image and apply to another >>> classified, model = reference_image.kmeans(n_clusters=5) >>> new_classified = target_image.apply_ML_model(model) >>> new_classified.visu(colorbar=True, cmap='viridis') >>> >>> # Train on specific bands and apply to the same bands >>> _, model = image.kmeans(bands=["NIR", "Red"], n_clusters=3) >>> result = image.apply_ML_model(model, bands=["NIR", "Red"]) >>> result.save("classified.tif")
Notes
The model must have been trained on data with the same structure as what it’s being applied to (e.g., same number of bands)
If a scaler was used during training, it will be applied before prediction
This method is useful for:
Applying a classification model to new images
Ensuring consistent classification across multiple scenes
Time-series analysis with consistent classification
- adapt(imt, tab_source=None, nb=1000, mapping='gaussian', reg_e=0.1, mu=1.0, eta=0.01, bias=False, max_iter=20, verbose=True, sigma=1, inplace=False)[source]
Adjust spectral characteristics to match a target image.
This method adapts the spectral characteristics of the current image to match those of a target image using optimal transport methods. This is useful for harmonizing images from different sensors or acquisitions.
Parameters
- imtGeoimage or numpy.ndarray
Target image serving as a reference for spectral adjustment, or a NumPy array of shape (N, bands) containing N spectral samples.
- tab_sourcenumpy.ndarray, optional
Required if imt is a NumPy array. Must be an array of shape (M, bands) containing spectral samples from the source image.
- nbint, optional
Number of random samples used to train the transport model. Default is 1000.
- mappingstr, optional
Optimal transport method to use: - ‘emd’: Earth Mover’s Distance (simplest) - ‘sinkhorn’: Sinkhorn transport with regularization (balanced) - ‘mappingtransport’: Mapping-based transport (flexible) - ‘gaussian’: Transport with Gaussian assumptions (default, robust) Default is ‘gaussian’.
- reg_efloat, optional
Regularization parameter for Sinkhorn transport. Default is 1e-1.
- mufloat, optional
Regularization parameter for mapping-based methods. Default is 1e0.
- etafloat, optional
Learning rate for mapping-based transport methods. Default is 1e-2.
- biasbool, optional
Whether to add a bias term to the transport model. Default is False.
- max_iterint, optional
Maximum number of iterations for iterative transport methods. Default is 20.
- verbosebool, optional
Whether to display progress information. Default is True.
- sigmafloat, optional
Standard deviation used for Gaussian transport methods. Default is 1.
- inplacebool, default False
If False, return a copy. Otherwise, do the adaptation in place and return None.
Returns
The image with adapted spectral characteristics or None if inplace=True
Examples
>>> # Basic spectral adaptation >>> image_adapt = image1.adapt(image2) >>> image_adapt.visu() # Now spectrally similar to image2 >>> >>> # Use specific transport method >>> image_adapt = image1.adapt(image2, mapping='sinkhorn', reg_e=0.01) >>> image_adapt.save("adapted_image.tif") >>> >>> # Adaptation using sample arrays >>> adapted_image = image1.adapt(tab_target, tab_source = tab_source, mapping='sinkhorn', reg_e=0.01) >>> >>> # Basic spectral adaptation and modify inplace the image >>> image1.adapt(image2, inplace=True) >>> image1.visu() # Now spectrally similar to image2
Notes
- This method is useful for:
Harmonizing multi-sensor data
Matching images acquired under different conditions
Preparing time-series data for consistent analysis
- Different mapping methods have different characteristics:
‘emd’: Most accurate but slowest
‘sinkhorn’: Good balance between accuracy and speed
‘mappingtransport’: Flexible and can handle complex transformations
‘gaussian’: Fastest and works well for most cases
- fuse_dempster_shafer_2(*images)[source]
Fuse the 3 band image (associated with mass functions) from multiple sources using Dempster-Shafer theory with two hypotheses: A and B.
Parameters
- *imagesGeoimage
Each input is a 3-band Geoimage.
Band 1: mass function m(A)
Band 2: mass function m(B)
Band 3: mass function m(A ∪ B)
Returns
- Geoimage
A new Geoimage with 3 bands containing the fused mass functions: m(A), m(B), and m(A ∪ B).
- Geoimage
A new Geoimage with 1 band containing the conflict values.
Examples
>>> fused, conflict = im1.fuse_dempster_shafer_2(im2) >>> fused, conflict = im1.fuse_dempster_shafer_2(im1, im2, im3, im4)
- standardize(scaler=None, dest_name=None, type='standard', inplace=False, dtype='float64')[source]
Standardize band values.
This method performs statistical standardization of image bands, modifying the current image so values have specific statistical properties, such as zero mean and unit variance (for ‘standard’ type) or values in the 0-1 range (for ‘minmax’ type).
Parameters
- scalerobject or None, optional
Scikit-learn scaler object to use. If None, a new scaler is created. Default is None.
- dest_namestr, optional
Path to save the standardized image. If None, image is not saved. Default is None.
- type{‘standard’, ‘minmax’}, optional
Type of standardization to apply: - ‘standard’: Standardize to zero mean and unit variance (z-scores) - ‘minmax’: Scale values to the range [0, 1] Default is ‘standard’.
- inplacebool, default False
If False, return the standardization in a new image. Otherwise, do standardization in place and return None.
- dtypestr, optional
Data type for the standardized image. Default is ‘float64’.
Returns
- Geoimage
The image with standardized values or None if inplace=True
Examples
>>> # Standard standardization (zero mean, unit variance) >>> im_standardized = image.standardize() >>> print(f"Mean: {im_standardized.mean()}, Std: {im_standardized.std()}") >>> >>> # Min-max scaling to [0, 1] range >>> im_standardized = iimage.standardize(type='minmax') >>> print(f"Min: {im_standardized.min()}, Max: {im_standardized.max()}") >>> >>> # Standardize one image and apply same transformation to another (target) >>> _, scaler = image.standardize() >>> target_std = target.standardize(scaler=scaler) >>> >>> # Standard standardization of the image directly >>> # With zero mean, unit variance >>> image.standardize(inplace=True) >>> print(f"Mean: {image.mean()}, Std: {image.std()}") >>> >>> # With min-max scaling to [0, 1] range >>> image.standardize(type='minmax', inplace=True) >>> print(f"Min: {image.min()}, Max: {image.max()}") >>> >>> # Standardize one image and apply same transformation to another (target) >>> _, scaler = image.standardize() >>> target.standardize(scaler=scaler, inplace=True)
Notes
When using a pre-fit scaler, make sure it was created with data having similar statistical properties.
Standardization is often a prerequisite for machine learning algorithms that are sensitive to data scales.
- inverse_standardize(scaler, dest_name=None, inplace=False, dtype='float64')[source]
Revert standardization.
This method creates an image by applying the inverse of a standardization transformation, converting standardized values back to their original scale.
Parameters
- scalerobject
Scikit-learn scaler object that was used for the original standardization. This must have an inverse_transform() method (like StandardScaler or MinMaxScaler).
- dest_namestr, optional
Path to save the restored image. If None, image is not saved. Default is None.
- inplacebool, default False
If False, return a copy of the inverse standardization. Otherwise, do operation in place and return None.
- dtypestr, optional
Data type for the output image. Default is ‘float64’.
Returns
- Geoimage
The image with values transformed back to the original scale or None if inplace=True
Examples
>>> # Standardize and then restore original values >>> image_copy = image.copy() >>> image_copy_std, scaler = image_copy.standardize() >>> image_copy_back = image_copy_std.inverse_standardize(scaler) >>> image_copy_back.visu() # Should look like the original >>> >>> # With inplace = True >>> image_copy_std, scaler = image_copy.standardize() >>> image_copy_std.inverse_standardize(scaler, inplace=True) >>> image_copy_std.visu() # Should look like the original
Notes
The scaler must be the exact one used for the original standardization to ensure accurate inverse transformation
This is often used as the final step in a processing pipeline to convert results back to physically meaningful units
- resampling(final_resolution, dest_name=None, inplace=False, method='cubic_spline', update_history=True)[source]
Resample the image to a different resolution.
This method changes the spatial resolution of the image by resampling the pixel values. The resampling process creates a new grid of pixels at the target resolution and interpolates values from the original grid.
Parameters
- final_resolutionfloat
The target resolution in the image’s coordinate system units (typically meters or degrees). A smaller value results in a higher-resolution (larger) image.
- dest_namestr, optional
Path to save the resampled image. If None, the image is not saved. Default is None.
- inplacebool, default False
If False, return a copy. Otherwise, do the resampling in place and return None.
- methodstr, optional
Resampling algorithm to use. Options include:
‘cubic_spline’ (default): High-quality interpolation, good for continuous data
‘nearest’: Nearest neighbor interpolation, preserves original values, best for categorical data
‘bilinear’: Linear interpolation between points, faster than cubic
‘cubic’: Standard cubic interpolation
‘lanczos’: High-quality downsampling
‘average’: Takes the average of all contributing pixels, useful for downsampling
- update_historybool, optional
Whether to update the image processing history. Default is True.
Returns
- Geoimage
A copy of the resampled image or None if inplace=True
Examples
>>> # Resample to 30 meter resolution >>> image_resampled = image.resampling(30) >>> print(f"New resolution: {image.resolution}") >>> >>> # Resample using nearest neighbor (best for categorical data) >>> classified_image_resampled = classified_image.resampling(10, method='nearest') >>> >>> # Resample and save the result >>> image_resampled = image.resampling(20, dest_name='resampled_20m.tif') >>> >>> >>> # Resample directly the image to 30 meter resolution >>> image.resampling(30, inplace=True) >>> print(f"New resolution: {image.resolution}") >>> >>> # Resample directly the image using nearest neighbor (best for categorical data) >>> classified_image.resampling(10, method='nearest', inplace=True) >>> >>> # Resample and save the result >>> image.resampling(20, dest_name='resampled_20m.tif', inplace=True)
Notes
When upsampling (to higher resolution), no new information is created;
the function only interpolates between existing pixels - When downsampling (to lower resolution), information is lost - The choice of resampling method is important: - For continuous data (e.g., elevation, reflectance): ‘cubic_spline’, ‘bilinear’, or ‘cubic’ - For categorical data (e.g., land classifications): ‘nearest’ or ‘mode’ - This method changes the dimensions (shape) of the image
- crop(deb_row_lon, end_row_lon, deb_col_lat, end_col_lat, dest_name=None, pixel=True, inplace=False)[source]
Crop the image to a specified extent.
This method extracts a rectangular subset of the image, defined either by pixel coordinates or by geographic coordinates, and updates the current image to contain only the cropped region.
Parameters
- deb_row_lonint or float
Starting position: - If pixel=True: Starting row (y) coordinate - If pixel=False: Starting longitude coordinate
- end_row_lonint or float
Ending position: - If pixel=True: Ending row (y) coordinate - If pixel=False: Ending longitude coordinate
- deb_col_latint or float
Starting position: - If pixel=True: Starting column (x) coordinate - If pixel=False: Starting latitude coordinate
- end_col_latint or float
Ending position: - If pixel=True: Ending column (x) coordinate - If pixel=False: Ending latitude coordinate
- dest_namestr, optional
Path to save the cropped image. If None, the image is not saved. Default is None.
- inplacebool, default False
If False, return a copy. Otherwise, do cropping in place and return None.
- pixelbool, optional
Coordinate system flag: - If True: Coordinates are interpreted as pixel indices (row, col) - If False: Coordinates are interpreted as geographic coordinates (lon, lat) Default is True.
Returns
- Geoimage
A copy of the cropped image or None if inplace=True
Examples
>>> # Crop using pixel coordinates >>> original_shape = image.shape >>> image_crop = image.crop(100, 500, 200, 600) >>> print(f"Original shape: {original_shape}, New shape: {image_crop.shape}") >>> >>> # Crop using geographic coordinates >>> image_crop = image.crop(-122.5, -122.3, 37.8, 37.7, pixel=False) >>> image.visu() >>> >>> # Crop and save the result >>> image_crop = image.crop(100, 500, 200, 600, dest_name='cropped_area.tif') >>> >>> >>> # Crop using pixel coordinates >>> original_shape = image.shape >>> image.crop(100, 500, 200, 600, inplace=True) # inplace = True : modify directly the image >>> print(f"Original shape: {original_shape}, New shape: {image.shape}") >>> >>> # Crop using geographic coordinates >>> image.crop(-122.5, -122.3, 37.8, 37.7, pixel=False, inplace=True) >>> image.visu() >>> >>> # Crop and save the result >>> image.crop(100, 500, 200, 600, dest_name='cropped_area.tif', inplace=True)
Notes
The cropping operation changes the spatial extent of the image but preserves
the resolution and projection. - When using pixel coordinates, the format is (row_start, row_end, col_start, col_end). - When using geographic coordinates, the format is (lon_start, lon_end, lat_start, lat_end).
- select_bands(bands=None, dest_name=None, inplace=False, reformat_names=False)[source]
Select only specified bands in the image
This method modifies the image to contain only the specified bands, discarding all other bands. Band naming can be preserved or updated based on parameters.
Parameters
- bandsstr, list, int, or None, optional
The bands to keep in the image. Format depends on band naming: - If using named bands: band name(s) as string(s) (e.g., ‘NIR’, [‘R’, ‘G’, ‘B’]) - If using indexed bands: band index/indices as int(s) or string(s) (e.g., 3, [‘1’, ‘4’, ‘7’]) If None, no bands are selected (invalid operation).
- dest_namestr, optional
Path to save the modified image. If None, the image is not saved. Default is None.
- inplacebool, default False
If False, return a copy. Otherwise, modify the image by keeping only selected bands
- reformat_namesbool, optional
Band naming behavior: - If True: Rename bands sequentially as “1”, “2”, “3”, etc. - If False: Preserve original band names when possible Default is False.
Returns
- Geoimage
The modified image with only selected bands or None if inplace=True.
Raises
- ValueError
If no bands are specified, or if any specified band doesn’t exist in the image.
Examples
>>> # Extract only 3 specific bands >>> original_bands = list(image.names.keys()) >>> image_selected = image.select_bands(['NIR', 'Red', 'Green']) >>> print(f"Original bands: {original_bands}, New bands: {list(image_selected.names.keys())}") >>> >>> # Keep bands and renumber them sequentially >>> image.select_bands([4, 3, 2], reformat_names=True, inplace=True) >>> print(f"Band names after reordering: {list(image.names.keys())}") >>> >>> # Select a single band >>> nir = image.select_bands('NIR', dest_name='nir_only.tif')
Notes
If band names contain duplicates, they will be automatically reformatted.
The band order in the result matches the order in the ‘bands’ parameter.
- stack(im_to_stack, dtype=None, dest_name=None, inplace=False, reformat_names=False)[source]
Stack bands from another image onto this image.
This method combines the bands from another image with the current image, modifying the current image to include all bands from both sources.
Parameters
- im_to_stackGeoimage
The image whose bands will be stacked onto this image. Should have the same spatial dimensions (rows, cols).
- dtypestr or None, optional
The data type for the stacked image. If None, an appropriate type is determined based on the types of both input images. Common values: ‘float64’, ‘float32’, ‘int32’, ‘uint16’, ‘uint8’. Default is None.
- dest_namestr, optional
Path to save the stacked image. If None, the image is not saved. Default is None.
- inplacebool, default False
If False, return a copy of the stacked image. Otherwise, do stacking in place and return None.
- reformat_namesbool, optional
If True, band names will be reset to a simple numeric format (“1”, “2”, “3”, …). If False, the function will preserve original band names where possible, adding suffixes if needed to resolve conflicts. Default is False.
Returns
- Geoimage
The image with additional bands or None if inplace=True
Raises
- ValueError
If the spatial dimensions of the images don’t match or an unknown dtype is specified.
Examples
>>> # Stack two images with different spectral bands >>> optical = Geoimage("optical.tif", names={'R': 1, 'G': 2, 'B': 3}) >>> thermal = Geoimage("thermal.tif", names={'T': 1}) >>> combined = optical.stack(thermal) >>> print(f"Combined bands: {list(combined.names.keys())}") >>> >>> # Stack and rename bands sequentially >>> combined = optical.stack(thermal, reformat_names=True) >>> print(f"After renaming: {list(combined.names.keys())}") >>> >>> # Stack with explicit data type >>> combined = optical.stack(thermal, dtype='float32', dest_name='combined.tif') >>> >>> # Stack in the image directly >>> optical.stack(thermal, reformat_names=True, inplace=True) >>> print(f"After renaming: {list(combined.names.keys())}")
Notes
The bands from both images are combined along the band dimension (axis 0).
Band naming conflicts are resolved automatically, adding suffixes if needed.
The spatial dimensions (rows, cols) of both images must match.
- remove_bands(bands, inplace=False, reformat_names=False, dest_name=None)[source]
Remove specified bands from the image.
This method modifies the current image by removing the specified bands. The remaining bands can be renamed sequentially or retain their original names.
Parameters
- bandsstr, list, int, or array-like
The bands to remove from the image. Format depends on band naming: - If using named bands: band name(s) as string(s) (e.g., ‘NIR’, [‘R’, ‘G’, ‘B’]) - If using indexed bands: band index/indices as int(s) or string(s) (e.g., 3, [‘1’, ‘4’, ‘7’])
- inplacebool, default False
If False, return a copy. Otherwise, do removing in place and return None.
- reformat_namesbool, optional
Band naming behavior after removal: - If True: Rename remaining bands sequentially as “1”, “2”, “3”, etc. - If False: Preserve original band names with their indices updated Default is False.
- dest_namestr, optional
Path to save the modified image. If None, the image is not saved. Default is None.
Returns
- Geoimage
The image with specified bands removed or None if inplace=True
Raises
- ValueError
If any specified band doesn’t exist in the image, or if removing all bands.
Examples
>>> # Remove a single band >>> original_bands = list(image.names.keys()) >>> image_removed = image.remove_bands('B4') >>> print(f"Original: {original_bands}, After removal: {list(image_removed.names.keys())}") >>> >>> # Remove multiple bands and rename sequentially >>> image_removed = image.remove_bands(['B1', 'B2'], reformat_names=True) >>> print(f"After renaming: {list(image_removed = .names.keys())}") >>> >>> # Remove bands and save the result >>> image_removed = image.remove_bands(['SWIR1', 'SWIR2'], dest_name='visible_only.tif') >>> >>> # Remove a single band >>> original_bands = list(image.names.keys()) >>> image.remove_bands('B4', inplace=True) >>> print(f"Original: {original_bands}, After removal: {list(image.names.keys())}") >>> >>> # Remove multiple bands and rename sequentially >>> image.remove_bands(['B1', 'B2'], reformat_names=True, inplace=True) >>> print(f"After renaming: {list(image.names.keys())}") >>> >>> # Remove bands and save the result >>> image.remove_bands(['SWIR1', 'SWIR2'], dest_name='visible_only.tif', inplace=True)
Notes
If reformat_names=False (default), band names are preserved but indices are updated.
If reformat_names=True, bands are renamed sequentially (1, 2, 3, …).
- reorder_bands(band_order, inplace=False)[source]
Reorder the image bands according to the specified order.
This method changes the order of bands in the image based on the specified band_order parameter. The current image is modified in-place or in a new Geoimage.
Parameters
- band_orderlist or dict
The desired band order specification: - If list: A list of band names in the desired order Example: [‘NIR’, ‘Red’, ‘Green’, ‘Blue’] - If dict: A dictionary mapping band names to their desired positions (1-based) Example: {‘NIR’: 1, ‘Red’: 2, ‘Green’: 3, ‘Blue’: 4}
- inplacebool, default False
If False, return a copy. Otherwise, do reorder bands in place and return None.
Returns
- Geoimage
A copy of the image with reordered bands or None if inplace=True
Raises
- ValueError
If band_order is not a list or dictionary, or if it contains bands that don’t exist in the image.
Examples
>>> # Reorder bands using a list (most common usage) >>> image.info() # Shows original band order >>> image_reorder = image.reorder_bands(['B6', 'B5', 'B4']) >>> image_reorder.info() # Shows new band order >>> >>> # Directly reorder bands using a dictionary with explicit positions >>> image.reorder_bands({'NIR': 1, 'Red': 2, 'Green': 3}, inplace=True) >>> >>> # Reorder bands and save >>> image.reorder_bands(['R', 'G', 'B']).save('rgb_order.tif')
Notes
All bands in the image must be included in band_order if using a list.
If using a dictionary, bands not specified will be excluded.
The band indices in the result will be updated to match the new order.
- switch_band(band_to_switch, band_to_position=None, inplace=False)[source]
Change the position of a specified band in the image.
This method modifies the current image by moving a specified band to a new position, either at the beginning of the band sequence or after a specific band.
Parameters
- band_to_switchstr, int, or list
The band(s) to move to a new position. Can be specified as a band name, band index, or a list containing a single band identifier.
- band_to_positionstr, int, or None, optional
The target position specification: - If None: Move the band to the first position (beginning of the sequence) - If specified: Move the band to the position immediately after this band Default is None.
- inplacebool, default False
If False, return a copy. Otherwise, do switch in place and return None.
Returns
- Geoimage
The image with the reordered bands or None if inplace=True
Raises
- ValueError
If specified bands don’t exist or if input parameters are invalid.
Examples
>>> # Move NIR band to the first position >>> image.info() # Check original band order >>> im_switch = image.switch_band('NIR') >>> im_switch.info() # NIR is now the first band >>> >>> # Move SWIR band to position after Red band >>> im_switch = image.switch_band('SWIR', 'Red') >>> im_switch.info() # SWIR now follows Red >>> >>> # Using band indices instead of names >>> iim_switch = mage.switch_band(5, 2) # Move band 5 to after band 2 >>> >>> # Move NIR band to the first position and change image directly >>> image.info() # Check original band order >>> image.switch_band('NIR', inplace=True) >>> image.info() # NIR is now the first band >>> >>> # Move SWIR band to position after Red band >>> image.switch_band('SWIR', 'Red', inplace=True) >>> image.info() # SWIR now follows Red >>> >>> # Using band indices instead of names >>> image.switch_band(5, 2, inplace=True) # Move band 5 to after band 2
Notes
When multiple bands should be moved as a unit, provide them in a list
as the band_to_switch parameter. - The band indices in the result will be updated to reflect the new order.
- add_band(spectral_band, name_band=None, after_band=None, dtype=None, inplace=False, dest_name=None)[source]
Add a new spectral band to the image.
This method adds a new spectral band to the current image. The new band can be placed at the end of the band stack (default) or after a specified band.
Parameters
- spectral_bandnumpy.ndarray
The spectral band data to add. Can be in any of the following formats: - 2D array with shape (rows, cols) - 3D array with shape (1, rows, cols) - 3D array with shape (rows, cols, 1) The spatial dimensions must match the current image.
- name_bandstr, optional
Name to assign to the new band. If None, a sequential name will be used. Default is None.
- after_bandstr, int, or None, optional
Specify where to insert the new band: - If None: Add to the end of the band stack (default) - If str or int: Insert after the specified band name or index Default is None.
- dtypestr or None, optional
Data type for the new band and resulting image. If None, preserves the highest precision type between the current image and the new band. Common values: ‘float64’, ‘float32’, ‘int32’, ‘uint16’, ‘uint8’. Default is None.
- inplacebool, default False
If False, return a copy of the image with added band Otherwise, adding band in place and return None.
- dest_namestr, optional
Path to save the updated image. If None, the image is not saved. Default is None.
Returns
- Geoimage
The modified image with the new band added or None if inplace=True.
Raises
- ValueError
If dimensions don’t match, if the dtype is unknown, or if the after_band doesn’t exist in the image.
Examples
>>> # Add a NDVI band to the end >>> ndvi = (image.select_band('NIR') - image.select_band('Red') / (image.select_band('NIR') + image.select_band('Red') >>> image_and_ndvi = image.add_band(ndvi, name_band='NDVI') >>> image_and_ndvi.info() # Shows NDVI as the last band >>> >>> # Add a band after a specific position >>> image_and_ndvi = image.add_band(thermal_data, name_band='TIR', after_band='NIR') >>> >>> # Add with explicit data type and save >>> image.add_band(elevation, name_band='DEM', dtype='float32',inplace = True, >>> dest_name='with_dem.tif')
Notes
This method modifies the current image by adding a new band.
The spatial dimensions (rows, cols) of the new band must match the current image.
- class rastereasy.shpfiles[source]
Bases:
object
Utility class for working with shapefiles and converting them to raster formats.
This class contains static methods for operations like: - Getting attribute names from shapefiles - Converting shapefiles to raster data - Converting shapefiles directly to Geoimage objects
Examples
>>> # Get attributes from a shapefile >>> attributes = shpfiles.get_shapefile_attributes("landcover.shp") >>> >>> # Convert a shapefile to a raster file >>> shpfiles.shp2raster("landcover.shp", "landcover.tif", attribute="landtype") >>> >>> # Convert a shapefile to a Geoimage object >>> landcover_img = shpfiles.shp2geoim("landcover.shp", attribute="landtype")
- static get_shapefile_attributes(shapefile_path)[source]
Get the attribute field names from a shapefile.
Parameters
- shapefile_pathstr
Path to the input shapefile.
Returns
- list
List of attribute field names in the shapefile.
Examples
>>> attributes = shpfiles.get_shapefile_attributes("landcover.shp") >>> print(attributes) >>> ['FID', 'landtype', 'area', 'perimeter']
- static shp2geoim(shapefile_path, attribute='code', resolution=10, nodata=0)[source]
Convert a shapefile to a Geoimage object.
Parameters
- shapefile_pathstr
Path to the input shapefile.
- attributestr, optional
Attribute field in the shapefile to assign values to each pixel. Default is ‘code’.
- resolutionfloat, optional
Spatial resolution of the output raster in meters/degrees. Default is 10.
- nodataint or float, optional
Value to assign to areas outside the shapes. Default is 0.
Returns
- Geoimage
A Geoimage object containing the rasterized data.
Notes
The shapefile_path should be the full path to a shapefile (.shp) on the disk.
The attribute field will be assigned to each pixel in the rasterized Geoimage.
To get the attributes of a shapefile, see
shpfiles.get_shapefile_attributes()
The resolution sets the size of each pixel in the output image.
Examples
>>> geo_img = shpfiles.shp2geoim("landcover.shp", attribute='landtype', resolution=5)
- static shp2raster(shapefile_path, dest_name, attribute='code', resolution=10, nodata=0)[source]
Convert a shapefile to a GeoTIFF raster file.
Parameters
- shapefile_pathstr
Path to the input shapefile.
- dest_namestr
Path to save the output raster file.
- attributestr, optional
Attribute field in the shapefile to assign values to each pixel. Default is ‘code’.
- resolutionfloat, optional
Spatial resolution of the output raster in meters/degrees. Default is 10.
- nodataint or float, optional
Value to assign to areas outside the shapes. Default is 0.
Notes
The shapefile_path should be the full path to a shapefile (.shp) on the disk.
To get the attributes of a shapefile, see
shpfiles.get_shapefile_attributes()
The output raster will be written in GeoTIFF format to the path specified by dest_name.
Examples
>>> shpfiles.shp2raster("landcover.shp", "landcover.tif", attribute='landtype', resolution=5)
- class rastereasy.InferenceTools[source]
Bases:
object
Utility class for inference operations on raster images.
This class provides methods for clustering, spectral adaptation fusion, … of georeferenced images.
Examples
>>> # Perform K-means clustering on an image >>> classified_img, model = InferenceTools.kmeans(image, n_clusters=5) >>> >>> # Adapt spectral properties of one image to match another >>> adapted_img = InferenceTools.adapt(source_img, target_img, mapping='sinkhorn')
- static kmeans(im, n_clusters=4, bands=None, random_state=None, dest_name=None, standardization=True)[source]
Perform K-means clustering on a Geoimage.
Parameters
- imGeoimage
Input image to cluster
- n_clustersint, optional
Number of clusters (categories) to create. Default is 4.
- bandslist, optional
List of bands to use for clustering. If None, all bands are used. Default is None.
- random_stateint, optional
Random state for reproducible results. Default is None.
- dest_namestr, optional
Path to save the clustered image. Default is None.
- standardizationbool, optional
Whether to standardize bands before clustering. Default is True.
Returns
- Geoimage
A new Geoimage with clusters as pixel values
- tuple
A tuple containing the KMeans model and the scaler (if standardization was applied)
Examples
>>> classified_img, model = InferenceTools.kmeans(image, n_clusters=3) >>> classified_img.visu() >>> >>> # Clustering with specific bands >>> classified_img, model = InferenceTools.kmeans( >>> image, n_clusters=4, bands=["8", "2", "1"], random_state=42)
- static fuse_dempster_shafer_2hypotheses(*images)[source]
Fuse mass functions from multiple sources using Dempster-Shafer theory with two hypotheses: A and B.
Parameters
- *imagesGeoimage
Each input is a 3-band Geoimage.
Band 1: mass function m(A)
Band 2: mass function m(B)
Band 3: mass function m(A ∪ B)
Returns
- Geoimage
A new Geoimage with 3 bands containing the fused mass functions: m(A), m(B), and m(A ∪ B).
- Geoimage
A new Geoimage with 1 band containing the conflict values.
Examples
>>> fused, conflict = fuse_dempster_shafer_2hypotheses(im1, im2, im3) >>> fused, conflict = fuse_dempster_shafer_2hypotheses(im1, im2, im3, im4) >>> fused, conflict = fuse_dempster_shafer_2hypotheses(im1, im2)
- static adapt(ims, imt, tab_source=None, nb=1000, mapping='gaussian', reg_e=0.1, mu=1.0, eta=0.01, bias=False, max_iter=20, verbose=True, sigma=1)[source]
Adjusts the spectral characteristics of a source image to match those of a target image using optimal transport methods.
This function normalizes the data, applies the chosen optimal transport algorithm to adapt the spectral characteristics, and then restores the original data scale.
Parameters
- imsGeoimage
Source image whose spectral characteristics will be adjusted.
- imtGeoimage or numpy.ndarray
Target image serving as a reference for spectral adjustment, or a NumPy array of shape (N, bands) containing N spectral samples.
- tab_sourcenumpy.ndarray, optional
Required if imt is a NumPy array. Must be an array of shape (M, bands) containing spectral samples from the source image.
- nbint, optional
Number of random samples used to train the transport model. Default is 1000.
- mappingstr, optional
Optimal transport method to use. Available options: - ‘emd’: Earth Mover’s Distance (more precise but slower) - ‘sinkhorn’: Sinkhorn transport with regularization (good balance) - ‘mappingtransport’: Mapping-based transport (flexible) - ‘gaussian’: Transport with Gaussian assumptions (faster, robust) Default is ‘gaussian’.
- reg_efloat, optional
Regularization parameter for Sinkhorn transport. Default is 1e-1.
- mufloat, optional
Regularization parameter for mapping-based methods. Default is 1e0.
- etafloat, optional
Learning rate for mapping-based transport methods. Default is 1e-2.
- biasbool, optional
Adds a bias term to the transport model if enabled. Default is False.
- max_iterint, optional
Maximum number of iterations for iterative transport methods. Default is 20.
- verbosebool, optional
Enables progress messages during processing. Default is True.
- sigmafloat, optional
Standard deviation used for Gaussian transport methods. Default is 1.
Returns
- Geoimage
A new image where the spectral bands of the source image ims are adapted to match those of the target image imt.
Raises
- ValueError
If an unrecognized mapping method is specified.
- RuntimeError
If the adaptation process fails.
Notes
This function uses optimal transport tools (via the POT library).
Raster data is normalized before transport and then denormalized afterward.
Pixels with nodata values in both images are excluded from calculations.
Adjusted values are limited to remain within valid ranges.
Examples
>>> adapted_image = InferenceTools.adapt(source_image, target_image, mapping='sinkhorn', reg_e=0.01) >>> adapted_image.save('adapted_image.tif') >>> >>> # Adaptation using sample arrays >>> adapted_image = InferenceTools.adapt(source_image, tab_target, tab_source, mapping='sinkhorn', reg_e=0.01) >>> adapted_image.save('adapted_image.tif') >>> adapted_image.save('adapted_image.tif') >>> >>> # Adaptation using different methods >>> adapted_gaussian = InferenceTools.adapt(source_image, target_image, mapping='gaussian') >>> adapted_emd = InferenceTools.adapt(source_image, target_image, mapping='emd')
- class rastereasy.rasters[source]
Bases:
object
Utility class for raster image operations.
This class provides static methods for operations like stacking multiple images and removing bands from images.
Examples
>>> # Stack two images >>> combined_image = rasters.stack(image1, image2) >>> >>> # Remove bands from an image >>> reduced_image = rasters.remove_bands(image, bands=["NIR", "SWIR1"])
- static stack(im1, im2, dtype='float64', dest_name=None, reformat_names=False)[source]
Stack two Geoimage objects into a single image.
Parameters
- im1Geoimage
First image to stack
- im2Geoimage
Second image to stack
- dtypestr, optional
Data type for the output image. Default is ‘float64’.
- dest_namestr, optional
Path to save the stacked image. Default is None.
- reformat_namesbool, optional
How to handle band names: - If True: Reset all names like {“1”:1, “2”:2, …} - If False: Adapt names like {“NIR_1”:1, “R_1”:2, “G_1”:3, “R_2”:4, …} Default is False.
Returns
- Geoimage
A new Geoimage containing all bands from both input images
Examples
>>> combined = rasters.stack(sentinel2_img, landsat8_img) >>> combined.info()
- static remove_bands(im, bands, reformat_names=True, dest_name=None)[source]
Remove specified bands from an image.
Parameters
- imGeoimage
The input image
- bandsstr, list, or numpy.ndarray
The bands to remove, specified as either: - A string with a band name (e.g., ‘SWIR1’) - A list or array of band names (e.g., [‘R’, ‘G’, ‘B’]) - An integer representing the band index (e.g., 4) - A list or array of band indices (e.g., [4, 2, 3])
- reformat_namesbool, optional
If True, the band names are renumbered from 1 after removal. If False, the original band names are preserved (gaps may remain). Default is True.
- dest_namestr, optional
Path to save the modified image. Default is None.
Returns
- Geoimage
A new Geoimage with the specified bands removed
Examples
>>> reduced_img = rasters.remove_bands(image, bands=["NIR", "SWIR1"]) >>> reduced_img.info()
- class rastereasy.Visualizer[source]
Bases:
object
Utility class for visualizing raster image data.
This class provides methods for interactive plotting and exploration of spectral data in georeferenced images.
Examples
>>> # Extract and plot spectral values from user-selected pixels >>> series, pixel_i, pixel_j = Visualizer.plot_spectra(image, bands=['R', 'G', 'B'])
- static plot_spectra(im, bands=None, fig_size=(15, 5), percentile=2, title='', title_im='Original image (click outside to stop)', title_spectra='Spectra', xlabel='Bands', ylabel='Value')[source]
Plots and extracts spectral values from user-selected pixels on a multispectral image.
Parameters
- imGeoimage
Multispectral georeferenced image to analyze.
- bandslist, optional
List of bands to use for the color composition in the image plot. Default is None (uses the first three bands).
- fig_sizetuple, optional
Size of the figure in inches, specified as (width, height). Default is (15, 5).
- percentileint, optional
Percentile value for the color composition scaling. Default is 2.
- titlestr, optional
Main title for the figure. Default is ‘’.
- title_imstr, optional
Title for the image plot. Default is “Original image (click outside to stop)”.
- title_spectrastr, optional
Title for the spectra curves plot. Default is “Spectra”.
- xlabelstr, optional
X-axis label for the spectra curves plot. Default is “Bands”.
- ylabelstr, optional
Y-axis label for the spectra curves plot. Default is “Value”.
Returns
- list of lists
Collection of spectral series extracted from the selected pixels.
- list of int
List of row indices (i-coordinates) of the selected pixels.
- list of int
List of column indices (j-coordinates) of the selected pixels.
Notes
The data collection stops when the user clicks outside the image area or clicks the “Finish” button.
Examples
>>> series, i_coords, j_coords = Visualizer.plot_spectra( >>> image, bands=['B01', 'B02', 'B03'], fig_size=(10, 5))