Skip to content
프로젝트

소개

Python application based on KLT Algorithm for Registration of Images from Observing Systems (KARIOS)

디자인 및 미디어

이 수치를 측정하는 방법

측정된 스타 증가

in 24h
0
in 7 days
+1
in 15 days
+1
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

The KARIOS Project

DOI License: Apache2 pre-commit Code style: black Imports: isort

KLT-based Algorithm for Registration of Images from Observing Systems (KARIOS)

https://github.com/user-attachments/assets/ae1c28ff-fe07-44b8-9548-ec22725a9573

Introduction

In general, quality assessment processes are fundamental to appreciate how well data is fit for Earth Observation application purposes. Those assessments dedicated to geometric accuracy are rarely open to community. As a consequence, it is difficult to inter compare data based on the same processes and to compare results based on harmonized mapping accuracy metrics.

To overcome this situation, thanks to funding of ESA / EDAP EDAP project, the KARIOS initiative has been launched and a user tool is now available.

The KARIOS tool has been designed to analyse geometric deformations within optical and radar images. For this purpose, the tool performs image matching and generate several key graphical representations and compute accuracy statistics.

Image matching process does not follow traditional approach because it is based on feature point matching (corner). A KLT implementation available in OpenCV library is used in KARIOS. Also, the Candidate point selection is done with GoodFeaturesToTrack function and matching is done with calcOpticalFlowPyrLK function.

As shown in the following picture, KARIOS makes KLT algorithm compatible with remote sensing images embedding suitable pre-processing (image filtering) and post-processing (outlier filtering).

functional representation

As an optional and experimental feature, KARIOS has the capability to detect large shifts between images. If a large shift is detected, the monitored image is shifted according to the offsets found, and the KLT matching is applied

To enable large shift detection, use --enable-large-shift-detection program argument.

Please note that it could use lot of memory in case of large images such as Sentinel2 10 m bands, e.g. 11GB for band B04.

Furthermore, KARIOS analyses displacements between the two input image grids in both line (along-track) and pixel (across-track) directions, providing user with the three following items:

Geometric Error overview

Geometric Error overview

Geometric accuracy report

Geometric accuracy report

Geometric distortion analysis report

Geometric distortion analysis report

The geometric accuracy report includes the following accuracy metrics, in both directions when relevant:

  • Root Mean Square Error
  • Minimum / Maximum Error
  • Mean Error
  • Standard deviation Error
  • Circular Error @90 percentile

The Circular Error (CE) at the 90% level confidence graphic is used for horizontal accuracy in image products.
This representation is relevant for image expressed within cartographic system grid.
Because with the CE representation, it is straightforward to evaluate mapping accuracy, considering reference data with known accuracy.

In case of images with no cartographic system grid, the CE graphic representation becomes less informative.
The CE graphic is still generated, and equally spaced sample data is assumed.
This hypothesis is not obvious, when details on image grids are unknown.

Installation

Prerequisites

This tool is a Python application for which you need a dedicated conda environnement.

  • Python 3.12+
  • Conda or Miniconda. We recommend Miniconda.
  • libGL: you need libGL for linux, depending on your distribution it can be libgl1-mesa-glx, mesa-libGL or another. Install it if you don't have it yet.

Get KARIOS:

git clone https://github.com/telespazio-tim/karios.git

Then goes to KARIOS dir:

cd karios

Environment Setup

  1. Setup the conda environment:

    conda env create -f environment.yml
    

    If the following error message CondaValueError: prefix already exists: <PATH_TO_CONDA_DIR>/envs/karios appears, that means you already have a karios conda environment.

    Update it with following command:

    conda env update -f environment.yml --prune
    
  2. Activate the environment:

    conda activate karios
    
  3. Install KARIOS

For runtime :

pip install .

For development:

pip install -e .

Karios is now installed in its conda envronement.

Verify Installation

python -m karios --help

or

karios --help

Usage

KARIOS can be used both as a command-line tool and as a Python library.

Always activate the environment before using the command-line

conda activate karios

Input Requirements and recommendations

KARIOS takes as inputs:

  • Monitored image (mandatory): The image to analyze for shifts/changes
  • Reference image (mandatory): The stable reference image for comparison
  • Mask file (optional): Exclude pixels from matching (co-registered the monitored image, having byte values, 0 are excluded while 1 are considered has valid for process)
  • DEM file (optional): Enable altitude-based analysis (compatible with reference image)

Requirements:

  • Input images grids should be comparable. The user should take care of data preparation.
    That means geo coded images must have the same footprint, same geotransform information (same cartographic projection, i.e. EPSG code) and same resolution.
  • Image pixel resolution should also be square (same X, Y) and unit meter.

This is also applicable to DEM and mask files for compatibility requirements.

Recommendation:

  • KARIOS converts input data to 8 bit internally, so the shape of the dynamic range matters, not its scale. Rescaling a float image (for instance multiplying values in [0, 1] by 100) makes no difference and is not needed.
    What does matter is extreme and non-finite pixels. For float rasters the conversion takes its bounds from the 2nd and 98th percentile of the finite pixels, so a few stray values are tolerated; for integer rasters it still uses the minimum and maximum, where a single outlier compresses everything else. Mark such pixels as no-data in the raster, or exclude them with --no-value.
  • Input files shall contain only one layer (band) of data, and the format shall be recognized by GDAL library.

