| Title: | Superpixel Segmentation with the Simple Non-Iterative Clustering Algorithm |
| Version: | 0.6.0 |
| Maintainer: | Rolf Simoes <rolfsimoes@gmail.com> |
| Description: | Implements the Simple Non-Iterative Clustering algorithm for superpixel segmentation of multi-band images, as introduced by Achanta and Susstrunk (2017) <doi:10.1109/CVPR.2017.520>. Supports both standard image arrays and geospatial raster objects, with a design that can be extended to other spatial data frameworks. The algorithm groups adjacent pixels into compact, coherent regions based on spectral similarity and spatial proximity. A high-performance implementation supports images with arbitrary spectral bands. |
| Depends: | R (≥ 3.5.0) |
| Suggests: | testthat (≥ 3.0.0), terra, spelling, covr, magick, jpeg, png, knitr, rmarkdown |
| URL: | https://github.com/rolfsimoes/snic, https://rolfsimoes.github.io/snic/ |
| BugReports: | https://github.com/rolfsimoes/snic/issues |
| ByteCompile: | true |
| VignetteBuilder: | knitr |
| RoxygenNote: | 7.3.3 |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| Language: | en-US |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| NeedsCompilation: | yes |
| Packaged: | 2025-11-28 03:49:24 UTC; rolf |
| Author: | Rolf Simoes |
| Repository: | CRAN |
| Date/Publication: | 2025-12-03 20:40:02 UTC |
Backend abstraction layer for SNIC data structures
Description
These generics define the minimal interface required for SNIC to operate on different raster / array backends. Implementations must convert between:
geographic coordinates
(lat, lon),projected map coordinates (
x, y), andpixel indices (
r, c) in image space,
and must provide functions to translate external image objects to raw numeric arrays (and back) for input to the SNIC core.
Usage
## S3 method for class 'array'
.check_x(x, param_name = "x")
## S3 method for class 'array'
.has_crs(x)
## S3 method for class 'array'
.wgs84_to_xy(x, seeds_wgs84)
## S3 method for class 'array'
.xy_to_wgs84(x, seeds_xy)
## S3 method for class 'array'
.xy_to_rc(x, seeds_xy)
## S3 method for class 'array'
.rc_to_xy(x, seeds_rc)
## S3 method for class 'array'
.x_to_arr(x)
## S3 method for class 'array'
.arr_to_x(x, arr, names = NULL)
## S3 method for class 'array'
.x_bbox(x)
## S3 method for class 'array'
.get_idx(x, idx)
.check_x(x, param_name = "x")
.has_crs(x)
.wgs84_to_xy(x, seeds_wgs84)
.xy_to_wgs84(x, seeds_xy)
.xy_to_rc(x, seeds_xy)
.rc_to_xy(x, seeds_rc)
.x_to_arr(x)
.arr_to_x(x, arr, names = NULL)
.x_bbox(x)
.get_idx(x, idx)
.rc_to_wgs84(x, seeds_rc)
.wgs84_to_rc(x, seeds_wgs84)
## S3 method for class 'SpatRaster'
.check_x(x, param_name = "x")
## S3 method for class 'SpatRaster'
.has_crs(x)
## S3 method for class 'SpatRaster'
.wgs84_to_xy(x, seeds_wgs84)
## S3 method for class 'SpatRaster'
.xy_to_wgs84(x, seeds_xy)
## S3 method for class 'SpatRaster'
.xy_to_rc(x, seeds_xy)
## S3 method for class 'SpatRaster'
.rc_to_xy(x, seeds_rc)
## S3 method for class 'SpatRaster'
.x_to_arr(x)
## S3 method for class 'SpatRaster'
.arr_to_x(x, arr, names = NULL)
## S3 method for class 'SpatRaster'
.x_bbox(x)
## S3 method for class 'SpatRaster'
.get_idx(x, idx)
Arguments
x |
Backend-specific raster/array object that implements these conversions. |
param_name |
Parameter name to echo in validation errors for
|
seeds_wgs84 |
Two-column seed object with columns |
seeds_xy |
Two-column seed object with columns |
seeds_rc |
Two-column seed object with 1-based pixel indices
|
arr |
Numeric array with dimensions |
names |
Optional character vector of band names applied by
|
idx |
Numeric or character band identifiers to resolve via
|
Details
The SNIC algorithm itself only works with:
a numeric array
arrwith dimensions(height, width, bands), anda two-column matrix/data frame
seeds_rcgiving pixel coordinates.
All spatial logic, projection handling, and raster I/O is delegated to these interface methods.
Value
Results depend on the generic:
-
.check_x(): the validated backend object (usuallyx) returned invisibly; errors if unsupported. -
.has_crs(): logical flag indicating whetherxcarries a CRS. -
.wgs84_to_xy(): seed data frame with columnsxandyin the CRS ofx. -
.xy_to_wgs84(): seed data frame with columnslatandloninEPSG:4326. -
.xy_to_rc(): seed data frame with 1-based integer columnsrandc; values outside the raster extent may beNA_integer_. -
.rc_to_xy(): seed data frame with columnsxandyin the CRS ofx, with coordinates set toNAwhen indices fall outside the extent. -
.rc_to_wgs84(): seed data frame with columnslatandlonobtained by composing.rc_to_xy()and.xy_to_wgs84(). -
.wgs84_to_rc(): seed data frame with columnsrandcobtained by composing.wgs84_to_xy()and.xy_to_rc(). -
.x_to_arr(): numeric array shaped(height, width, bands)in column-major order. -
.arr_to_x(): object of the same backend type asxcontaining the supplied array data, with band names applied when provided. -
.x_bbox(): numeric vectorc(xmin, xmax, ymin, ymax)in the coordinate system ofx. -
.get_idx(): numeric vector of band indices resolved from numeric or name-based input.
Required Methods for each backend
-
.check_x(x)Validate thatxis a supported input type. Return the validated object (usuallyx) invisibly if supported, or throw an error with a helpful message if not. This is the entry point for SNIC algorithm compatibility. -
.has_crs(x)ReturnTRUEifxcarries a spatial reference system. Used to decide whether seeds are interpreted as pixel coordinates or(lat, lon). -
.wgs84_to_xy(x, seeds_wgs84)Convert(lat, lon)coordinates inEPSG:4326to projected map coordinates ofx's CRS. -
.xy_to_rc(x, seeds_xy)Convert projected(x, y)(map) coordinates to image pixel indices(r, c). Output must be integer and 1-based. -
.rc_to_wgs84(x, seeds_rc)Inverse of the above: convert 1-based pixel indices to(lat, lon). Used to return seeds or segmentation results in geographic form. -
.x_to_arr(x)Convert imagexto a numeric array of shape(height, width, bands)in column-major order. No normalization, scale adjustments, or band selection should be performed here. -
.arr_to_x(x, arr, names = NULL)Wrap a(height, width, bands)numeric array (often single-band output from SNIC) back into the native data type ofx, preserving extent, CRS, resolution, and metadata where possible. -
.xy_to_wgs84(x, seeds_xy)and.rc_to_xy(x, seeds_rc)Inverse conversions that return geographic or projected map coordinates from the respective inputs. -
.x_bbox(x)Returnc(xmin, xmax, ymin, ymax)in the CRS (or pixel) coordinate system ofx. -
.get_idx(x, idx)Resolve character band names or numeric indices into explicit numeric positions for use in downstream helpers.
Note
Backends may differ dramatically in how they internally represent
coordinates and storage layouts. The only requirement is that these
methods form a consistent round-trip:
lat/lon <-> (x, y) <-> (r, c) <-> arr
Internal grid utilities (developer documentation)
Description
These functions implement the core logic for generating seed coordinates used in SNIC grid-based seeding. They are not exported and should not be called directly by users. All grid functions operate in pixel-index space (row/column). CRS-aware conversion is handled elsewhere.
Usage
.check_grid_args(x, spacing, padding)
.grid_count_seeds(x, spacing, padding)
.grid_rect(x, spacing, padding)
.grid_diamond(x, spacing, padding)
.grid_hex(x, spacing, padding)
.grid_random(x, spacing, padding)
.grid_manual(x, snic_args, plot_args)
Functions
-
.check_grid_args(x, spacing, padding)Validates input dimensions and parameters. Ensures:-
xhas positive height and width, -
spacingis numeric of length 2 and greater than 1, -
paddingis numeric of length 2 and non-negative, padding does not eliminate all valid placement area.
-
-
.grid_count_seeds(x, spacing, padding)Computes the number of grid points in each dimension that fit within the interior region defined bypadding. -
.grid_rect(x, spacing, padding)Generates a rectangular grid of seed positions evenly spaced across the available region. -
.grid_diamond(x, spacing, padding)Generates a rectangular grid and a second grid offset diagonally by half the spacing, producing a diamond pattern. Boundary checks ensure offset points remain valid. -
.grid_hex(x, spacing, padding)Similar to.grid_diamond, but applies axis-dependent spacing to approximate a hexagonal tiling geometry. -
.grid_random(x, spacing, padding)Placesprod(.grid_count_seeds(...))uniformly sampled seed positions inside the padded region. Sampling is without replacement. -
.grid_manual(x, snic_args, snic_plot_args)Interactive seeding. Displays an image and iteratively updates seeds based on mouse clicks. Re-runs SNIC and re-plots after each update. Intended for exploratory inspection, not automated workflows.
Internal plotting utilities (developer documentation)
Description
Shared helpers for rendering arrays and raster objects via terra. These functions are not exported; they encapsulate the common steps needed for plotting SNIC images, seeds, and segments.
Usage
.plot_core(x, plot_args)
.plot_seeds(seeds_xy, x, plot_args, add)
.plot_segments(x, plot_args, add)
Functions
-
.plot_core(x, plot_args)Handles the low-level plotting of either a single band or an RGB composite. -
.plot_seeds(seeds_xy, x, plot_args, add)Draws seed locations over an existing plot window. -
.plot_segments(x, plot_args, add)Converts segmentation rasters into polygons and plots them with the supplied style overrides.
Internal SNIC helpers
Description
Developer-facing utilities wrapping the SNIC container metadata and the native segmentation entry point.
Usage
.snic_new(seg)
.snic_check(x)
.snic_seg(x)
.snic_means(x)
.snic_centroids(x)
.snic_animation(
x,
seeds,
file_path,
n_cycles,
delay,
progress,
plot_args,
snic_args,
device_args
)
.snic_core(arr, seeds_rc, compactness)
Functions
-
.snic_new(seg)Packs the segmentation array and metadata into an S3 container. -
.snic_check(x)Validatessnicobjects before accessing their slots. -
.snic_seg(x),.snic_means(x),.snic_centroids(x)Accessors returning the segmentation map, feature means, and centroids respectively. -
.snic_animation(...)Internal driver used bysnic_animation()to orchestrate frame generation. -
.snic_core(arr, seeds_rc, compactness)Thin wrapper around the nativesnic_snicroutine that performs the actual clustering.
Internal utilities for native calls and helpers
Description
Lightweight wrappers for calling into the C++ backend plus helper utilities reused throughout the package.
Usage
.call(fn_name, ...)
.expand(...)
.set_dim(x, dim)
.polygonize(x)
.rast_tmpl(x)
.modify_list(x, y)
Functions
-
.call(fn_name, ...)Executes the registered C++ symbol via.Calland wraps errors with friendly messages. -
.expand(...)A thin wrapper aroundexpand.grid()that drops row attributes and prevents factor coercion. -
.set_dim(x, dim)Re-shapesxby delegating to thesnic_set_dimnative routine. -
.polygonize(x)Converts a segmentation raster into polygons. -
.rast_tmpl(x)Builds an emptyterra::rast()template matching the array's footprint. -
.modify_list(x, y)Modifies x list using named entries from y
Internal message dictionary
Description
Stores lightweight translations for user-facing messages. Extend this list with new language codes (e.g., "pt", "es") as needed.
Usage
.msg_env
.msg_load(lang, msg_lst)
.msg(key, ..., lang = getOption("lang", "en"))
Arguments
lang |
Language override; defaults to |
msg_lst |
Named character vector/list of message templates. |
key |
Message identifier to retrieve. |
... |
Optional |
Format
An object of class environment of length 1.
Convert seed coordinates between raster index, map, and WGS84 systems
Description
These helpers make it easy to express an existing set of seed coordinates in a different coordinate system. Seeds are accepted when they already contain the target column pair and otherwise are projected using the provided raster.
Usage
as_seeds_rc(seeds, x)
as_seeds_xy(seeds, x)
as_seeds_wgs84(seeds, x)
Arguments
seeds |
A data frame, |
x |
A |
Value
A data frame with the target coordinate columns and any additional
columns that were present in seeds.
Target systems
as_seeds_rc()Ensures seeds are expressed in raster row / column indices
(r, c).as_seeds_xy()Ensures seeds use the raster CRS in map units
(x, y).as_seeds_wgs84()Ensures seeds are in geographic coordinates
(lat, lon)inEPSG:4326.
Note
Only rasters with a defined coordinate reference system (CRS) can be transformed to WGS84 coordinates. If the input raster 'x' lacks a CRS, attempting to convert to WGS84 will result in an error.
Examples
if (requireNamespace("terra", quietly = TRUE)) {
# Load a test Sentinel-2 band
s2_file <- system.file(
"demo-geotiff/S2_20LMR_B04_20220630.tif",
package = "snic"
)
s2_rast <- terra::rast(s2_file)
# Create some test coordinates in pixel space
seeds_rc <- data.frame(r = c(10, 20, 30), c = c(15, 25, 35))
# Convert to map coordinates (x,y)
seeds_xy <- as_seeds_xy(seeds_rc, s2_rast)
# Convert to geographic coordinates (lat,lon)
seeds_wgs84 <- as_seeds_wgs84(seeds_rc, s2_rast)
}
Internal seed utilities
Description
Low-level helpers shared across the seed conversion and validation stack. These functions never touch disk or user I/O; they simply standardize how seeds are checked, typed, and appended so that downstream helpers can focus on the conversions.
Usage
.seeds_check(seeds)
## S3 method for class 'data.frame'
.seeds_check(seeds)
## S3 method for class 'matrix'
.seeds_check(seeds)
## S3 method for class ''NULL''
.seeds_check(seeds)
## Default S3 method:
.seeds_check(seeds)
.seeds_type(seeds)
.switch_seeds(seeds, ...)
.append_seed(seeds, new_seed)
.seeds(...)
Arguments
seeds |
A data frame, matrix, or |
new_seed |
Single-row object to append to an existing seed set. |
Components
.seeds_check()Generic plus methods that coerce arbitrary inputs into the required column pairs while emitting targeted errors.
.seeds_type()Identifies which coordinate signature a seed object currently follows so that dispatchers can choose the right path.
.switch_seeds()Wrapper around
switch()that routes execution based on the detected type..append_seed()Appends a single seed row after verifying the incoming and existing coordinate systems match.
.seeds()Thin data.frame constructor with consistent defaults used throughout tests and helper code.
Simple Non-Iterative Clustering (SNIC) segmentation
Description
Segment an image into superpixels using the SNIC algorithm. This function wraps a C++ implementation operating on any number of spectral bands and uses 4-neighbor (von Neumann) connectivity.
Usage
snic(x, seeds, compactness = 0.5, ...)
Arguments
x |
Image data. For the |
seeds |
Initial seed coordinates. The required format depends on the
spatial status of
Seeds define the starting cluster centers. They are usually generated with
|
compactness |
Non-negative numeric value controlling the balance between feature similarity and spatial proximity (default = 0.5). Larger values produce more spatially compact superpixels. |
... |
Currently unused; reserved for future extensions. |
Details
The algorithm performs clustering in a joint space that includes the image's
spectral dimensions and two spatial coordinates. Each seed initializes a
region, and pixels are assigned based on the SNIC distance metric combining
spectral similarity and spatial distance, weighted by compactness.
Value
An object of class snic bundling the segmentation result together
with per-cluster summaries produced by the SNIC algorithm. The segmentation
result can be accessed using snic_get_seg. The per-cluster
summaries can be accessed using snic_get_means and
snic_get_centroids.
See Also
snic_grid for seed generation,
snic_grid_manual for interactive placement,
snic_plot for visualizing results.
Examples
# Example 1: Geospatial raster
if (requireNamespace("terra", quietly = TRUE)) {
path <- system.file("demo-geotiff", package = "snic", mustWork = TRUE)
files <- file.path(
path,
c(
"S2_20LMR_B02_20220630.tif",
"S2_20LMR_B04_20220630.tif",
"S2_20LMR_B08_20220630.tif",
"S2_20LMR_B12_20220630.tif"
)
)
# Downsample for speed (optional)
s2 <- terra::aggregate(terra::rast(files), fact = 8)
# Generate a regular grid of seeds (lat/lon because CRS is present)
seeds <- snic_grid(
s2,
type = "rectangular",
spacing = 10L,
padding = 18L
)
# Run segmentation
seg <- snic(s2, seeds, compactness = 0.25)
# Visualize RGB composite with seeds and segment boundaries
snic_plot(
s2,
r = 4, g = 3, b = 1,
stretch = "lin",
seeds = seeds,
seg = seg
)
}
# Example 2: In-memory image (JPEG) + Lab transform
# Uses an example image shipped with the package (no terra needed)
if (requireNamespace("jpeg", quietly = TRUE)) {
img_path <- system.file(
"demo-jpeg/clownfish.jpeg",
package = "snic",
mustWork = TRUE
)
rgb <- jpeg::readJPEG(img_path) # h x w x 3 in [0, 1]
# Convert sRGB -> CIE Lab for perceptual clustering
dims <- dim(rgb)
dim(rgb) <- c(dims[1] * dims[2], dims[3])
lab <- grDevices::convertColor(
rgb,
from = "sRGB",
to = "Lab",
scale.in = 1,
scale.out = 1 / 255
)
dim(lab) <- dims
dim(rgb) <- dims
# Seeds in pixel coordinates for array inputs
seeds_rc <- snic_grid(lab, type = "hexagonal", spacing = 20L)
# Segment in Lab space and plot L channel with boundaries
seg <- snic(lab, seeds_rc, compactness = 0.1)
snic_plot(
rgb,
r = 1L,
g = 2L,
b = 3L,
seg = seg,
seg_plot_args = list(
border = "black"
)
)
}
Animated visualization of SNIC seeding and segmentation
Description
Generate an animated GIF illustrating how SNIC segmentation evolves as seeds are progressively added. This function runs a sequence of SNIC segmentations using incremental subsets of the provided seeds and compiles the results into an animation.
Usage
snic_animation(
x,
seeds,
file_path,
max_frames = 100L,
delay = 10,
progress = getOption("snic.progress", FALSE),
...,
snic_args = list(compactness = 0.5),
device_args = list(res = 96, bg = "white")
)
Arguments
x |
A |
seeds |
A two-column object specifying seed coordinates. If |
file_path |
Path where the resulting GIF is saved. The file must not already exist and the parent directory must be writable. |
max_frames |
Maximum number of frames to render. If there are more
seeds than |
delay |
Per-frame delay in centiseconds (1/100 s). Passed to
|
progress |
Logical scalar; if |
... |
Additional arguments forwarded to |
snic_args |
Named list of extra arguments passed to |
device_args |
Named list of arguments passed to
|
Details
For each iteration, the function adds one seed to the current set and
re-runs snic. The segmentation and seed locations are drawn
using snic_plot, saved as PNGs, and then combined into an
animated GIF using the magick package. This is intended for
exploratory and didactic use to illustrate the influence of seed placement
and parameters such as compactness.
Value
Invisibly, the file path of the generated GIF.
See Also
snic, snic_plot,
snic_grid, snic_grid_manual.
Examples
if (requireNamespace("terra", quietly = TRUE) &&
requireNamespace("magick", quietly = TRUE)) {
tif_dir <- system.file("demo-geotiff", package = "snic", mustWork = TRUE)
files <- file.path(
tif_dir,
c(
"S2_20LMR_B02_20220630.tif",
"S2_20LMR_B04_20220630.tif",
"S2_20LMR_B08_20220630.tif",
"S2_20LMR_B12_20220630.tif"
)
)
s2 <- terra::aggregate(terra::rast(files), fact = 8)
set.seed(42)
seeds <- snic_grid(s2, type = "random", spacing = 10L, padding = 0L)
gif_file <- snic_animation(
s2,
seeds = seeds,
file_path = tempfile("snic-demo", fileext = ".gif"),
max_frames = 20L,
snic_args = list(compactness = 0.1),
r = 4, g = 3, b = 1,
device_args = list(height = 192, width = 256)
)
gif_file
}
SNIC segmentation container
Description
Objects returned by snic inherit from the snic
S3 class. They are lightweight containers bundling the segmentation
result together with per-cluster summaries produced by the SNIC
algorithm. Internally, a snic object is a named list with
components:
segThe segmentation map in the native type of the input (either a 3D integer
arraywith dimensions(height, width, 1)or a single-layerSpatRaster—matching the input given tosnic()). Values are superpixel labels (positive integers);NAmarks pixels that were not assigned.meansNumeric matrix with one row per superpixel and one column per input band (column names preserved when available), giving the mean feature value of each cluster. May be
NULLif the backend cannot retain these summaries.centroidsNumeric matrix with columns
randcgiving the cluster centers in pixel coordinates (0-based indices used by the SNIC core). May beNULLwhen centroids are unavailable.
The list carries class "snic" to enable the accessors and print
methods below; the segmentation labels index the corresponding rows of
means and centroids.
Usage
snic_get_means(x)
snic_get_centroids(x)
snic_get_seg(x)
## S3 method for class 'snic'
snic_get_means(x)
## S3 method for class 'snic'
snic_get_centroids(x)
## S3 method for class 'snic'
snic_get_seg(x)
## S3 method for class 'snic'
print(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to or from methods. Currently unused, but included for compatibility with S3 method dispatch. |
Value
-
snic_get_means(): Numeric matrix of per-cluster band means, orNULLwhen not available. -
snic_get_centroids(): Numeric matrix with columnsrandcgiving cluster centers in pixel coordinates (0-based), orNULLwhen not available. -
snic_get_seg(): Segmentation map in the native type of the input (arrayorSpatRaster) with integer labels and possibleNAfor unassigned pixels. -
print.snic(): Invisibly returnsxafter printing a human-readable summary.
Accessors
-
snic_get_seg: Retrieve the segmentation result. -
snic_get_means: Retrieve per-cluster feature means. -
snic_get_centroids: Retrieve per-cluster centroids.
Methods
-
snic_animation: Animate the segmentation process. -
print: Print a summary of the segmentation result. -
plot: Visualize the segmentation result.
Spatial grid seeding for SNIC segmentation
Description
Generate seed locations on an image following one of four spatial
arrangements used in SNIC (Simple Non-Iterative Clustering) segmentation:
rectangular, diamond, hexagonal, or random. Works for both numeric arrays
and SpatRaster objects.
Usage
snic_grid(
x,
type = c("rectangular", "diamond", "hexagonal", "random"),
spacing,
padding = spacing/2,
...
)
snic_count_seeds(x, spacing, padding = spacing/2)
Arguments
x |
Image data. For arrays, this must be numeric with dimensions
|
type |
Character string indicating the spatial pattern to generate.
One of |
spacing |
Numeric or integer. Either one value (applied to both axes)
or two values |
padding |
Numeric or integer. Distance from image borders within which
no seeds are placed. May be of length 1 or 2. Defaults to
|
... |
Currently unused; reserved for future extensions. |
Details
The spacing parameter controls seed density. Padding shifts the
seed grid inward so that seeds are not placed directly on image borders.
The spatial arrangements are:
-
rectangular: regular grid aligned with rows and columns. -
diamond: alternating row offsets, forming a diamond layout. -
hexagonal: alternating offsets approximating a hexagonal tiling. -
random: uniform random placement with similar expected density.
The helper snic_count_seeds estimates how many seeds would be
generated for a rectangular lattice with the given spacing and padding,
without computing coordinates. For type = "diamond" or
"hexagonal", the actual number of seeds will be up to roughly
twice this estimate (minus boundary effects). For "random", the
estimate corresponds to the expected density.
If x has a coordinate reference system, the returned data frame
includes geographic coordinates (lat, lon) in EPSG:4326.
Value
A data frame containing:
-
r,cwhenxhas no CRS. -
lat,lonwhenxhas a CRS, expressed inEPSG:4326.
See Also
snic_count_seeds for estimating seed counts.
Examples
# Example 1: Geospatial raster
if (requireNamespace("terra", quietly = TRUE)) {
# Load example multi-band image (Sentinel-2 subset) and downsample
tiff_dir <- system.file("demo-geotiff",
package = "snic",
mustWork = TRUE
)
files <- file.path(tiff_dir, c(
"S2_20LMR_B02_20220630.tif",
"S2_20LMR_B04_20220630.tif",
"S2_20LMR_B08_20220630.tif",
"S2_20LMR_B12_20220630.tif"
))
s2 <- terra::aggregate(terra::rast(files), fact = 8)
# Compare grid types visually using snic_plot for immediate feedback
types <- c("rectangular", "diamond", "hexagonal", "random")
op <- par(mfrow = c(2, 2), mar = c(2, 2, 2, 2))
for (tp in types) {
seeds <- snic_grid(s2, type = tp, spacing = 12L, padding = 18L)
snic_plot(
s2,
r = 4, g = 3, b = 1, stretch = "lin",
seeds = seeds,
main = paste("Grid:", tp)
)
}
par(mfrow = c(1, 1))
# Estimate seed counts for planning
snic_count_seeds(s2, spacing = 12L, padding = 18L)
par(op)
}
# Example 2: In-memory image (JPEG)
if (requireNamespace("jpeg", quietly = TRUE)) {
img_path <- system.file(
"demo-jpeg/clownfish.jpeg",
package = "snic",
mustWork = TRUE
)
rgb <- jpeg::readJPEG(img_path)
# Compare grid types visually using snic_plot for immediate feedback
types <- c("rectangular", "diamond", "hexagonal", "random")
op <- par(mfrow = c(2, 2), mar = c(2, 2, 2, 2))
for (tp in types) {
seeds <- snic_grid(rgb, type = tp, spacing = 12L, padding = 18L)
snic_plot(
rgb,
r = 1, g = 2, b = 3,
seeds = seeds,
main = paste("Grid:", tp)
)
}
par(mfrow = c(1, 1))
par(op)
}
Interactive seed selection for SNIC segmentation
Description
Collect seed points interactively by clicking on the image. Each left-click
adds a new seed; pressing ESC ends the session. After each click,
SNIC segmentation is recomputed and plotted for visual feedback. This is
intended for exploratory and fine-tuning workflows, where automatic seeding
may not be ideal.
Usage
snic_grid_manual(
x,
seeds = NULL,
...,
snic_args = list(compactness = 0.5),
snic_plot_args = list(stretch = "lin", seeds_plot_args = list(pch = 4, col = "#FFFF00",
cex = 1), seg_plot_args = list(border = "#FFFF00", col = NA, lwd = 0.4))
)
Arguments
x |
A |
seeds |
Optional existing seed set to display and extend.
If pixel coordinates are supplied, they are internally converted. If
|
... |
Arguments forwarded to |
snic_args |
A list of arguments passed to |
snic_plot_args |
A list of display modifiers forwarded to
|
Details
After each new seed is placed interactively, segmentation is recomputed to provide immediate feedback on how the seed placement affects clustering.
Value
A two-column data frame of seed coordinates. If x lacks a CRS the
result is always pixel indices (r, c). When x has a CRS:
If
seedswere supplied, their coordinate system is preserved in the output.Otherwise the result is expressed as
(lat, lon)inEPSG:4326.
The output can be passed directly to snic.
See Also
snic, snic_grid, snic_animation.
Examples
if (interactive() && requireNamespace("terra", quietly = TRUE)) {
tiff_dir <- system.file("demo-geotiff",
package = "snic",
mustWork = TRUE
)
files <- file.path(
tiff_dir,
c(
"S2_20LMR_B02_20220630.tif",
"S2_20LMR_B04_20220630.tif",
"S2_20LMR_B08_20220630.tif",
"S2_20LMR_B12_20220630.tif"
)
)
s2 <- terra::aggregate(terra::rast(files), fact = 8)
seeds <- snic_grid_manual(
s2,
snic_args = list(compactness = 0.1),
snic_plot_args = list(r = 4, g = 3, b = 1)
)
seg <- snic(s2, seeds, compactness = 0.1)
snic_plot(
s2,
r = 4, g = 3, b = 1,
stretch = "lin",
seeds = seeds,
seg = seg
)
}
Package initialization hook
Description
Registers the built-in English message catalog during package load.
Usage
.onLoad(libname, pkgname)
Plot SNIC imagery
Description
Render image data processed by SNIC either from in-memory numeric arrays
or from terra::SpatRaster objects
provided by the terra package. The function supports plotting a
single band or a three-channel RGB composite, with optional overlays for
seed points and segmentation boundaries.
Usage
snic_plot(
x,
...,
band = 1L,
r = NULL,
g = NULL,
b = NULL,
col = getOption("snic.col", grDevices::hcl.colors(128L, "Spectral")),
stretch = "lin",
seeds = NULL,
seeds_plot_args = getOption("snic.seeds_plot", list(pch = 20, col = "#00FFFF", cex =
1)),
seg = NULL,
seg_plot_args = getOption("snic.seg_plot", list(border = "#FFD700", col = NA, lwd =
0.6))
)
Arguments
x |
Image data. For the array method this must be a numeric array
with dimensions |
... |
Additional arguments forwarded to the underlying plotting
function. For arrays, these are passed to
|
band |
Integer index of the band to display when producing a single-band plot. Defaults to the first band. |
r, g, b |
Integer indices (1-based) of the bands to use when composing an RGB plot. All three must be supplied to trigger RGB rendering and the image must contain at least three bands. |
col |
Color palette used for single-band plots. Ignored for RGB plots. |
stretch |
Character string indicating the contrast-stretching method.
Determines how band values are scaled to the
Non-numeric arrays or bands with only constant values are plotted as-is. |
seeds |
Optional object containing seed coordinates with
columns |
seeds_plot_args |
Optional named list with additional arguments passed
to |
seg |
For |
seg_plot_args |
Named list of arguments forwarded to
|
Value
Invisibly, NULL.
Examples
if (requireNamespace("terra", quietly = TRUE)) {
tiff_dir <- system.file("demo-geotiff",
package = "snic",
mustWork = TRUE
)
files <- file.path(
tiff_dir,
c(
"S2_20LMR_B02_20220630.tif",
"S2_20LMR_B04_20220630.tif",
"S2_20LMR_B08_20220630.tif",
"S2_20LMR_B12_20220630.tif"
)
)
# Load and optionally downsample for faster segmentation
s2 <- terra::aggregate(terra::rast(files), fact = 8)
# Visualize
snic_plot(s2, r = 4, g = 3, b = 1, stretch = "lin")
}
# Simple array example using bundled JPEG
if (requireNamespace("jpeg", quietly = TRUE)) {
img_path <- system.file("demo-jpeg/clownfish.jpeg",
package = "snic",
mustWork = TRUE
)
# Load
rgb <- jpeg::readJPEG(img_path)
# Visualize
snic_plot(rgb, r = 1, g = 2, b = 3, stretch = "none")
}