img_moments: Image moments

View source: R/img_moments.R

img_momentsR Documentation

Image moments

Description

Compute raw, central, or central normalised moments of a greyscale image.

Usage

img_moments(x, order = 3)

img_moments_central(x, order = 3)

img_moments_normalised(x, order = 3)

Arguments

x

a greyscale image, of type imager::cimg()

order

maximal order of the moments to compute.

Details

Black pixels have a value of 0 and therefore do not contribute to the moments. To compute the moments based on the shape of the object only, compute a mask where the object is white (1) and the background black (0). To compute the moments of an object based on the grey scale intensities in the object, make the background black (i.e. invert it when the image is dark on white).

Value

A square matrix of dimension order+1. The usual notation of moments uses 0-based indexing (M[0,0] is the first moment) while R uses 1-based indexing (M[1,1] is the first moment). To facilitate the extraction of moments from those matrices, we provide the utility function get_moment() which does the 0-based indexing.

Examples

x <- img_read(system.file("extdata", "blob.jpg", package="morphr"))
img_show(x)
# extract the (largest) object from the image
X <- img_extract_largest(x)
img_show(X)
# convert it into a binary mask
X_binary <- X<1
img_show(X_binary)
# and into an inverted greyscale image
X_intensity <- 1-X
img_show(X_intensity)

# compute the moments
# of the binary image
m <- img_moments(X_binary, 2)
mu <- img_moments_central(X_binary, 2)
nu <- img_moments_normalised(X_binary, 2)
# of the intensity image
m_i <- img_moments(X_intensity, 2)
mu_i <- img_moments_central(X_intensity, 2)
nu_i <- img_moments_normalised(X_intensity, 2)

# from the (binary) moments, other properties can be derived
# http://raphael.candelier.fr/?blog=Image%20Moments
area <- gm(m, 0, 0)
centroid <- c(
  gm(m,1,0)/gm(m,0,0),
  gm(m,0,1)/gm(m,0,0)
)
centre_of_mass <- c(
  gm(m_i,1,0)/gm(m_i,0,0),
  gm(m_i,0,1)/gm(m_i,0,0)
)
angle <- 0.5 * atan(2 * gm(mu,1,1) / (gm(mu,2,0) - gm(mu,0,2))) + pi/2

# further normalise by area
mu20_n <- gm(mu,2,0)/gm(mu,0,0)
mu02_n <- gm(mu,0,2)/gm(mu,0,0)
mu11_n <- gm(mu,1,1)/gm(mu,0,0)
major_axis <- 0.5 * sqrt(8 * (mu20_n + mu02_n + sqrt(4* mu11_n^2 + (mu20_n - mu02_n)^2)))
minor_axis <- 0.5 * sqrt(8 * (mu20_n + mu02_n - sqrt(4* mu11_n^2 + (mu20_n - mu02_n)^2)))

# which allows to identify remarkable features of the image
image(0:18, 0:27, X_intensity[,,1,1], asp=1, ylim=c(27,0), col=grey(seq(1,0,length=255)))
points(centroid[1], centroid[2], col="red")
points(centre_of_mass[1], centre_of_mass[2], pch=3, col="red")
lines(ellipse(major_axis, minor_axis, angle, centroid[1], centroid[2]), col="blue")

# those parameters are derived (with refinement) in functions of this package

jiho/morphr documentation built on May 11, 2024, 9:32 p.m.