Breaking changes in 3.0.0

  • Refused inputs: images and masks that read other data are refused. That covers network paths (/vsicurl, /vsis3, http://...), VRT and web-service rasters, and OGR VRT, WFS, database and GPSBabel vector masks. Convert them to a plain file (e.g. GeoTIFF) first.
  • Exit status: karios process and karios align exit with status 1 on error (they always exited with 0). Scripts can now rely on it.
  • Output folder names: names derived from the input files are sanitized. Path traversal sequences are removed, characters other than letters, digits, _, . and - become _, and Windows reserved names get a safe_ prefix. Inputs with spaces or special characters get differently named output folders.
  • Pixel units: images in a geographic CRS or on a rotated grid are measured in pixels, unless --input-pixel-size is given.
  • API: AccuracyAnalysis has the new required fields rmse, min_error, max_error, std_dev and num_points. They are NaN (num_points is 0) when no key point is confident. Code that builds it by hand must pass them.

CLI Usage

:warning: All commands below suppose that the karios conda environment is activated

Command Structure

karios process MONITORED_IMAGE REFERENCE_IMAGE [MASK_FILE] [DEM_FILE] [OPTIONS]

Arguments

  • MONITORED_IMAGE: Path to the image to analyze for shifts/changes
  • REFERENCE_IMAGE: Path to the stable reference image for comparison
  • MASK_FILE: Optional mask file to exclude pixels from matching (use '-' to skip)
  • DEM_FILE: Optional DEM file for altitude-based analysis

Examples

Basic Processing

karios process monitored.tif reference.tif

With Mask

karios process monitored.tif reference.tif mask.tif

With Mask and DEM

karios process monitored.tif reference.tif mask.tif dem.tif \
  --dem-description "SRTM 30m resample to 10m"

DEM Only (No Mask)

karios process monitored.tif reference.tif - dem.tif \
  --dem-description "Copernicus DEM 30m"

Full Workflow with Options

karios process monitored.tif reference.tif mask.tif dem.tif \
  --out ./results \
  --generate-key-points-mask \
  --generate-intermediate-product \
  --title-prefix "MyAnalysis" \
  --dem-description "SRTM 30m" \
  --enable-large-shift-detection

Resume Previous Analysis

karios process monitored.tif reference.tif mask.tif dem.tif \
  --resume \
  --out ./existing_results

With DN Value Filtering

# Filter out key points with zero DN values
karios process monitored.tif reference.tif --no-value 0

# Filter out multiple DN values (e.g., 0 and 255)
karios process monitored.tif reference.tif --no-value 0 --no-value 255

# Combine with other options
karios process monitored.tif reference.tif mask.tif \
  --no-value 0 \
  --out ./results \
  --generate-key-points-mask

CLI Options

Processing Options

Option Type Description
--conf FILE Configuration file path. Default is the built-in configuration. [default: PWD/karios/configuration/processing_configuration.json]
--resume Flag Do not run KLT matcher, only accuracy analysis and report generation
--input-pixel-size, -pxs FLOAT Input image pixel size in meter. Ignored if image resolution can be read from input image

Output Options

Option Type Description
--out PATH Output results folder path [default: results]
--title-prefix, -tp TEXT Add prefix to title of generated output charts (limited to 26 characters)
--generate-key-points-mask, -kpm FLAG Generate a tiff mask based on KP from KTL
--generate-intermediate-product, -gip FLAG Generate a two-bands tiff based on KP with band 1 dx and band 2 dy
--generate-kp-chips, -gkc FLAG Generate chip images centered on key points of monitored and reference products
--mosaic-tile-size, -mts INTEGER Generate a checkerboard mosaic of the monitored and reference images with tiles of this size in pixel (e.g. 128), shown in the HTML report. 0 disables it [default: 0]
--generate-overlay, -gov FLAG Generate an overlay of the monitored image, in red, and the reference image, in green and blue, shown in the HTML report. Aligned features are gray, shifted ones fringed in red and cyan
--no-value INTEGER Filter out key points where reference or monitored image has this DN value. Can be used multiple times (e.g., --no-value 0 --no-value 255)
--dem-description TEXT DEM source name. Added in generated DEM plots (example: "COPERNICUS DEM resampled to 10m")

Advanced Options

Option Type Description
--enable-large-shift-detection FLAG Enable detection and correction of large pixel shifts. Mutually exclusive with --enable-coarse-to-fine
--enable-coarse-to-fine FLAG Match by descending the image pyramid explicitly, keeping key points near data edges. Mutually exclusive with --enable-large-shift-detection, and not compatible with laplacian_kernel_size: "auto". See KLT param leverage
--laplacian-power FLOAT [0.0-1.0] Shape of the Laplacian rescale feeding the KLT tracker. 0 keeps it as the plain percentile-normalized value; 1 (default) saturates it to a near-binary response, deliberately reproducing the historical behaviour's cross-sensor matching robustness; values in between interpolate via a signed power law.

Logging Options

Option Type Description
--debug, -d FLAG Enable Debug mode
--no-log-file FLAG Do not log in file (not compatible with --log-file-path)
--log-file-path PATH Log file path [default: karios.log]

Library Usage

KARIOS can be used as a Python library in your own applications by providing an API that separates processing configuration from input data.

:warning: Your code should run in a Python environment having KARIOS dependencies installed

Prerequisite

Activate your project conda environment, then install KARIOS in this environment.

From the karios directory, run :

pip install .

Verify with

karios --help

Basic Example

from karios.api import KariosAPI, RuntimeConfiguration
from karios.core.configuration import ProcessingConfiguration

# Load processing configuration
processing_config = ProcessingConfiguration.from_file("config.json")

# Create runtime configuration (how to process)
runtime_config = RuntimeConfiguration(
    output_directory="./results",
    gen_kp_mask=True,
    gen_delta_raster=True,
    pixel_size=10.0,  # meters
    enable_large_shift_detection=False,
    generate_kp_chips=True,
    no_values=[0, 255],  # Optional: filter out key points with DN values 0 and 255
)

# Initialize API
api = KariosAPI(processing_config, runtime_config)

# Process images (what to process) and generates plots
match_result, accuracy, reports = api.process(
    monitored_image_path="monitored.tif",
    reference_image_path="reference.tif",
    mask_file_path="mask.tif",        # Optional
    dem_file_path="dem.tif"           # Optional
)

# Access results
print(f"CE90: {accuracy.ce90:.3f}")
print(f"Mean shift X: {accuracy.mean_x:.3f} pixels")
print(f"Generated reports: {reports.overview_plot}")
print(f"Matching confidence: {accuracy.quality.verdict} ({accuracy.quality.confidence:.0%})")

Batch Processing Example

# Same configuration, multiple image pairs
image_pairs = [
    ("mon1.tif", "ref1.tif", "mask1.tif", "dem.tif"),
    ("mon2.tif", "ref2.tif", "mask2.tif", "dem.tif"),
    ("mon3.tif", "ref3.tif", None, "dem.tif")  # No mask for this pair
]

results = []
for monitored, reference, mask, dem in image_pairs:
    match, accuracy, reports = api.process(monitored, reference, mask, dem)
    results.append({
        'pair': (monitored, reference),
        'ce90': accuracy.ce90,
        'mean_shift': (accuracy.mean_x, accuracy.mean_y)
    })
    # ... other statements 

    # clean memory
    match = None
    accuracy = None
    reports = None
    monitored = None
    reference = None
    mask = None
    dem = None

    # or eventually use gc.collect()

API Components

  • ProcessingConfiguration: KLT parameters, accuracy thresholds, plot settings
  • RuntimeConfiguration: Output settings, processing flags, optional descriptions
  • KariosAPI: Main processing interface
  • MatchResult: Key point matches and image metadata
  • AccuracyAnalysis: Statistical metrics: mean_x, mean_y, std_x, std_y, ce90, ce95, rmse, min_error, max_error, std_dev (standard deviation of the error), num_points (confident key points), valid_pixels, total_pixels, plus the quality confidence and the summary_file path
  • ReportPaths: Generated visualization and product file paths

Configuration

KARIOS uses two types of configurations:

Processing Configuration

The processing configuration defines algorithm parameters and is loaded from JSON files. The default configuration is located in karios/configuration/processing_configuration.json.

This configuration includes:

  • KLT matching parameters: Corner detection, window sizes, quality thresholds
  • Accuracy analysis settings: Confidence thresholds for statistical calculations
  • Plot configurations: Figure sizes, color maps, axis limits
  • Large shift detection: Bias correction thresholds

Runtime Configuration (API)

The runtime configuration defines how processing should be performed and where outputs should be saved. It can be created programmatically when using KARIOS as a library:

runtime_config = RuntimeConfiguration(
    output_directory="./results",
    pixel_size=10.0,              # Optional pixel size override
    title_prefix="MyAnalysis",    # Optional chart title prefix
    gen_kp_mask=True,             # Generate key point mask
    gen_delta_raster=True,        # Generate displacement raster
    generate_kp_chips=True,      # Enable chip generation
    mosaic_tile_size=256,         # Optional: checkerboard mosaic tile size in pixel, 0 (default) disables it
    generate_overlay=True,        # Optional: overlay of the monitored image in red and the reference in cyan
    dem_description="SRTM 30m",   # Optional DEM description for plots
    enable_large_shift_detection=False,
    no_values=[0, 255],           # Optional: filter out key points with these DN values
    debug=True,                   # Also generate the key point coverage plot (05_coverage.png)
    laplacian_power=1.0,          # 0 = plain percentile-normalized value, 1 = near-binary (default)
)

When using the CLI, runtime configuration is automatically created from command-line arguments.

Parameter Details

processing_configuration.shift_image_processing (Large Shift Matching processing parameters)

  • bias_correction_min_threshold: Pixel threshold for applying large shift correction

processing_configuration.klt_matching (Matching processing parameters)

  • xStart: X margin to skip during matching
  • tile_size: Tile size for memory-efficient processing
  • laplacian_kernel_size: Aperture size for Laplacian filtering
  • laplacian_invert_polarity: Controls monitored-image polarity before Laplacian. false (default) keeps pixels as-is, true always inverts them (255 - pixel), and "auto" runs both per tile and keeps the higher-inlier-ratio result. Useful when the two images have opposite feature polarity (e.g. cross-sensor or signed elevation data).

The following parameter allows to control how to find the most prominent corners in the reference image, as described by the OpenCV documentation goodFeaturesToTrack, after applying Laplacian.

  • minDistance: Minimum distance between detected corners
  • blocksize: Block size for derivative computation
  • maxCorners: Maximum corners to extract per tile. 0 implies that no limit on the maximum is set and all detected corners are returned.
  • qualityLevel: Minimum corner quality threshold
  • matching_winsize: Search window size during matching
  • outliers_filtering: Enable/disable outlier filtering
  • maxLevel: Pyramid depth used when matching. Deeper pyramids capture larger displacements but, in the default matching mode, erode matching inward from every data edge. Matching mode itself is a runtime switch, not a configuration key: see --enable-coarse-to-fine.

Refer to section KLT param leverage for details

processing_configuration.accuracy_analysis

  • confidence_threshold: Minimum confidence score for statistical analysis. If None, not applied.

Plot configuration parameters for overview, shift, dem, and ce plots control figure sizes, color maps, and axis limits.

plot_configuration.overview (overview plot parameters)

  • fig_size : Size of the generated figure in inches
  • shift_colormap : matplotlib color map name for the KP shift error scatter plot
  • shift_auto_axes_limit : auto compute KP shift error colorbar scale
  • shift_axes_min_limit : KP shift error colorbar minimum limit (default 0), N/A if shift_auto_axes_limit is true
  • shift_axes_limit : KP shift error colorbar maximum limit, N/A if shift_auto_axes_limit is true
  • theta_colormap : matplotlib color map name for the KP theta error scatter plot
  • theta_min_limit, theta_max_limit : KP angle error colorbar limits in degrees (default -180, 180)

plot_configuration.shift (shift by row/col group plot parameters)

  • fig_size : Size of the generated figure in inches
  • scatter_colormap : matplotlib color map name for the KP shift scatter plot
  • scatter_auto_limit : auto compute KP shift scatter plot limit
  • scatter_min_limit : KP shift scatter plot minimum limit, N/A if scatter_auto_limit is true
  • scatter_max_limit : KP shift scatter plot maximum limit, N/A if scatter_auto_limit is true
  • histo_mean_bin_size : KP shift histogram bin size (number of image row/col for the histogram bin)

plot_configuration.dem (shift by altitude group plot parameters)

  • fig_size : Size of the generated figure in inches
  • show_fliers : draw fliers of box plot
  • histo_mean_bin_size: KP altitude histogram bin size (altitude ranges size)

plot_configuration.ce (Circular error plot parameters)

  • fig_size : Height size of the generated figure in inches, width is 5/3 of the height
  • ce_scatter_colormap : matplotlib color map name for the KP shift density scatter plot
  • ce_auto_limit : auto compute the CE plot axis limits from the largest displacement (default true)
  • ce_axes_limit : CE plot axis limit, the axes span [-limit, limit] in the plot unit (meters, or pixels without pixel size), N/A if ce_auto_limit is true (default 5.0)

plot_configuration.coverage (Key point coverage plot parameters, --debug only)

  • fig_size : Height size of the generated figure in inches
  • grid_size : number of grid cells along each axis used to bin key points for the density and quality maps
  • quality_colormap : matplotlib color map name for the mean-score quality maps (KLT score, ZNCC, NMI)
  • zncc_threshold : ZNCC value (conventionally ~0.8) above which a match is considered trustworthy; shown as a contour line on the ZNCC map and as a "% of KP above threshold" figure

Outputs

KARIOS generates several types of outputs:

Statistical Files

  • CSV file: Key points with dx/dy deviations and confidence scores (see CSV Output section)
  • correl_res.txt: Summary statistics (RMSE, min/max error, standard deviation, CE90, CE95, number of key points)
  • summary.json: Statistics (mean, standard deviation, CE90, CE95, valid pixels) and the matching confidence, machine readable (see Matching Confidence section)

Visualizations

  • 01_overview.png: Error distribution overview with image thumbnails
  • 02_dx.png: X-direction displacement analysis by row/column
  • 03_dy.png: Y-direction displacement analysis by row/column
  • 04_ce.png: Circular error analysis with statistical summaries
  • 05_coverage.png: Key point density, plus three independent quality maps (mean KLT score, mean ZNCC, mean NMI - since a KP the tracker is confident about can still be a poor radiometric match), with coverage statistics (empty cell ratio, coefficient of variation) and a per-column overall mean - only with --debug. The ZNCC map also shows a dashed contour at zncc_threshold (default 0.8) and the share of key points at or above it, since that check is conventionally a statement about individual matches, not a cell average. A high point count is not by itself evidence of a good registration: points can cluster in the most textured regions and leave the rest of the scene unmatched, which the CSV's aggregate statistics cannot reveal on their own.
  • dem_*.png: DEM-based altitude analysis (if DEM provided)
  • 05_mosaic.avif (lossless .png if Pillow has no AVIF support): Color checkerboard mosaic at native resolution, alternating reference (blue) and monitored (red) image tiles, each image histogram equalized to 8 bit, to eyeball misregistration at tile edges. Shown in the Mosaic tab of the HTML report (if --mosaic-tile-size is not 0)
  • 06_overlay.avif (lossless .png if Pillow has no AVIF support): Color overlay at native resolution, the monitored image in the red channel and the reference in the green and blue ones, each histogram equalized to 8 bit: aligned features are gray, shifted ones fringed in red and cyan. Shown in the Overlay tab of the HTML report (if --generate-overlay)

Products (Optional)

  • kp_mask.tif: Binary mask of key point locations (if --generate-key-points-mask)
  • kp_delta.tif: Two-band raster with dx/dy displacement values (if --generate-intermediate-product)
  • kp_delta.json: GeoJSON of key points with displacement vectors (if images are georeferenced, see GeoJSON Output section)
  • chips/ directory: Directory with chip images of KP (see Chip Images section)

Configuration

  • Copy of the processing configuration used

Matching Confidence

KLT returns key points even between two unrelated images, and the statistics computed on them then look like a measurement. karios process therefore rates its confidence that the key points measure a real misregistration, from three indicators computed on the key points above the confidence threshold:

Indicator Meaning Related images Unrelated images
Median ZNCC Correlation of the key points' 57×57 patches in both images, from -1 to 1 0.85-0.88 0.03-0.06
Coherent key points Share of key points whose shift is within 1 px of the median of their 8 nearest neighbours: a misregistration is smooth, false matches are random 97 % 5-6 %
Tracking ratio Share of the corners detected in the reference that pass KLT's forward-backward check 36-39 % 3.3-3.5 %

(Measured on 2000 and 3000 px crops of the Landsat-9 / Sentinel-2 test pair, against the same monitored crop on another area, offset, or flipped.)

Each indicator is mapped linearly to [0, 1] between its unrelated level and its related one (0.1 to 0.5 for the ZNCC, 20 % to 70 % for the coherence, 5 % to 20 % for the tracking ratio), and the confidence, from 0 to 100 %, is their mean. The ZNCC is not available when a large shift was applied, nor the tracking ratio with --resume: the confidence then comes from the others. The verdict is:

  • reliable: confidence of 70 % or more
  • doubtful: confidence between 30 % and 70 %
  • unreliable: confidence below 30 %, or fewer than 30 key points above the confidence threshold

An unreliable result means the images are unrelated, or misregistered beyond the matching range: the statistics are then meaningless. The verdict, the indicators and the reasons for a confidence below 1 are printed in the console summary, shown on the summary page of the HTML report, and written to summary.json. The exit status is not affected.

A scene only partly related to the reference, half of it say, can still be rated reliable: key points rarely survive on the unrelated part, so the statistics come from the related one.

Output File Formats

summary.json

Written next to correl_res.txt, with the statistics of the console summary (mean and standard deviation in pixels, CE90 and CE95 in the image CRS unit when it has a pixel size, in pixels otherwise) and the matching confidence:

{
  "monitored_image": "mon.tif",
  "reference_image": "ref.tif",
  "matched_points": 7813,
  "valid_pixels": 8963138,
  "total_pixels": 9000000,
  "confidence_threshold": 0.4,
  "statistics": {
    "mean_x": -0.0587,
    "mean_y": 0.1195,
    "std_x": 0.3005,
    "std_y": 0.3976,
    "ce90": 5.7159,
    "ce95": 8.5424
  },
  "quality": {
    "confidence": 1.0,
    "verdict": "reliable",
    "detected_points": 20000,
    "tracked_points": 7813,
    "confident_points": 5329,
    "tracking_ratio": 0.39065,
    "median_zncc": 0.851,
    "coherent_fraction": 0.973,
    "reasons": []
  }
}

The confidence, the tracking ratio and the coherent fraction are fractions from 0 to 1 there, not percentages. Undefined values, the statistics without any key point above the confidence threshold or an indicator that is not available, are null.

CSV Output

KARIOS generates a CSV file containing all key points detected by the KLT matcher with their displacement measurements and quality metrics. The CSV file is saved as KLT_matcher_{monitored_filename}_{reference_filename}.csv in the output directory.

CSV Columns

Column Description Unit Notes
x0 X coordinate of key point in reference image pixels Column position (0-based)
y0 Y coordinate of key point in reference image pixels Row position (0-based)
dx Displacement in X direction (column) pixels Positive = eastward shift
dy Displacement in Y direction (row) pixels Positive = southward shift
score KLT matching confidence score 0.0-1.0 Higher values indicate better matches
radial error Euclidean distance of displacement pixels √(dx² + dy²)
angle Direction of displacement degrees Measured from east, counter-clockwise
zncc_score Zero-mean Normalized Cross-Correlation score -1.0 to 1.0 Optional: only if large shift detection is disabled

Notes:

  • The CSV uses semicolon (;) as separator
  • zncc_score is only computed for a selection of key points with KLT score above the confidence threshold
  • zncc_score provides additional matching quality assessment using normalized cross-correlation
  • All coordinates are in image pixel space (not geographic coordinates)

GeoJSON Output

When input images are georeferenced, KARIOS generates a GeoJSON file (kp_delta.json) containing key points as geographic features with displacement vectors and quality metrics.

GeoJSON Structure

{
  "type": "FeatureCollection",
  "crs": {
    "type": "name",
    "properties": {
      "name": "urn:ogc:def:crs:EPSG::{EPSG_CODE}"
    }
  },
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [x_geographic, y_geographic]
      },
      "properties": {
        "dx": displacement_x_pixels,
        "dy": displacement_y_pixels,
        "score": klt_confidence_score,
        "radial error": euclidean_displacement,
        "angle": displacement_angle_degrees,
        "zncc_score": cross_correlation_score
      }
    }
  ]
}

