Rastereasy Library
Overview and structuration
The rastereasy library provides functions for the easy manipulation (resampling, cropping, reprojection, tiling, …)
and visualization (color composites, spectra) of geospatial raster and vector data (e.g., *.tif, *.jp2, *.shp).  It simplifies geospatial workflows with efficiency.
A geospatial image is read and represented within the Geoimage class, which contains most of the
required functions for processing and visualization. Other classes are related to InferenceTools (some
functions related to clustering, domain adaptation, fusion) shpfiles or rasters (to deal with shapefiles
and rasters respectively)
The goal of rastereasy is to simplify geospatial workflows by offering tools for:
Reading and processing raster and vector files.
Resampling, cropping, reprojecting, stacking, … raster images.
Applying classic filters (gaussian, median, laplace, sobel) and generic ones.
Creating visualizations such as color composites or spectral analyses.
Use (train / apply) some classical Machine Learning algorithms.
Provide some tools for late fusion of classifications (Dempster-Shafer).
Provide some tools for some ML algorithms, basic domain adaptation, …
…
The Geoimage class
The Geoimage class  contains most of the
required functions for processing and visualization. Other classes are related to InferenceTools (some
functions related to clustering, domain adaptation, fusion) shpfiles or rasters (to deal with shapefiles
and rasters respectively).
Apart from
Geoimageclass, rastereasy also provides functions to handle bounding boxes (e.g., extracting common areas between two images, or extending the spatial area of an image to match the extent of another) and to create stacks from individual band files (see in examples).The Geoimage object is the core of the rastereasy library. It acts as a wrapper around a NumPy array, enriched with essential geospatial metadata like its Coordinate Reference System (CRS), spatial resolution, nodata information and geotransform. It provides a wide range of intuitive methods for data processing, analysis, and visualization.
- image: numpy.ndarray
 The raw pixel data of the image as a NumPy array. The shape is typically (rows, columns, bands).
- names: dict
 A dictionary mapping band numbers or default keys to band names. Example:
{'1': 'Red', '2': 'Green', ...}.
- nb_bands: int
 The total number of spectral bands in the image.
- shape: tuple
 The shape of the image as (rows, columns).
- resolution: float or tuple
 The spatial resolution of the pixels (e.g.,
10.0for square pixels).
- nodata: float
 The kind of nodata
- info()
 Print detailed information about the image.
- save(path)
 Saves the Geoimage to a file (e.g., GeoTIFF), preserving geospatial metadata.
- crop(bbox)
 Crops the image to a specified bounding box.
- resample(scale_factor)
 Changes the spatial resolution of the image.
- reproject(projection)
 Transforms the image to a new Coordinate Reference System.
- stack(other_geoimage)
 Combines the current Geoimage with another one into a multi-band image.
- select_bands(bands)
 Extracts one or more spectral bands by name or index.
- switch_band()
 Change the position of a specified band in the image.
- remove_bands()
 Remove specified bands from the image.
- standardize()
 Applies standardization to the image bands.
- inverse_standardize()
 Revert standardization.
- filter(kernel_type, sigma)
 Applies a spatial filter (e.g., ‘gaussian’, ‘sobel’) to the image.
- kmeans(n_clusters)
 Performs K-Means clustering on the image pixels using their band values as features.
The class overloads standard operators for intuitive element-wise algebra:
Arithmetic:
+,-,*,/,**can be used with scalars or other Geoimage objects.Comparison:
<,>,!=,==,<=,>=produce boolean masks.Boolean operation:
and,or,xor,isnan()produce boolean masks.
- replace_values(value_to_replace, new_value)
 Change some specific values in the image
- astype(dtype)
 Convert the image data to a specified data type.
- percentage_pixels(value)
 Percentage of pixels with a specific value
- where(condition, value1, value2)
 Select values based on a condition, similar to numpy.where().
- min(axis)
 Minimal values along various axes
- max(axis)
 Maximal values along various axes
- median(axis)
 Median values along various axes
- sum(axis)
 Sum of values along various axes
- mean(axis)
 Mean of values along various axes
- std(axis)
 Standard deviation of values along various axes
- abs()
 Absolute values
- get_meta()
 Get the metadata dictionary.
- get_bounds()
 Get the geographic bounds of the image.
- latlon2pixel(coord_lat, coord_lon)
 Convert geographic coordinates (latitude, longitude) to pixel coordinates.
- pixel2latlon(i, j)
 Convert pixel coordinates to geographic coordinates (latitude, longitude).
- visu()
 Displays a quick visualization of the image.
- hist()
 Plots histograms of the band values.
- colorcomp(bands=['Red', 'Green', 'Blue'])
 Creates and displays a false-color composite image from specified bands.
