module

CrImage::Util::Convolution

Convolution operations for image filtering and effects.

Provides low-level convolution operations used by filters like blur, sharpen, and edge detection. Supports both standard 2D kernels and separable 1D kernels for performance.

Class methods

apply_kernel(src : Image, kernel : Array(Array(Float64)), divisor : Float64 | Nil = nil) : Image

Applies a 2D convolution kernel to an image.

Convolves the image with the specified kernel matrix. Each output pixel is computed as a weighted sum of neighboring input pixels according to the kernel weights.

Parameters:

  • src : The source image
  • kernel : 2D array of weights (must be square and odd-sized)
  • divisor : Optional normalization divisor (default: sum of kernel)

Returns: A new RGBA image with convolution applied

Raises: ArgumentError if kernel is not square or not odd-sized

Example:

# 3x3 sharpen kernel
kernel = [
  [0.0, -1.0, 0.0],
  [-1.0, 5.0, -1.0],
  [0.0, -1.0, 0.0],
]
sharpened = CrImage::Util::Convolution.apply_kernel(img, kernel)
Source
apply_separable(src : Image, kernel : Array(Float64)) : Image

Applies a separable 1D convolution kernel (horizontal then vertical).

Separable convolution is much faster than 2D convolution for kernels that can be decomposed into horizontal and vertical passes (like Gaussian blur). Complexity is O(n) instead of O(n²) per pixel.

Parameters:

  • src : The source image
  • kernel : 1D array of weights (must be odd-sized)

Returns: A new RGBA image with separable convolution applied

Raises: ArgumentError if kernel size is not odd

Example:

# 1D Gaussian kernel
kernel = [0.06, 0.24, 0.40, 0.24, 0.06]
blurred = CrImage::Util::Convolution.apply_separable(img, kernel)
Source
gaussian_kernel(radius : Int32, sigma : Float64 | Nil = nil) : Array(Float64)

Generates a 1D Gaussian kernel for blur operations.

Creates a normalized Gaussian distribution kernel suitable for separable convolution. The kernel is symmetric and sums to 1.0.

Parameters:

  • radius : Kernel radius (total size = radius * 2 + 1)
  • sigma : Standard deviation (default: radius / 3, clamped to 0.5 minimum)

Returns: Normalized 1D Gaussian kernel

Raises: ArgumentError if radius is negative

Example:

kernel = CrImage::Util::Convolution.gaussian_kernel(3, 1.5)
# Returns 7-element array with Gaussian distribution
Source