Feature Properties

Property Description Unit Range
dx X displacement in pixels pixels Real number
dy Y displacement in pixels pixels Real number
score KLT matching confidence 0.0-1.0 Higher = better match
radial error Total displacement magnitude pixels ≥ 0
angle Displacement direction degrees -180 to 180
zncc_score Cross-correlation score -1.0 to 1.0 Optional, can be null

Coordinate System:

  • Point coordinates are in the same coordinate reference system as the input images
  • Coordinates are transformed from pixel space to geographic space using the image's geotransform
  • The CRS is specified in the crs object using the EPSG code from the reference image

Chip Images (Optional)

When enabled with --generate-kp-chips, KARIOS generates small image patches (chips) centered on key points for visual inspection and quality assessment.

karios process monitored.tif reference.tif --generate-kp-chips

Chip Specifications

  • Size: 57×57 pixels per chip
  • Selection: Up to 125 chips using center + quarter strategy from a 5×5 grid overlay
  • Quality threshold: Only key points with KLT score ≥ confidence threshold are considered
  • Pairing: Each chip location generates two files (monitored and reference)

Output Structure

results/
└── chips/
    ├── {monitored_filename}/
    │   ├── MON_1234_5678.TIFF
    │   ├── MON_2345_6789.TIFF
    │   └── ...
    ├── {reference_filename}/
    │   ├── REF_1234_5678.TIFF
    │   ├── REF_2345_6789.TIFF
    │   └── ...
    ├── chips.csv
    ├── monitored_chips.vrt
    └── reference_chips.vrt