- plot_spectra(pixel)
 Plots the spectral signature for a given pixel coordinate.
- numpy_channel_first()
 Extract image data as a NumPy array in channel-first format.
- numpy_channel_last()
 Extract image data as a NumPy array in channel-last format.
- numpy_table()
 Extract image data as a 2D table of shape (pixels, bands).
- image_from_table()
 Create a new Geoimage from a 2D table of shape (pixels, bands)
- upload_image()
 Update the image data with a new image array.
- kmeans()
 Perform K-means clustering on the image data.
- predict()
 Apply a pre-trained machine learning model to the image.
- adapt()
 Adjust spectral characteristics to match a target image.
- fuse_dempster_shafer_2()
 Fuse the 3 band image (associated with mass functions) from multiple sources using Dempster-Shafer theory with two hypotheses: A and B.
- reset_names()
 Reset the band names to sequential numbers (“1”, “2”, …).
- change_nodata()
 Modify the no-data value of the image.
- change_names()
 Modify the names of spectral bands.
- activate_history()
 Activate history tracking for the image object.
- copy()
 Create a deep copy of the Geoimage object.
- extract_from_shapefile()
 Extract data from areas matching a shapefile attribute value.
- extract_from_shapeimage()
 Extract data from areas matching a shape image value.
Note
This module requires external dependencies such as rasterio, numpy, and matplotlib.
Using and citing the toolbox
If you use this toolbox in your research, please cite it as:
Corpetti, T., Matelot, P., de la Brosse, A., & Lissak, C. (2025). Rastereasy: A Python package for easy manipulation of remote sensing images. Manuscript submitted for publication, Journal of Open Source Software.
Some interesting functions
Below are some of the primary functions provided by the module:
Resampling Function
- rastereasy.Geoimage.resample(self, final_resolution, dest_name=None, inplace=False, method='cubic_spline', update_history=True)
 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.resample(30) >>> print(f"New resolution: {image.resolution}") >>> >>> # Resample using nearest neighbor (best for categorical data) >>> classified_image_resampled = classified_image.resample(10, method='nearest') >>> >>> # Resample and save the result >>> image_resampled = image.resample(20, dest_name='resampled_20m.tif') >>> >>> >>> # Resample directly the image to 30 meter resolution >>> image.resample(30, inplace=True) >>> print(f"New resolution: {image.resolution}") >>> >>> # Resample directly the image using nearest neighbor (best for categorical data) >>> classified_image.resample(10, method='nearest', inplace=True) >>> >>> # Resample and save the result >>> image.resample(20, dest_name='resampled_20m.tif', inplace=True)
Notes
Same function as resampling but rather prefer this one
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
Projection Function
- rastereasy.Geoimage.reproject(self, projection='EPSG:3857', inplace=False, dest_name=None)
 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)
Cropping Function
- rastereasy.Geoimage.crop(self, *args, area=None, dest_name=None, pixel=True, inplace=False)
 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
- areatuple
 - Area to crop
 If based on pixel coordinates, you must indicate - the row/col coordinades of
the north-west corner (deb_row,deb_col)
- the row/col coordinades of
 the south-east corner (end_row,end_col)
in a tuple area = ((deb_row,end_row),(deb_col,end_col))
If based on latitude/longitude coordinates, you must indicate - the lat/lon coordinades of the north-west corner (lat1,lon1) - the lat/lon coordinades of the south-east corner (lat2,lon2) area = ((lon1,lon2),(lat1,lat2))
- 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(area=((100, 500), (200, 600))) >>> print(f"Original shape: {original_shape}, New shape: {image_crop.shape}") >>> >>> # Crop using geographic coordinates >>> image_crop = image.crop(area=((-122.5, -122.3), (37.8, 37.7)), pixel=False) >>> image.visu() >>> >>> # Crop and save the result >>> image_crop = image.crop(area=((100, 500), (200, 600)), dest_name='cropped_area.tif') >>> >>> >>> # Crop using pixel coordinates >>> original_shape = image.shape >>> image.crop(area=((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(area=((-122.5, -122.3), (37.8, 37.7)), pixel=False, inplace=True) >>> image.visu() >>> >>> # Crop and save the result >>> image.crop(area=((100, 500), (200, 600)), dest_name='cropped_area.tif', inplace=True)
Notes
For consistency with older versions, a use with 4 parameters (deb_row_lon, end_row_lon, deb_col_lat, end_col_lat) instead of the area tuple is possible
- deb_row_lonint or float
 Starting position (north): - If pixel=True: Starting row (y) coordinate - If pixel=False: Starting longitude coordinate
