API Reference
min_photons calibrates the filtered peak of a noise-free, pixel-integrated Gaussian centered on a pixel. At exactly that photon count it just reaches the threshold. See BoxerConfig for subpixel-position effects. Each camera path uses its own filter kernels, with uniform variance as the sCMOS reference.
Camera and image dimensions must match. Odd and even box sizes are supported; after edge clamping, only the brightest filtered detection per corner and frame remains.
SMLMBoxer.SMLMBoxerSMLMBoxer.GPU_CONTEXT_RESERVESMLMBoxer.BoxerConfigSMLMBoxer.BoxesInfoSMLMBoxer.GetBoxesArgsSMLMBoxer._getboxes_implSMLMBoxer._gpu_maxima2coordsSMLMBoxer._process_with_batchingSMLMBoxer.apiSMLMBoxer.box_cornerSMLMBoxer.convolveSMLMBoxer.convolve_variance_weightedSMLMBoxer.cuda_free_memorySMLMBoxer.dog_border_kernel!SMLMBoxer.dog_conv_kernel!SMLMBoxer.dog_filterSMLMBoxer.dog_filter_variance_weightedSMLMBoxer.dog_kernelSMLMBoxer.dog_kernel_pairSMLMBoxer.estimate_gpu_memory_per_frameSMLMBoxer.fillbox!SMLMBoxer.findlocalmaxSMLMBoxer.frame_fits_some_gpuSMLMBoxer.frames_per_batchSMLMBoxer.free_gpu_arraysSMLMBoxer.gaussian_2dSMLMBoxer.gaussian_pixel_massSMLMBoxer.gaussian_spot_responseSMLMBoxer.genlocalmaximageSMLMBoxer.get_effective_gainSMLMBoxer.get_pixel_sizeSMLMBoxer.get_variance_mapSMLMBoxer.getboxesSMLMBoxer.getboxstackSMLMBoxer.gpu_free_memorySMLMBoxer.has_cudaSMLMBoxer.is_gpu_query_errorSMLMBoxer.is_gpu_resource_errorSMLMBoxer.localmax_kernel!SMLMBoxer.maxima2coordsSMLMBoxer.nvml_deviceSMLMBoxer.nvml_free_memorySMLMBoxer.photons_to_dog_thresholdSMLMBoxer.poll_gpu_nvmlSMLMBoxer.reclaim_failed_gpu_attemptSMLMBoxer.recommend_batch_sizeSMLMBoxer.release_gpu_memorySMLMBoxer.removeoverlapSMLMBoxer.reshape_for_fluxSMLMBoxer.variance_gaussian_windowSMLMBoxer.variance_weighted_gaussian_kernel!SMLMBoxer.variance_weighted_gaussian_kernel_batched!
SMLMBoxer.SMLMBoxer — Module
SMLMBoxerHigh-performance particle/blob detection in SMLM image stacks using difference-of-Gaussians filtering with GPU acceleration and sCMOS variance-weighted filtering support.
API Overview
For a comprehensive overview of the API, use help mode:
?SMLMBoxer.apiOr access the complete API documentation programmatically:
docs = SMLMBoxer.api()SMLMBoxer.GPU_CONTEXT_RESERVE — Constant
GPU_CONTEXT_RESERVEBytes reserved for a CUDA context and the driver. The lab RTX 4090 reported 878.812 MiB in use at start in dev/output/drop-cudnn/pool-diag2-branch.log; round up to 1 GiB.
SMLMBoxer.BoxerConfig — Type
BoxerConfigConfiguration for ROI detection via getboxes().
Use either PSF-aware interface (psfsigma + minphotons) or advanced interface (sigmasmall + sigmalarge + minval). PSF-aware is recommended.
Fields
PSF-Aware Interface (Recommended)
psf_sigma::Union{Float64,Nothing}: PSF sigma in microns (e.g., 0.13 for 130nm PSF). Requires camera for pixel conversion. When set, overrides sigmasmall/sigmalarge/minval.min_photons::Float64: Photon threshold (default: 500.0). A noise-free, pixel-integrated Gaussian centered on a pixel just reaches the threshold at this photon count. A spot centered on a pixel corner needs more photons, about 1.1× at a PSF sigma of 1.35 pixels (0.135 µm on 0.1 µm pixels), 1.2× at 1 pixel and 1.5× at 0.7 pixel.
Advanced Interface (Direct Control)
sigma_small::Float64: Small Gaussian sigma in pixels (default: 1.0)sigma_large::Float64: Large Gaussian sigma in pixels (default: 2.0)minval::Float64: DoG intensity threshold (default: 0.0)
Box Parameters
boxsize::Int: ROI box size in pixels, odd or even (default: 7)overlap::Float64: pixels (default 2.0). Local maxima are found in a square window of k = max(3, ⌊boxsize − overlap⌋) pixels, so two detections in one frame are at least ⌈k/2⌉ pixels apart along x or y. A largeroverlaplets detections sit closer together. This is not a bound on box overlap: with the defaults, neighboring boxes can share 4 rows or columns.
Backend Parameters
backend::Symbol: Compute backend :cpu, :gpu, or :auto (default: :auto)auto_timeout::Float64: Max wait for GPU in :auto mode before CPU fallback (default: 300.0)gpu_timeout::Float64: Max wait for GPU in :gpu mode (default: Inf)on_wait::Union{Function,Nothing}: Optional callback(elapsed, available, required) -> nothingfor GPU wait progress (default: nothing)
GPU memory errors and an unavailable device are retried until auto_timeout under :auto, then processing falls back to the CPU; any other GPU failure uses the CPU at once. Under :gpu, resource errors are retried until gpu_timeout; any other error is raised at once; an interrupt (Ctrl-C) always stops the call. Resource retries halve the batch cap immediately; after a single-frame failure they resume device polling. A frame larger than any GPU can free errors under :gpu or uses the CPU immediately under :auto.
Examples
# PSF-aware (recommended)
config = BoxerConfig(psf_sigma=0.13, min_photons=500.0, boxsize=11)
# Advanced (direct control)
config = BoxerConfig(sigma_small=1.5, sigma_large=3.0, minval=10.0)
# GPU-specific
config = BoxerConfig(psf_sigma=0.13, backend=:gpu, gpu_timeout=60.0)SMLMBoxer.BoxesInfo — Type
BoxesInfoMetadata returned alongside ROIBatch from getboxes().
Fields
backend::Symbol: Compute backend used (:gpu or :cpu)elapsed_s::Float64: Wall time in secondsdevice_id::Int: GPU device ID (0-based), or -1 for CPUn_rois::Int: Number of ROIs detectedbatch_size::Int: Frames per batch during processingn_batches::Int: Number of batches processedmemory_per_batch::Int: Estimated memory per batch in bytes
SMLMBoxer.GetBoxesArgs — Type
GetBoxesArgsInternal structure for getboxes parameters. Users should call getboxes() with keyword arguments rather than constructing this directly.
Primary Interface (Recommended)
psf_sigma::Real: PSF sigma in microns (physical units, e.g., 0.13 for 130nm PSF) Requires camera to be provided for pixel size conversion.min_photons::Real: Photon threshold (default: 500.0). A noise-free, pixel-integrated Gaussian centered on a pixel just reaches the threshold at this photon count. SeeBoxerConfigfor subpixel-position effects.
When psf_sigma is provided:
- Converted to pixels using camera pixel size
- sigmasmall = 1.0 × psfsigma_pixels (automatically calculated)
- sigmalarge = 2.0 × psfsigma_pixels (automatically calculated)
- minval from the actual filter kernels and effective gain (uniform variance for sCMOS)
Advanced Interface (Direct Control)
sigma_small::Real: Small Gaussian sigma in pixels (default: 1.0)sigma_large::Real: Large Gaussian sigma in pixels (default: 2.0)minval::Real: DoG intensity threshold (default: 0.0)
Other Parameters
imagestack: Input image stackcamera: Camera object (IdealCamera or SCMOSCamera)boxsize::Int: ROI box size in pixels, odd or even (default: 7)overlap::Real: pixels (default 2.0). Local maxima are found in a square window of k = max(3, ⌊boxsize − overlap⌋) pixels, so two detections in one frame are at least ⌈k/2⌉ pixels apart along x or y. A largeroverlaplets detections sit closer together. This is not a bound on box overlap: with the defaults, neighboring boxes can share 4 rows or columns.backend::Symbol: Compute backend :cpu, :gpu, or :auto (default: :auto)auto_timeout::Real: Max wait seconds for :auto mode before CPU fallback (default: 300.0)gpu_timeout::Real: Max wait seconds for :gpu mode (default: Inf)on_wait: Optional callback(elapsed, available, required) for wait progress
SMLMBoxer._getboxes_impl — Method
_getboxes_impl(args::GetBoxesArgs)Internal implementation of getboxes that does the actual work.
SMLMBoxer._gpu_maxima2coords — Method
_gpu_maxima2coords(localmaximage::CuArray)GPU-accelerated coordinate extraction using sparse compaction.
Instead of transferring the entire 4D array to CPU (e.g., 1 GB for 512x512x1x1000), uses GPU findall (prefix-sum compaction) to find nonzero indices on-device, then transfers only the sparse indices and values (~1.2 MB for ~100K maxima).
Arguments
localmaximage: 4D CuArray (nrows, ncols, 1, nframes) with nonzero values at maxima
Returns
coords: Vector{Matrix{Float32}} — same format asmaxima2coords
SMLMBoxer._process_with_batching — Method
_process_with_batching(imagestack, args, kernelsize, max_free_mem; use_gpu,
max_batch_frames=size(imagestack, 4), batch_cleanup=nothing)Process imagestack with memory-aware batching. Handles both single-batch (fits in memory) and multi-batch (too large) cases.
Returns (coords, batch_size, n_batches, memory_per_batch).
Arguments
imagestack: 4D image stack (ny, nx, 1, nframes)args: GetBoxesArgs with filter parameterskernelsize: Kernel size for local max detectionmax_free_mem: Available memory in bytesuse_gpu: Whether to use GPU for processingmax_batch_frames: Optional cap on frames per batch, retained across GPU retriesbatch_cleanup: Optional function called after each batch (e.g., for GC)
SMLMBoxer.api — Method
SMLMBoxer.jl API Reference
Particle/blob detection in SMLM image stacks using difference-of-Gaussians filtering with GPU acceleration and sCMOS variance-weighted filtering support.
Exports
Total exports: 6
getboxes- Main detection functionBoxerConfig- Configuration struct for detection parametersBoxesInfo- Metadata struct returned alongside ROIBatchrecommend_batch_size- Memory-aware batch sizing utilityROIBatch- Re-exported from SMLMData.jlSingleROI- Re-exported from SMLMData.jl
Note: SMLMBoxer.api() is available but not exported to avoid conflicts with other JuliaSMLM packages.
Key Concepts
Difference of Gaussians (DoG) Filtering
Detects blob-like features by subtracting two Gaussian-blurred versions of the image:
- sigma_small: Matches PSF size for optimal blob detection
- sigma_large: Suppresses background (typically 2× sigma_small)
- minval: Intensity threshold after filtering
PSF-Aware Detection (Recommended)
Specify physical PSF parameters (in microns), automatically converted to optimal filter settings:
- psf_sigma: PSF sigma in microns (e.g., 0.13 for 130nm PSF)
- min_photons: Total photon threshold (automatically converted to DoG intensity threshold)
Variance-Weighted Filtering (sCMOS)
When SCMOSCamera is provided, implements SMITE-style inverse variance weighting:
- Each pixel weighted by
gaussian_kernel / variance, withvariance = (readnoise / gain)^2in ADU² (gain in e⁻/ADU) - Low-noise pixels: high weight (strong detection influence)
- High-noise pixels: low weight (reduced false positives)
- GPU-accelerated via KernelAbstractions.jl (device-agnostic kernels)
GPU Acceleration and Scheduling
- Standard DoG: NNlib on CPU, KernelAbstractions kernel on GPU. On 500 frames at 256×256, IdealCamera GPU throughput is 13,805 images/s versus 876 with 32 CPU threads, measured on AMD Ryzen 9 5950X / NVIDIA RTX 4090 with SMLMBoxer 0.4.0, CUDA.jl 6.5.0 and KernelAbstractions 0.10.4
- Variance-weighted: KernelAbstractions custom kernels (same code for CPU/GPU)
- Multi-GPU support: polling selects the eligible GPU with the most free memory
GPU support is NVIDIA only through CUDA.jl. AMD or Intel GPUs, or no GPU, use the CPU under :auto and raise GPU backend requested but CUDA is not functional under :gpu. Reactant loads beside SMLMBoxer after removal of the conflicting cuDNN dependency; SMLMBoxer does not use Reactant or need setup for it.
Unified GPU retry loop handles multi-process contention:
- Check that one frame, including the 1.5x safety margin, fits at least one visible GPU's total memory. If none can hold it,
:gpuerrors and:autowarns and uses the CPU at once - Poll all GPUs via NVML without creating CUDA contexts for sufficient free memory and low utilization. When NVML cannot report a GPU's memory, ask CUDA for it
- Acquire GPU context and run processing
- On GPU memory errors or an unavailable device (including context-creation races): try to release memory via
GC.gc(false),CUDA.reclaim()andrelease_gpu_memory(). Halve the failed batch's frame cap and retry immediately; only after a single-frame failure re-poll with the remaining timeout - On any other GPU failure: try to release memory; under
:auto, warn and use the CPU at once; under:gpu, raise the original error at once - On timeout:
:autofalls back to CPU,:gpuerrors with the failed batch size and memory need - On success: release explicitly freed GPU memory without full garbage collection
Backend modes:
:cpu- Always CPU, no GPU involvement:gpu- Require GPU, retry GPU memory errors and an unavailable device untilgpu_timeout(default: Inf); error on timeout; raise any other error at once:auto- Try GPU, retry GPU memory errors and an unavailable device untilauto_timeout(default: 300s), then use the CPU; any other GPU failure uses the CPU at once
Wait progress callback:
config = BoxerConfig(
psf_sigma=0.13,
backend=:auto,
on_wait=(elapsed, available, required) -> @info "Waiting for GPU" elapsed available required
)Configuration
BoxerConfig
Configuration struct for ROI detection parameters. Supports @kwdef construction with defaults.
@kwdef struct BoxerConfig
# PSF-aware interface (recommended)
psf_sigma::Union{Float64,Nothing} = nothing # PSF sigma in microns
min_photons::Float64 = 500.0 # Minimum photons for detection
# Advanced interface (direct control)
sigma_small::Float64 = 1.0 # Small Gaussian sigma in pixels
sigma_large::Float64 = 2.0 # Large Gaussian sigma in pixels
minval::Float64 = 0.0 # DoG intensity threshold
# Box parameters
boxsize::Int = 7 # ROI size in pixels
overlap::Float64 = 2.0 # Local-maximum window is max(3, ⌊boxsize - overlap⌋)
# Backend parameters
backend::Symbol = :auto # :cpu, :gpu, or :auto
auto_timeout::Float64 = 300.0 # Max wait for GPU in :auto mode
gpu_timeout::Float64 = Inf # Max wait in :gpu mode
on_wait::Union{Function,Nothing} = nothing # Optional wait progress callback
endUsage:
# PSF-aware (recommended)
config = BoxerConfig(psf_sigma=0.13, min_photons=500.0, boxsize=11)
# Advanced (direct control)
config = BoxerConfig(sigma_small=1.5, sigma_large=3.0, minval=10.0)
# GPU-specific
config = BoxerConfig(psf_sigma=0.13, backend=:gpu, gpu_timeout=60.0)Core Function
getboxes - Two Calling Conventions
Config-based (recommended for reusable settings):
getboxes(imagestack, camera, config::BoxerConfig) -> (ROIBatch, BoxesInfo)Kwargs-based (convenient for one-off calls):
getboxes(imagestack, camera=nothing; kwargs...) -> (ROIBatch, BoxesInfo)Both conventions are equivalent - kwargs are forwarded to a BoxerConfig internally.
Main detection function. Applies DoG filtering, finds local maxima, extracts ROI patches. Image (rows, columns) must match the camera pixel edges, or DimensionMismatch is raised. Crop the camera together with the image. Odd and even box sizes share the corner rule clamp(center - (boxsize - 1) ÷ 2, 1, image_size - boxsize + 1) on each axis. After clamping, keep the brightest filtered detection per corner and frame.
Arguments:
imagestack::AbstractArray{<:Real}- Input image stack (2D or 3D)camera::Union{AbstractCamera,Nothing}- Camera object (IdealCamera or SCMOSCamera)config::BoxerConfig- Configuration struct (config-based convention)
Kwargs (kwargs-based convention):
PSF-Aware Interface (Recommended):
psf_sigma::Real- PSF sigma in microns (requires camera for pixel size conversion)min_photons::Real- Photon threshold (default: 500.0). A noise-free, pixel-integrated Gaussian centered on a pixel just reaches the threshold at this count. SeeBoxerConfigfor subpixel-position effects.
Advanced Interface (Direct Control):
sigma_small::Real- Small Gaussian sigma in pixels (default: 1.0)sigma_large::Real- Large Gaussian sigma in pixels (default: 2.0)minval::Real- DoG intensity threshold (default: 0.0)
Other Parameters:
boxsize::Int- ROI size in pixels, odd or even (default: 7)overlap::Real- pixels (default 2.0). Local maxima are found in a square window of k = max(3, ⌊boxsize − overlap⌋) pixels, so two detections in one frame are at least ⌈k/2⌉ pixels apart along x or y. A largeroverlaplets detections sit closer together. This is not a bound on box overlap: with the defaults, neighboring boxes can share 4 rows or columns.backend::Symbol- Compute backend::cpu,:gpu, or:auto(default::auto):cpu- Always use CPU:gpu- Require GPU, wait for memory if needed (waits forever by default):auto- Try GPU with timeout, fall back to CPU if memory unavailable
auto_timeout::Real- Max seconds to wait for GPU in:automode (default: 300.0)gpu_timeout::Real- Max seconds to wait in:gpumode (default: Inf)on_wait::Function- Optional callback(elapsed, available, required) -> nothingfor wait progress
Returns: Tuple of (ROIBatch, BoxesInfo)
ROIBatch with fields:
data- ROI stack (boxsize × boxsize × n_rois)x_corners- Vector of x (column) corner positionsy_corners- Vector of y (row) corner positionsframe_indices- Vector of frame indices for each ROIcamera- Camera object (provided or default IdealCamera)roi_size- Size of each ROI (square)
BoxesInfo with fields:
backend- Compute backend used (:gpuor:cpu)elapsed_s- Wall time in secondsdevice_id- GPU device ID (0-based), or -1 for CPUn_rois- Number of ROIs detectedbatch_size- Frames per batch during processingn_batches- Number of batches processedmemory_per_batch- Estimated memory per batch in bytes
recommend_batch_size(height, width; backend=:auto, memory_fraction=0.8) -> Int
Returns the recommended maximum number of frames to load at once given memory constraints.
Use this when processing very large datasets to determine optimal chunk size before calling getboxes().
Arguments:
height::Int- Image height in pixelswidth::Int- Image width in pixelsbackend::Symbol- Compute backend::cpu,:gpu, or:auto(default::auto)memory_fraction::Real- Fraction of free memory to use (default: 0.8)
Returns: Maximum recommended number of frames to load at once
Memory Model: The processing pipeline requires approximately 6× the raw image size:
- Input imagestack
- Filtered stack (DoG output)
- Local maxima detection intermediates
- Coordinate arrays
- Box extraction workspace
- Broadcast temporaries
Example:
using SMLMBoxer
# Check how many 512×512 frames to load at once
max_frames = recommend_batch_size(512, 512)
println("Load up to $max_frames frames at a time")
# Load and process in chunks
for chunk_start in 1:max_frames:total_frames
chunk_end = min(chunk_start + max_frames - 1, total_frames)
imagestack = load_frames(chunk_start:chunk_end)
(roi_batch, info) = getboxes(imagestack, camera; psf_sigma=0.13)
roi_batch.frame_indices .+= chunk_start - 1
# ... process results
endRe-Exported Types
ROIBatch (from SMLMData.jl)
Container for multiple ROIs from particle detection. Supports iteration and indexing.
# Iteration
for roi in roi_batch
# roi is a SingleROI with .data, .corner, .frame_idx
process(roi.data)
end
# Indexing
roi = roi_batch[1] # Returns SingleROISingleROI (from SMLMData.jl)
Individual ROI: image patch, corner (x, y) = (column, row) in camera pixels (1-based), and frame index. Calibration stays on the batch (roi_batch.camera, full image).
Common Workflows
PSF-Aware Detection (Recommended)
using SMLMBoxer, SMLMData
# Create camera with physical pixel size (100nm pixels)
camera = IdealCamera(1:256, 1:256, 0.1f0)
# Config-based (recommended for reusable settings)
config = BoxerConfig(psf_sigma=0.13, min_photons=500.0, boxsize=11)
(roi_batch, info) = getboxes(imagestack, camera, config)
# OR kwargs-based (convenient for one-off calls)
(roi_batch, info) = getboxes(imagestack, camera;
psf_sigma = 0.13, # 130nm PSF in microns
min_photons = 500.0, # Minimum 500 photons
boxsize = 11)
# Access results
n_detections = length(roi_batch.x_corners)
boxes = roi_batch.data # 11×11×n ROI patches
positions_x = roi_batch.x_corners # Column positions
positions_y = roi_batch.y_corners # Row positions
frames = roi_batch.frame_indices
# Check processing info
println("Backend: ", info.backend)
println("Elapsed: ", info.elapsed_s * 1000, " ms")sCMOS Variance-Weighted Detection
using SMLMData
# Create sCMOS camera with readnoise map (Float32 for type consistency)
readnoise_map = Float32.(load_readnoise_calibration("camera_calib.mat"))
camera = SCMOSCamera(256, 256, 0.1f0, readnoise_map)
# Variance-weighted detection (automatically enabled)
(roi_batch, info) = getboxes(imagestack, camera;
psf_sigma = 0.13,
min_photons = 300.0, # Lower threshold possible with noise weighting
backend = :auto) # GPU with CPU fallbackAdvanced: Direct Parameter Control
# Expert mode: bypass PSF-aware interface
# Config-based
config = BoxerConfig(sigma_small=1.5, sigma_large=3.0, minval=10.0, boxsize=9, overlap=1.5)
(roi_batch, info) = getboxes(imagestack, nothing, config)
# OR kwargs-based
(roi_batch, info) = getboxes(imagestack;
sigma_small = 1.5, # Custom filter sigma (pixels)
sigma_large = 3.0,
minval = 10.0, # Direct intensity threshold
boxsize = 9,
overlap = 1.5)Processing Individual ROIs
(roi_batch, info) = getboxes(imagestack, camera; psf_sigma=0.13)
# Iterate over ROIs
for roi in roi_batch
# SingleROI fields:
# - roi.data: Image patch
# - roi.corner: (x, y) corner position
# - roi.frame_idx: Frame index
fit_gaussian(roi.data)
end
# Direct indexing
first_roi = roi_batch[1]Internal Functions (Not Exported)
These functions are documented but not part of the public API. Use at your own risk as they may change.
Filtering:
dog_filter(imagestack, args)- Apply DoG filter (routes to standard or variance-weighted)dog_filter_variance_weighted(imagestack, σ_small, σ_large, args)- Variance-weighted DoGconvolve(imagestack, kernel; use_gpu)- NNlib on CPU, KernelAbstractions on GPUconvolve_variance_weighted(imagestack, variance_map, σ, use_gpu)- Variance-weighted via KAgaussian_2d(sigma, kernelsize)- Create 2D Gaussian kerneldog_kernel(sigma_small, sigma_large)- Create DoG kernel
Local Maxima Detection:
findlocalmax(imagestack, kernelsize; minval, use_gpu)- Find local maximum coordinatesgenlocalmaximage(imagestack, kernelsize; minval, use_gpu)- Generate local max image
Coordinate Processing:
maxima2coords(imagestack)- Convert non-zero pixels to coordinatesremoveoverlap(coords, args)- Remove overlapping detections
Box Extraction:
getboxstack(imagestack, coords, args)- Extract ROI patches at coordinatesfillbox!(box, imagestack, row, col, im, boxsize)- Fill single ROI patch
Helper Functions:
get_pixel_size(camera)- Extract pixel size from cameraphotons_to_dog_threshold(min_photons, psf_sigma)- Convert photon threshold to DoG thresholdget_variance_map(camera, imagesize)- Compute variance map from camerareshape_for_flux(arr)- Reshape array for NNlib convolution
Algorithm Details
Detection Pipeline
- Filtering: Apply DoG filter (standard or variance-weighted based on camera type)
- Local Maxima: Find peaks above threshold using max pooling
- Overlap Removal: Maxima sharing a max-pool window have equal intensities; the earlier detection is kept
- Box Extraction: Clamp corners and retain one box per corner and frame, keeping the brightest filtered detection
- ROIBatch Construction: Package results with camera calibration
PSF-Aware Parameter Conversion
When psf_sigma (microns) is provided:
# Convert to pixels
psf_sigma_pixels = psf_sigma / pixel_size
# Automatic filter sizing
sigma_small = 1.0 × psf_sigma_pixels # Match PSF
sigma_large = 2.0 × psf_sigma_pixels # Background suppression
# Photon threshold → DoG intensity threshold
# P[i,j] is the integral over pixel (i,j) of a unit-photon Gaussian centered on a pixel.
# Ks, Kl are the actual normalized small and large Gaussian kernels of this path.
minval = min_photons * effective_gain * (sum(Ks .* P_small) - sum(Kl .* P_large))
# effective_gain: 1 for IdealCamera (photons); QE / gain for SCMOSCamera (ADU)The standard kernels come from dog_kernel_pair, with common odd size at least ceil(4 * sigma_large). The sCMOS reference uses uniform variance and its actual windows, each with half-width ceil(3 * sigma). Pixel integrals use numerical quadrature accurate to 1e-4 relative; no empirical DoG factor is used. At PSF sigma 1.35 pixels, the response is about 0.547 (standard) or 0.581 (sCMOS) times N / (2π * (sqrt(2) * 1.35)^2). A noise-free spot of min_photons photons centered on a pixel just reaches the threshold. See BoxerConfig for subpixel-position effects. Noise and varying calibration affect real detections.
Variance-Weighted Convolution
For sCMOS cameras with readnoise map:
# Calibration is converted per pixel when readnoise or gain is a map:
variance = (readnoise ./ gain).^2 # ADU²
# At each pixel (i,j):
weightsum = sum(gaussian_weight / variance[ii,jj] * input[ii,jj])
varsum = sum(gaussian_weight / variance[ii,jj])
output[i,j] = weightsum / varsumImplements optimal inverse variance weighting for spatially-varying noise.
Performance Notes
- GPU Memory Management: Automatically batches frames if image stack exceeds GPU memory
- Type Stability: All inputs converted to Float32 at entry point
- Multi-GPU NVML Polling: Checks free memory, process contention, and compute utilization via NVML without creating CUDA contexts. When NVML cannot report a GPU's memory, SMLMBoxer asks CUDA for it. The eligible GPU with the most free memory wins.
- Contention-Safe Retry: GPU memory errors and an unavailable device are retried until the timeout. Any other GPU failure uses the CPU at once under
:auto, or raises the original error at once under:gpu. Each failed attempt tries to release memory; cleanup errors cannot mask the original error or prevent CPU fallback. - Memory Pool Release: Explicitly frees owned GPU arrays within each batch, including on errors. Successful calls synchronize, purge caches and trim the pool without full garbage collection from CUDA.jl 6.2, when
RECLAIM_PURGEbecame available and the defaultreclaim()started running a full GC. CUDA.jl 5, 6.0 and 6.1 use their GC-freeCUDA.reclaim(). Failed attempts useGC.gc(false),CUDA.reclaim()andrelease_gpu_memory(). Release after a short call takes about 0.02 ms on the RTX 4090; returning 2 GiB to the driver takes about 42 ms. On CUDA.jl 5.9 to 6.5.0, the process is back within 64 MiB of its baseline after a call. - Jittered Backoff: NVML polling uses jittered sleep intervals to avoid thundering herd when multiple processes compete for GPUs.
- Backend Abstraction: KernelAbstractions enables same code for CPU/GPU variance weighting
- Typical Speedup: A warmed-up 256×256×10 GPU call takes about 0.75 ms in 0.4.0, down from about 57 ms in 0.3.4 on the RTX 4090 (medians of 0.73–0.84 ms across CUDA.jl 6.4.2 and 6.5.0). The GPU wins from one frame at every size tested (128, 256 and 512 px), with either camera path and either one or 32 CPU threads on the AMD Ryzen 9 5950X. On 500 frames at 256×256, GPU throughput is 13,805 images/s with an IdealCamera and 10,643 with an SCMOSCamera, versus 876 and 76 with 32 CPU threads, measured with CUDA.jl 6.5.0 and KernelAbstractions 0.10.4.
api() returns this documentation as a plain String.
SMLMBoxer.box_corner — Method
Clamp a box corner to the image, using the same rule for odd and even sizes.
SMLMBoxer.convolve — Method
convolve(imagestack, kernel; use_gpu=false)Convolve imagestack with given kernel using NNlib on the CPU, or a KernelAbstractions kernel on the GPU. Requires an odd square kernel, otherwise throws ArgumentError. Uses plain zero padding on every side; no edge normalization.
Arguments
imagestack: Input array of image data (H, W, 1, F)kernel: Kernel to convolve with (K, K), where K is odd
Keyword Arguments
use_gpu: Whether to use GPU
Returns
filtered_stack: Convolved image stack
SMLMBoxer.convolve_variance_weighted — Method
convolve_variance_weighted(imagestack, variance_map, sigma, use_gpu)Apply variance-weighted Gaussian convolution using KernelAbstractions. Device-agnostic: works on CPU and GPU with same code.
Follows same pattern as convolve(): stays on GPU if use_gpu=true, letting interface.jl handle memory batching for both paths uniformly.
Arguments
imagestack: Input image (rows, cols, 1, frames) - CPU or GPU arrayvariance_map: Variance at each pixel (rows, cols)sigma: Gaussian sigmause_gpu: Use GPU if available
Returns
- Variance-weighted filtered image (CuArray if use_gpu, Array otherwise)
SMLMBoxer.cuda_free_memory — Method
cuda_free_memory(i) -> IntReturn free memory in bytes on GPU i, a 0-based CUDA ordinal, from CUDA. Activates the device (creating its context if needed) for the query and restores the previous device.
SMLMBoxer.dog_border_kernel! — Method
dog_border_kernel!(out, img, kernel_small, kernel_large, p)Replace only border pixels of a standard DoG convolution with the difference of the two Gaussians normalized by their in-bounds weights. Runs on CPU and GPU, batched over frames. If either image dimension is at most 2p, every pixel is a border pixel.
SMLMBoxer.dog_conv_kernel! — Method
dog_conv_kernel!(out, img, w, p)KernelAbstractions kernel for direct 2D convolution, batched over frames via ndrange=(nrows, ncols, nframes). Zero padding of p on all sides; the kernel is flipped the way NNlib.conv does (true convolution, not cross-correlation).
Arguments
out: Output array (nrows, ncols, 1, nframes)img: Input array (nrows, ncols, 1, nframes)w: Convolution kernel (K, K)p: Zero-padding on each side (K ÷ 2)
SMLMBoxer.dog_filter — Method
dog_filter(imagestack, args; use_gpu=args.use_gpu)Apply DoG filter to imagestack based on args. Uses variance-weighted filtering if sCMOS camera is provided. For an IdealCamera or no camera, each Gaussian is normalized by its in-bounds weights at image edges, as in the sCMOS path. Interior convolution values are left untouched.
Arguments
imagestack: Input array of image dataargs: Arguments with sigma values and camerause_gpu: Filter on the GPU; the caller's backend decision, which overridesargs.use_gpu(a CPU fallback must not filter on the GPU)
Returns
filtered_stack: Filtered image stack
SMLMBoxer.dog_filter_variance_weighted — Method
dog_filter_variance_weighted(imagestack, sigma_small, sigma_large, args; use_gpu=args.use_gpu)Apply variance-weighted DoG filter using sCMOS variance map. Implements SMITE-style inverse variance weighting during convolution.
Arguments
imagestack: Input image data (rows, cols, 1, frames)sigma_small: Sigma for small Gaussiansigma_large: Sigma for large Gaussianargs: GetBoxesArgs with camerause_gpu: Filter on the GPU (the caller's backend decision; defaults toargs.use_gpu)
Returns
filtered_stack: Variance-weighted filtered image
SMLMBoxer.dog_kernel — Method
dog_kernel(s1, s2)
Compute difference of Gaussian kernels.
Arguments
sigma_small: Sigma for small Gaussiansigma_large: Sigma for large Gaussian
Returns
dog: Difference of Gaussians kernel
SMLMBoxer.dog_kernel_pair — Method
dog_kernel_pair(sigma_small, sigma_large)Return the two normalized Gaussian kernels used by dog_kernel, with the same odd size.
SMLMBoxer.estimate_gpu_memory_per_frame — Method
estimate_gpu_memory_per_frame(height, width, camera) -> IntEstimate GPU memory required per frame.
Arguments
height: Image height in pixelswidth: Image width in pixelscamera: Camera object (affects memory multiplier)
Returns
- Estimated bytes needed per frame for GPU processing
SMLMBoxer.fillbox! — Method
fillbox!(box, imagestack, row, col, im, boxsize)
Fill a box with a crop from the imagestack.
Arguments
box: Array to fill with box cropimagestack: Input image stackrow,col,im: Coords for cropboxsize: Size of box
Returns
boxcoords: Upper Left corners of boxes N x (row, col, im)
SMLMBoxer.findlocalmax — Method
findlocalmax(imagestack, kernelsize; minval=0.0, use_gpu=false)
Find the coordinates of local maxima in an image.
Arguments
imagestack: An array of real numbers representing the image data.kernelsize: The size of the kernel used to identify local maxima.
Keyword Arguments
minval: The minimum value a local maximum must have to be considered valid (default: 0.0).use_gpu: Whether or not to use GPU acceleration (default: false).
Returns
coords: The coordinates of the local maxima in the image.
SMLMBoxer.frame_fits_some_gpu — Method
frame_fits_some_gpu(frame_bytes, totals, reserve) -> BoolWhether any visible device can free enough memory for one frame after reserving reserve bytes for its context and driver. frame_bytes includes the same safety margin used by polling; totals contains device capacities in bytes. An empty device list cannot hold a frame.
SMLMBoxer.frames_per_batch — Method
frames_per_batch(nframes, memory_per_frame, max_free_mem, max_batch_frames) -> IntChoose a batch size from available memory and the frame cap retained across GPU retries. Always attempt at least one frame.
SMLMBoxer.free_gpu_arrays — Method
free_gpu_arrays(arrays...; failed=false)Explicitly free owned CuArray temporaries, ignoring CPU arrays and nothing. Never pass borrowed arrays. Attempt every free even if one fails; on an already failed operation, preserve its original exception instead of replacing it with a cleanup error.
SMLMBoxer.gaussian_2d — Method
gaussian_2d(sigma, ksize)
Create a 2D Gaussian kernel.
Arguments
sigma: Standard deviationkernelsize: Kernel size
Returns
kernel: Normalized 2D Gaussian kernel
SMLMBoxer.gaussian_pixel_mass — Method
Integrate a unit Gaussian over one pixel using an even number of Simpson intervals.
SMLMBoxer.gaussian_spot_response — Method
Return a normalized Gaussian kernel's response to separable pixel masses.
SMLMBoxer.genlocalmaximage — Method
genlocalmaximage(imagestack, kernelsize; minval=0.0, use_gpu=false)
Generate an image highlighting the local maxima using NNlib max pooling on the CPU, or a KernelAbstractions kernel on the GPU.
Arguments
imagestack: An array of real numbers representing the image data (H, W, 1, F).kernelsize: The size of the kernel used to identify local maxima.
Keyword Arguments
minval: The minimum value a local maximum must have to be considered valid (default: 0.0).use_gpu: Whether or not to use GPU acceleration (default: false).
Returns
localmaximage: An image with local maxima highlighted.
SMLMBoxer.get_effective_gain — Method
get_effective_gain(camera::AbstractCamera)Get effective gain for converting photons to image ADU units (ADU/photon).
For IdealCamera: returns 1.0 (assumes image is in photon units) For SCMOSCamera: returns QE / gain (photons → ADU conversion factor)
- SMLMData defines gain as e⁻/ADU (electrons per ADU)
- Physical conversion: photon → QE electrons → electrons/gain ADU
- So: ADU/photon = QE / gain
Used to convert photon-based thresholds to image-unit thresholds.
SMLMBoxer.get_pixel_size — Method
get_pixel_size(camera::AbstractCamera)Extract pixel size from camera pixel edges (in microns). Assumes approximately square pixels - returns x-direction pixel size.
For non-square pixels, pixelsizex and pixelsizey may differ slightly. This function returns pixelsizex for simplicity.
Arguments
camera: Camera object (IdealCamera or SCMOSCamera)
Returns
- Pixel size in microns (x-direction)
SMLMBoxer.get_variance_map — Method
get_variance_map(camera::AbstractCamera, imagesize)Compute variance map from camera calibration.
Arguments
camera: Camera object with noise calibrationimagesize: Tuple of (nrows, ncols) for the image
Returns
- Variance map in ADU²:
(readnoise / gain)^2, per pixel when either is a map. Image and camera dimensions must already match (checked bygetboxes).
SMLMBoxer.getboxes — Method
getboxes(imagestack, camera=nothing; kwargs...) -> (ROIBatch, BoxesInfo)Detect particles/blobs in a multidimensional image stack and return ROI batch with location tracking and processing metadata.
Arguments
imagestack::AbstractArray{<:Real}: The input image stack. Should be 2D or 3D.camera::Union{AbstractCamera,Nothing}: Optional camera object (IdealCamera or SCMOSCamera) from SMLMData. If not provided, an IdealCamera of the image's size with 1 um pixels is created (coordinates in um equal pixels). The image's (rows, columns) must match the camera's pixel edges, otherwise raisesDimensionMismatch. Crop the camera together with the image.
Primary Interface (Recommended - PSF-Aware)
psf_sigma::Real: PSF sigma in microns (physical units, e.g., 0.13 for 130nm PSF). Automatically converted to pixels using camera pixel size and sets optimal DoG filter parameters. Requires camera to be provided.min_photons::Real: Minimum total photons for detection (default: 500.0). A noise-free, pixel-integrated Gaussian centered on a pixel just reaches the threshold at this photon count. SeeBoxerConfigfor subpixel-position effects.
Advanced Interface (Direct Control)
For expert users who want direct control over filter parameters:
sigma_small::Real: Small Gaussian sigma in pixels (default: 1.0).sigma_large::Real: Large Gaussian sigma in pixels (default: 2.0).minval::Real: DoG filter intensity threshold (default: 0.0).
Note: If psf_sigma is provided, it overrides sigmasmall/sigmalarge/minval.
Other Parameters
boxsize::Int: ROI size in pixels, odd or even (default: 7).overlap::Real: pixels (default 2.0). Local maxima are found in a square window of k = max(3, ⌊boxsize − overlap⌋) pixels, so two detections in one frame are at least ⌈k/2⌉ pixels apart along x or y. A largeroverlaplets detections sit closer together. This is not a bound on box overlap: with the defaults, neighboring boxes can share 4 rows or columns.backend::Symbol: Compute backend -:cpu,:gpu, or:auto(default::auto).:cpu- Always use CPU:gpu- Require GPU, wait for memory if needed (waits forever by default):auto- Try GPU with timeout, fall back to CPU on timeout or other GPU failures
auto_timeout::Real: Max seconds to wait for GPU memory in:automode (default: 300.0).gpu_timeout::Real: Max seconds to wait for GPU memory in:gpumode (default: Inf).on_wait::Function: Optional callback(elapsed, available, required) -> nothingfor wait progress.
GPU memory queries use NVML when supported. Otherwise CUDA is queried on each device, restoring the previous device and skipping NVML contention checks for that device. Other device query errors warn and fall back to CPU in :auto mode, or propagate in :gpu.
GPU memory errors and an unavailable device are retried until auto_timeout under :auto, then processing falls back to the CPU; any other GPU failure uses the CPU at once. Under :gpu, resource errors are retried until gpu_timeout; any other error is raised at once; an interrupt (Ctrl-C) always stops the call. Resource retries halve the batch cap immediately; after a single-frame failure they resume device polling. A frame larger than any GPU can free errors under :gpu or uses the CPU immediately under :auto.
Returns
Tuple of (ROIBatch, BoxesInfo):
ROIBatch with the following fields:
data: ROI stack (boxsize × boxsize × n_rois) containing image patchesx_corners: Vector of x (column) corner positions in camera coordinatesy_corners: Vector of y (row) corner positions in camera coordinatesframe_indices: Vector of frame indices for each ROIcamera: Provided camera, or an IdealCamera of the image's size with 1 um pixels (coordinates in um equal pixels)roi_size: Size of each ROI (square)
BoxesInfo with the following fields:
backend: Compute backend used (:gpu or :cpu)elapsed_s: Wall time in secondsdevice_id: GPU device ID (0-based), or -1 for CPUn_rois: Number of ROIs detectedbatch_size: Frames per batch during processingn_batches: Number of batches processedmemory_per_batch: Estimated memory per batch in bytes
Details on filtering
The image stack is convolved with a difference of Gaussians (DoG) filter to identify blobs and local maxima. The DoG is computed from two Gaussian kernels with standard deviations sigma_small and sigma_large.
When using the PSF-aware interface with psf_sigma (in microns):
- psf_sigma is converted to pixels using camera pixel size
- sigmasmall = 1.0 × psfsigma_pixels (matches PSF for optimal blob detection)
- sigmalarge = 2.0 × psfsigma_pixels (background suppression)
- minval uses the actual filter kernels' peak response to a pixel-integrated Gaussian of min_photons photons, times effective gain (QE / gain for sCMOS). The sCMOS reference uses uniform variance and its own Gaussian windows, so thresholds can differ by path.
Variance-Weighted Filtering (sCMOS)
When an SCMOSCamera is provided, the package uses variance-weighted filtering based on the SMITE algorithm. Each pixel's contribution to the convolution is weighted by:
weight = gaussian_kernel / variancewhere variance = (readnoise / gain)² in ADU², per pixel when either calibration is a map (gain in e⁻/ADU). This implements inverse variance weighting:
- Low-noise pixels receive high weight (strong influence on detection)
- High-noise pixels receive low weight (reduced influence, avoiding false positives)
This significantly improves detection sensitivity in sCMOS data with spatially-varying noise.
GPU Acceleration: Variance-weighted filtering uses KernelAbstractions.jl for device-agnostic computation. The same kernel code runs on both CPU and GPU, automatically selected based on backend. This provides GPU acceleration for sCMOS cameras (10-100x speedup on large images).
Standard Filtering (IdealCamera or no camera)
Standard DoG convolution is used when no camera is provided or with IdealCamera. The convolution runs as a KernelAbstractions kernel on the GPU, or via NNlib on the CPU, depending on backend. At image edges, each Gaussian is normalized by its in-bounds weights, as in the sCMOS path. Interior pixels retain the original convolution values.
After filtering, local maxima above minval are identified. Maxima sharing a max-pool window have equal intensities; keep the earlier detection. Boxes use clamp(center - (boxsize - 1) ÷ 2, 1, image_size - boxsize + 1) on each axis. After clamping, only the brightest filtered detection per corner and frame is kept.
Examples
# Recommended: PSF-aware detection with physical units
camera = IdealCamera(1:256, 1:256, 0.1f0) # 256×256 pixels, 100nm pixel size
(roi_batch, info) = getboxes(imagestack, camera;
psf_sigma = 0.13, # PSF sigma in microns (physical units)
min_photons = 500.0, # Detect emitters with ≥500 photons
boxsize = 11)
# Access results
boxes = roi_batch.data # (11 × 11 × n_rois)
x_corners = roi_batch.x_corners # x (col) positions
y_corners = roi_batch.y_corners # y (row) positions
frames = roi_batch.frame_indices
# Check processing info
println("Backend: ", info.backend)
println("Elapsed: ", info.elapsed_s * 1000, " ms")
# Advanced: Direct control over filter parameters
(roi_batch, info) = getboxes(imagestack;
sigma_small = 1.5, # Custom small Gaussian sigma
sigma_large = 3.0, # Custom large Gaussian sigma
minval = 10.0) # Custom intensity threshold
# Iterate over ROIs
for roi in roi_batch
# roi is a SingleROI with .data, .corner, .frame_idx
process(roi.data)
endSMLMBoxer.getboxstack — Method
getboxstack(imagestack, coords, args::GetBoxesArgs)
Cut out box regions from imagestack centered on coords. After clamping corners, keep the brightest filtered detection per corner and frame; ties keep the earlier detection.
Arguments
imagestack: Input image stackcoords: Matrix of (row, col, frame, filtered intensity)args: Parameters
Returns
boxstack: Array with box crops from imagestackboxcoords: Upper left corners of boxes
SMLMBoxer.gpu_free_memory — Method
gpu_free_memory(i) -> IntReturn free memory in bytes on GPU i, a 0-based CUDA ordinal, using nvml_free_memory when supported. Otherwise query CUDA on that device and restore the previous device. Other errors propagate.
SMLMBoxer.has_cuda — Method
has_cuda() -> BoolCheck if CUDA is available. Wrapper for CUDA.functional().
SMLMBoxer.is_gpu_query_error — Method
is_gpu_query_error(e) -> BoolTrue when e comes from querying a GPU (an NVML error, or a CUDA driver error such as a failed context creation). :auto falls back to the CPU on these; anything else propagates.
SMLMBoxer.is_gpu_resource_error — Method
is_gpu_resource_error(e) -> BoolTrue only for GPU memory errors and an unavailable device, including context-creation races. GPU memory errors and an unavailable device are retried until the timeout; any other GPU failure falls back to the CPU at once under :auto, or is raised at once under :gpu; an interrupt (Ctrl-C) always stops the call.
SMLMBoxer.localmax_kernel! — Method
localmax_kernel!(out, img, plo, k)KernelAbstractions kernel for max pooling, batched over frames via ndrange=(nrows, ncols, nframes). Takes the max over the in-bounds part of a k×k window starting at offset -plo, reproducing NNlib.maxpool's odd (symmetric) and even (asymmetric) padding.
Arguments
out: Output array (nrows, ncols, 1, nframes)img: Input array (nrows, ncols, 1, nframes)plo: Window offset,(k - 1) ÷ 2k: Window size
SMLMBoxer.maxima2coords — Method
maxima2coords(imagestack)
Get coordinates of all non-zero pixels in input stack
Arguments
imagestack: Input image stack
Returns
coords: List of coords for each frame (always Float32)
SMLMBoxer.nvml_device — Method
nvml_device(i) -> CUDA.NVML.DeviceReturn the NVML device for GPU i, a 0-based CUDA ordinal, without creating a context. Resolve the CUDA device's UUID so CUDA_VISIBLE_DEVICES and MIG devices are respected.
SMLMBoxer.nvml_free_memory — Method
nvml_free_memory(i) -> Union{Int, Nothing}Return free memory in bytes on GPU i, a 0-based CUDA ordinal, using NVML without a CUDA context. Return nothing if NVML is unavailable or reports NVML_ERROR_NOT_SUPPORTED. Other errors propagate.
SMLMBoxer.photons_to_dog_threshold — Method
photons_to_dog_threshold(min_photons, psf_sigma; effective_gain=1.0,
variance_weighted=false)Convert total photon count threshold to DoG filter intensity threshold in image units (ADU).
Arguments
min_photons: Minimum signal photons above background for detectionpsf_sigma: PSF sigma in pixelseffective_gain: ADU per photon: 1 for an image in photons, QE / gain for an SCMOSCamera (gain in e⁻/ADU; seeget_effective_gain). Default 1.0.variance_weighted: Use the sCMOS Gaussian windows under uniform variance.
Returns
minval: DoG filter intensity threshold in image units (ADU)
Calibration
The threshold is the peak response of this path's actual normalized Gaussian kernels to a noise-free, pixel-integrated Gaussian of min_photons photons centered on a pixel, times effective gain. See BoxerConfig for subpixel-position effects. The standard path uses dog_kernel_pair; the sCMOS reference uses its own windows under uniform variance. Spatially varying calibration and noise affect real detections.
SMLMBoxer.poll_gpu_nvml — Method
poll_gpu_nvml(required_bytes; timeout=30.0, poll=0.5, on_wait=nothing) -> (Bool, Int)Poll all CUDA-visible GPUs via NVML until one has sufficient free memory and low contention. No CUDA context creation needed when NVML supports memory queries, making polling safe under multi-process contention. Otherwise queries CUDA on that device, restores the previous device and skips NVML contention checks for that device.
Arguments
required_bytes: Minimum bytes needed (1.5x safety margin applied internally)timeout: Maximum seconds to poll (default 30.0, use Inf for unlimited)poll: Seconds between checks (default 0.5)on_wait: Optional callback(elapsed, best_available, required) called each poll
Returns
(true, device_id)with a 0-based CUDA ordinal if a GPU became available,(false, -1)if timeout reached
Contention Detection
A GPU is considered contended when other processes are present AND either:
- Free memory is insufficient (< required × 1.5)
- Compute utilization exceeds 90%
When other processes are present but memory is sufficient and utilization is low, the GPU is still considered available.
SMLMBoxer.reclaim_failed_gpu_attempt — Method
reclaim_failed_gpu_attempt()Try to release allocations after a failed GPU attempt. A poisoned CUDA context may make reclaim throw; preserve the processing error and allow CPU fallback in that case.
SMLMBoxer.recommend_batch_size — Method
recommend_batch_size(height, width; backend=:auto, memory_fraction=0.8) -> IntReturn recommended maximum number of frames to load at once given memory constraints.
This helps users decide how much data to load before calling getboxes(). For very large datasets, loading data in chunks of this size ensures efficient processing without running out of memory.
GPU memory is queried via NVML when supported. Otherwise CUDA is queried on each device, restoring the previous device after each query. Other query errors propagate.
Arguments
height::Int: Image height in pixelswidth::Int: Image width in pixelsbackend::Symbol: Compute backend :cpu, :gpu, or :auto (default: :auto)memory_fraction::Real: Fraction of free memory to use (default: 0.8)
Returns
- Maximum recommended number of frames to load at once
Memory Model
The processing pipeline requires approximately 6× the raw image size:
- Input imagestack
- Filtered stack (DoG output)
- Local maxima detection intermediates
- Coordinate arrays
- Box extraction workspace
- Broadcast temporaries
Example
using SMLMBoxer
# Check how many 512×512 frames to load at once
max_frames = recommend_batch_size(512, 512)
println("Load up to $max_frames frames at a time")
# Load and process in chunks
for chunk_start in 1:max_frames:total_frames
chunk_end = min(chunk_start + max_frames - 1, total_frames)
imagestack = load_frames(chunk_start:chunk_end)
(roi_batch, info) = getboxes(imagestack, camera; psf_sigma=0.13)
roi_batch.frame_indices .+= chunk_start - 1
# ... process results
endSMLMBoxer.release_gpu_memory — Method
release_gpu_memory()Return explicitly freed GPU allocations to the driver after a successful call, without running garbage collection. RECLAIM_PURGE is available from CUDA.jl 6.2, when the default reclaim() started running a full GC; purge caches between device synchronizations, then trim the pool. Synchronization must be blocking because CUDA.jl 6.5.0's event-based wait on driver 12.5 or later leaves asynchronously freed blocks unavailable to trimming. On CUDA.jl 5, 6.0 and 6.1, the default reclaim() has no full GC and is used as is.
SMLMBoxer.removeoverlap — Method
removeoverlap(coords, args)
Remove maxima sharing a max-pool window, using Chebyshev distance < cld(k, 2), where k = max(3, floor(Int, boxsize - overlap)). Maxima from the filter that share a window have equal intensities, so the earlier detection is kept. For other input, the dimmer of two maxima is dropped and ties drop the later one. Keep intensities for clamped-corner selection.
Arguments
coords: List of coordsargs: Parameters
Returns
coords: Matrix of (row, col, frame, filtered intensity) with overlaps removed
SMLMBoxer.reshape_for_flux — Method
reshapeforflux(arr::AbstractArray)
Reshape array to have singleton dims for NNlib convolution.
Arguments
arr: Input array, must be 2D or 3D
Returns
- Reshaped array with added singleton dimensions
SMLMBoxer.variance_gaussian_window — Method
Half-width of the sCMOS Gaussian window, shared with photon calibration.
SMLMBoxer.variance_weighted_gaussian_kernel! — Method
variance_weighted_gaussian_kernel!(output, input, variance, sigma, winsize)KernelAbstractions kernel for variance-weighted Gaussian convolution. Implements SMITE-style inverse variance weighting.
This follows the same KernelAbstractions pattern used in GaussMLE.jl (kernel-abstract branch) for seamless CPU/GPU execution and consistent API across JuliaSMLM packages.
Arguments
output: Output array (nrows, ncols)input: Input array (nrows, ncols)variance: Variance map (nrows, ncols)sigma: Gaussian sigmawinsize: Window size (pixels)
Note
Same kernel code runs on CPU (via CPU() backend) or GPU (via CUDABackend()). Backend is selected automatically based on use_gpu parameter.
SMLMBoxer.variance_weighted_gaussian_kernel_batched! — Method
variance_weighted_gaussian_kernel_batched!(output, input, variance, sigma, winsize, nrows, ncols)Batched KernelAbstractions kernel for variance-weighted Gaussian convolution. Processes all frames in a single kernel launch via 3D ndrange=(nrows, ncols, nframes), eliminating per-frame launch overhead.
Arguments
output: Output array (nrows, ncols, 1, nframes)input: Input array (nrows, ncols, 1, nframes)variance: Variance map (nrows, ncols)sigma: Gaussian sigmawinsize: Window size (pixels)nrows: Number of rows (passed explicitly for bounds checking)ncols: Number of columns