Generated Files

File Description
MON_{x}_{y}.TIFF Chip from monitored image at reference coordinates (x,y)
REF_{x}_{y}.TIFF Chip from reference image at coordinates (x,y)
chips.csv Metadata of selected key points used for chip generation
*_chips.vrt Virtual raster mosaics for easy visualization in GIS software

Notes:

  • Chips near image boundaries are automatically excluded
  • Coordinate pairs (x,y) in filenames refer to the key point location in the reference image
  • Chips are extracted at the detected displacement location in the monitored image
  • VRT files enable easy visualization of all chips as a single mosaic in QGIS or similar tools

KLT param leverage

maxCorners & tile_size

In order to have a lower memory usage during KLT process, it is possible to define a tile size to process for KLT.

For example, a tile_size of 10000 for an image having a size of 20000 x 20000 pixels will result in 4 tiles to process.

In this context, the KLT process will look in each tile for maxCorners.

While an image of 20000 x 20000 pixels results in 4 equals tiles, an image of 20000 x 15000 pixels will also result in 4 tiles, but with different size, two of 10000 x 10000 pixels and two of 10000 x 5000 pixels.

The consequence is that the density for matching point will not be the same each tile, the bigger tiles will have a lower matching point density than the smallest.

You should also consider that the image can contain empty parts where KLT will not find any matching point. So tiles having large empty parts will also results in a higher matching point density.