- end_row_lonint or float
 Ending position (south): - If pixel=True: Ending row (y) coordinate - If pixel=False: Ending longitude coordinate
- deb_col_latint or float
 Starting position (west): - If pixel=True: Starting column (x) coordinate - If pixel=False: Starting latitude coordinate
- end_col_latint or float
 Ending position (east): - 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.
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).
Machine Learning
- rastereasy.Geoimage.kmeans(self, n_clusters=4, bands=None, random_state=None, dest_name=None, standardization=True, nb_points=1000)
 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.predict(model)
Notes
Standardization is recommended, especially when bands have different ranges
The returned model can be used with predict() on other images
- rastereasy.Geoimage.predict(self, model, bands=None)
 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
- modelscikit model or tuple
 If tuple, it must containi (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.predict(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.predict(model, bands=["NIR", "Red"]) >>> result.save("classified.tif") >>> >>> # Apply a RF model trained of other data to a Geoimage >>> from sklearn.ensemble import RandomForestClassifier >>> clf = RandomForestClassifier(max_depth=2, random_state=0) >>> clf.fit(X, y) >>> result = image.predict(clf)
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
Band manipulation
- rastereasy.Geoimage.stack(self, im_to_stack, dtype=None, dest_name=None, inplace=False, reformat_names=False)
 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.
- rastereasy.Geoimage.reorder_bands(self, band_order, inplace=False)
 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.
- rastereasy.Geoimage.remove_bands(self, bands, inplace=False, reformat_names=False, dest_name=None)
 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, …).
Filtering
- rastereasy.Geoimage.filter(self, method='generic', kernel=None, sigma=1, size=3, axis=-1, pre_smooth_sigma=None, inplace=False, dest_name=None)
 Apply a spatial filter to the Geoimage.
Parameters
- methodstr, default=”generic”
 Type of filter. Options: - “generic” : Generic convolution with a kernel. - “gaussian” : Gaussian filter. - “median” : Median filter. - “sobel” : Sobel edge detection (discrete operator). - “laplace” : Laplacian operator (discrete operator).
- kernelnumpy.ndarray, optional
 Convolution kernel (required if mode=”generic”).
- sigmafloat, default=1
 Standard deviation for Gaussian filter (if mode=”gaussian”).
- sizeint, default=3
 Size of the filter window (for median).
- axisint, default=-1
 Axis along which to compute the Sobel filter (if mode=”sobel”). It is 0 for x, 1 for y. If None, computes gradient magnitude.
- pre_smooth_sigmafloat or None, default=None
 If set (e.g., 1.0 or 2.0), a Gaussian filter is applied before Sobel or Laplace, useful to reduce noise and simulate larger kernels.
- inplacebool, default False
 If False, returns a new Geoimage instance with the filtered data. If True, modifies the current image in place.
- dest_namestr, optional
 Path to save the filtered image. If None, the image is not saved. Default is None.
Returns
- Geoimage
 A new filtered Geoimage if inplace=False, otherwise self.
Raises
- ValueError
 If method is unknown.
Examples
>>> # Create a gaussian with sigma = 8 >>> imf = image.filter("gaussian", sigma=8) >>> # Create a median with size = 7 >>> imf = image.filter("median", size=7) >>> # Create a sobel in x-axis >>> imf = image.filter("sobel", axis=0) >>> # Create a sobel in y-axis >>> imf = image.filter("sobel", axis=1) >>> # Create the norm of sobel >>> imf = image.filter("sobel") >>> # Create a sobel in x-axis with pre_smooth_sigma = 2 >>> imf = image.filter("sobel", axis=0, pre_smooth_sigma=2) >>> # Create a sobel in y-axis with pre_smooth_sigma = 2 >>> imf = image.filter("sobel", axis=1, pre_smooth_sigma=2) >>> # Create the norm of sobel with pre_smooth_sigma = 2 >>> imf = image.filter("sobel", pre_smooth_sigma=2)) >>> # Create a laplacian filter >>> imf = image.filter("laplace") >>> # Create a laplacian filter pre_smooth_sigma = 2 >>> imf = image.filter("laplace", pre_smooth_sigma=2)
Access to numpy
- rastereasy.Geoimage.numpy_channel_first(self, bands=None)
 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.
- rastereasy.Geoimage.numpy_channel_last(self, bands=None)
 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.
- rastereasy.Geoimage.image_from_table(self, table, names=None, dest_name=None)
 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.
Processing on images
- rastereasy.Geoimage.adapt(self, 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)
 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
- rastereasy.Geoimage.image_from_table(self, table, names=None, dest_name=None)
 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.
Additional Notes
Refer to the examples in the examples gallery section for practical applications of the library.