In order to avoid density differences in the final result, you can define a tile_size larger than the image with a high maxCorners, or a small tile_size and maxCorners in order to have tiles with almost same size.

For example, for image of 20000 x 15000 pixels, you should consider a tile_size of 20000 (1 tile), or 5000 (12 equal tiles)

maxLevel & coarse-to-fine matching

cv2.calcOpticalFlowPyrLK uses a window of the same pixel size at every pyramid level, so at level L that window spans matching_winsize * 2**L of the original image. Near a data edge the window hangs off the image, the coarse estimate is meaningless, and it seeds every finer level, which cannot recover. Matching therefore erodes inward from every edge as maxLevel grows — the lost band is roughly (matching_winsize / 2) * 2**maxLevel, about 400 px at the defaults with maxLevel: 5.

This is a real trade-off, because a displacement of more than a few pixels needs those coarse levels to be found at all. On a SPOT5/BSG pair misregistered by ~13.6 px, matched in the default mode:

maxLevel key points x extent (image is 2878 px wide)
1 1578 —
3 6794 173–2707
5 1850 606–2263

The --enable-coarse-to-fine switch removes the trade-off. It descends the pyramid one level at a time, running each level with no internal recursion, and hands down a displacement field fitted to that level's reliable points instead of each point's own result. A point near an edge inherits a usable starting guess from its neighbours, so only the finest level's matching_winsize / 2 band is lost — and maxLevel can be raised for capture range without cost. On the same pair, --enable-coarse-to-fine with maxLevel: 5 gives 8800 key points spanning x 24–2856, with roughly half the standard deviation, for about 1.4-1.6x the matching time and no additional memory.

About shift by altitude plot

This output uses box plot to show statistics of KP on altitudes groups.

The box extends from the first quartile (Q1) to the third quartile (Q3) of the data, with a line at the median. The whiskers extend from the box to the farthest data point lying within 1.5x the inter-quartile range (IQR) from the box. Flier points are those past the end of the whiskers. See https://en.wikipedia.org/wiki/Box_plot for reference.

     Q1-1.5IQR   Q1   median  Q3   Q3+1.5IQR
                  |-----:-----|
  o      |--------|     :     |--------|    o  o
                  |-----:-----|
flier             <----------->            fliers
                       IQR

credits https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.boxplot.html

Input Data Relationships

Understanding how input files relate to each other:

Image Compatibility

  • Monitored and Reference images must be compatible:
    • Same footprint and resolution
    • Same coordinate system (EPSG)
    • Same pixel grid alignment

Mask Usage

  • Mask file must be compatible with the monitored image
  • Used to exclude pixels from KLT feature detection
  • Typical use cases: exclude water bodies, clouds, or invalid data areas
  • Pixel value 0 = exclude from matching, non-zero = include

DEM Usage

  • DEM file must be compatible with the reference image
  • Used to extract altitude values at key point locations
  • Enables analysis of geometric errors vs terrain elevation
  • Helps identify elevation-dependent systematic errors

Troubleshooting

Common Issues

Image Compatibility Errors

KariosException: Monitored image geo info not compatible with reference image

Solution: Ensure both images have:

  • Same coordinate system (EPSG code)
  • Same pixel resolution
  • Same geographic extent
  • Same grid alignment

Mask or DEM Compatibility Errors

KariosException: Mask geo info not compatible with monitored image

Solution: Ensure mask has the same geometry as monitored image

Unreliable Matching Confidence

Matching confidence: UNRELIABLE (0 %)

The key points do not measure a misregistration (see Matching Confidence). Solution: check that both images cover the same scene; if they do, the misregistration may exceed the matching range: try --enable-large-shift-detection, a larger matching_winsize or maxLevel, or align the images first with karios align.

Performance Optimization

For Large Images

  • Use smaller tile_size (e.g., 5000-10000 pixels)
  • Reduce maxCorners per tile
  • Enable outliers_filtering: false for faster processing

For High Accuracy

  • Increase maxCorners for more key points
  • Use smaller matching_winsize for precise matching
  • Increase qualityLevel for better corner quality

Advanced Features

Large Shift Detection

When enabled with --enable-large-shift-detection, KARIOS can detect and compensate for large pixel offsets between images:

karios process monitored.tif reference.tif --enable-large-shift-detection

Use cases:

  • Images with significant misalignment
  • Coarse co-registration before fine matching
  • Detection of systematic offsets

Warning: Experimental feature that may use significant memory for large images.

Global Alignment (karios align)

karios align estimates and applies a global 2D homography to align the monitored image on the reference, keeping its CRS, grid and resolution. It is exposed as a standalone command — run it before karios process (with the aligned monitored image as input) when the inputs have significant rotation, scale, or perspective differences:

karios align monitored.tif reference.tif --out ./aligned
# Optionally, keep the 20000 strongest SIFT keypoints per image instead of 10000 (0 keeps all)
karios align monitored.tif reference.tif --out ./aligned --sift-nfeatures 20000
# karios process needs both images on one grid: resample the reference onto the
# aligned image's, with the gdalwarp command `karios align` prints, e.g.
gdalwarp -r cubic -t_srs EPSG:32631 -te 637530.0 4805820.0 659670.0 4829340.0 -tr 3.75 3.75 reference.tif ./aligned/reference_on_grid.tif
karios process ./aligned/monitored_global_aligned.tiff ./aligned/reference_on_grid.tif

The pipeline:

  1. Preprocess both inputs to uint8 with a percentile stretch and CLAHE, which equalises radiometry between sensors.
  2. Work at a common resolution when both images are georeferenced: their georeferencing gives a prior homography — directly from the geotransforms for two north-up images in the same CRS, otherwise fitted on a grid of monitored pixels reprojected into the reference's pixels, which takes any pair of CRS and rotated or mirrored grids (a PhiSat scene in WGS 84 fits a UTM Sentinel-2 tile within a pixel). The monitored image is straightened by the prior into the reference's orientation, since SIFT does not handle a mirrored image; the finer image is area-averaged down to the coarser one's pixel size, and the reference is cropped to the monitored footprint plus a search margin of half its size; only that window is read from disk. The georeferencing error has to fit in that margin: when the result looks cut short by the window (no plausible estimate, a gradient correlation under 0.2, or a shift beyond 75% of the margin), the margin is doubled, up to the whole reference, and the best result of the windows tried is kept. Otherwise a much finer monitored image has keypoints of details the reference cannot show, and a small footprint leaves most reference keypoints without a counterpart.
  3. Search the translation left by the georeferencing, by zero-mean correlation of a fully valid central block of the monitored image over the search window. ECC only corrects a few pixels, so a georeferencing kilometres off needs this coarse start.
  4. Detect SIFT keypoints and 128-dim descriptors on both images. By default the 10000 strongest per image are kept; --sift-nfeatures N keeps the N strongest, and 0 keeps them all, at the cost of a longer matching on large images.
  5. Match descriptors with a brute-force L2 matcher, or a FLANN KD-tree above 10⁸ descriptor pairs (a scene on a 10 m Sentinel-2 crop can have half a million reference keypoints), then filter with Lowe's ratio test and a mutual nearest-neighbour cross-check.
  6. Fit a 3×3 homography (8 DOF — translation, rotation, scale, shear, perspective) with cv2.findHomography + RANSAC. With a prior, a SIFT failure is not fatal: the other starting points remain.
  7. Refine with cv2.findTransformECC(MOTION_HOMOGRAPHY) on Sobel gradient magnitudes (sensor-invariant): a 25-iteration probe from every starting point (the RANSAC fit, the prior and the translation search), then up to 200 iterations from the probe that correlates best only.
  8. Select: with a prior, estimates too far from it to be a georeferencing correction are rejected (a reflection, a scale change beyond ×1.5, an anisotropy beyond 1.3, a rotation beyond 30°, or a move beyond the search window), and the gradient correlation of the others, computed on the pixels they all cover, picks the result. Without a prior, the RANSAC fit refined by ECC is kept.
  9. Warp the monitored image with cv2.warpPerspective by nearest neighbour, which keeps its original pixel values, onto its own grid, in its own CRS: same pixel size and pixel edges, extended or cropped by whole pixels to its corrected valid footprint, so a correction of whole pixels moves the georeferencing and leaves the pixels untouched. A rotated or mirrored grid becomes north-up in the same CRS, at the same pixel area. The output overlays the reference in QGIS, which reprojects on the fly. Without georeferencing on both images there is no CRS to bring the correction back to: the output then covers the monitored footprint in the reference on a grid nested in the reference's, its pixel the reference's divided by the smallest integer that keeps the monitored resolution (a 4.1 m image on a 30 m reference gets 30 / 8 = 3.75 m pixels; one coarser than the reference gets the reference's own pixels), georeferenced in the reference's CRS.

The command writes <mon_stem>_global_aligned.tiff, the monitored image aligned on the reference, and <mon_stem>_global_alignment.json, the alignment itself.

The final 3×3 homography, an approximate decomposition (rotation, scale-x/y, translation, perspective magnitude, RANSAC inlier ratio), the output grid and the gdalwarp command resampling the reference onto it are printed to stdout.

Use cases:

  • Cross-sensor pairs with significant rotation, scale, or perspective differences
  • Inputs with inaccurate geotransforms (one or both products mis-registered)
  • Removing systematic geometric error before fine KLT matching

Applying one alignment to the other bands of a product

The homography estimated on each band of one product differs slightly from band to band, so bands aligned separately no longer overlay. Align one band and apply its alignment to the others with --apply-to, repeated for each band, or later from the saved alignment with --load-transform, which takes no reference image:

karios align B04.tif reference.tif --out ./aligned --apply-to B02.tif --apply-to B03.tif
# Later, without estimating it again
karios align B08.tif --load-transform ./aligned/B04_global_alignment.json --out ./aligned

Each image is written as <stem>_global_aligned<ext>. A band on the aligned band's grid (same size, geotransform and CRS) comes out on its output grid, pixel for pixel, so the aligned bands stack. A band on another grid, like a 20 m band of a 10 m product, is placed on the aligned band by their georeferencing, corrected the same way, and keeps its own grid and CRS over its corrected footprint. Without georeferencing on the aligned band or the reference, the alignment only applies to images on the aligned band's grid.

The JSON file holds the 3×3 homography from the monitored pixels to the reference pixels and the one the georeferencing implies (OpenCV pixel-center coordinates), the size, geotransform and CRS of both images, and the output grid.

Resume Functionality

Skip KLT matching and reuse previous results:

karios process monitored.tif reference.tif --resume --out ./existing_results

Requirements:

  • Previous KLT CSV results must exist in output directory
  • Same images pair and configuration

Additionnal Documentation

Software User Manual

License

Apache License 2.0 - see LICENSE file for details.

Citation

If you use KARIOS in your research, please cite:

@software{karios2024,
  author = {{KARIOS Development Team}},
  title = {KARIOS: KLT-based Algorithm for Registration of Images from Observing Systems},
  url = {https://github.com/telespazio-tim/karios},
  doi = {10.5281/zenodo.10598329},
  year = {2024}
}

Acknowledgments

This project has been funded by ESA/EDAP (European Space Agency Earth Observation Data Assessment Pilot).


For more information, issues, or contributions, please visit the project repository.

관련 프로젝트 살펴보기

불러오는 중…