Skip to contents

Calculates the squared distance between each pixel and its assigned color center.

Usage

colorResiduals(
  pixel_matrix,
  pixel_assignments,
  centers,
  color_space = "Lab",
  metric = "euclidean",
  ref_white = "D65"
)

Arguments

pixel_matrix

2D matrix of pixels to classify (rows = pixels, columns = channels).

pixel_assignments

A vector of color center assignments for each pixel. Must match the order of pixel_matrix.

centers

A matrix of color centers, with rows as centers and columns as color channels. Rows are assumed to match the index values of pixel_assignments, e.g. a pixel assigned 1 in the assignment vector is assigned to the color in the first row of centers.

color_space

Color space in which to calculate distances. One of "sRGB", "Lab", "Luv", or "XYZ". Passed to grDevices::convertColor().

metric

Distance metric to be used for calculating pairwise pixel distances in the given color space; passed to stats::dist().

ref_white

Passed to grDevices::convertColor() if color_space = "Lab. Reference white for CIE Lab space.

Value

A list with the following attributes:

  1. sq_residuals: The squared residual for every pixel in pixel_matrix.

  2. tot_residuals: The sum of all squared residuals.

  3. avg_residual: The average squared residual.

  4. residuals_by_center: A list of squared residuals for every color center.

  5. avg_by_center: The average squared residual for every color center.

Examples

# RGB extremes (white, black, red, green, blue, yellow, magenta, cyan)
ctrs <- matrix(c(1, 1, 1,
                 0, 0, 0,
                 1, 0, 0,
                 0, 1, 0,
                 0, 0, 1,
                 1, 1, 0,
                 1, 0, 1,
                 0, 1, 1), byrow = TRUE, ncol = 3)

# plot it
recolorize::plotColorPalette(ctrs)


# create a pixel matrix of random colors
pixel_matrix <- matrix(runif(3000), ncol = 3)

# assign pixels
# see `assignPixels` function for details
reassigned <- assignPixels(ctrs, pixel_matrix, adjust_centers = TRUE)

# find residuals from original color centers
color_residuals <- colorResiduals(pixel_matrix = pixel_matrix,
                                  pixel_assignments = reassigned$pixel_assignments,
                                  centers = ctrs)

# compare to residuals from adjusted color centers
color_residuals_adjust <- colorResiduals(pixel_matrix = pixel_matrix,
                                  pixel_assignments = reassigned$pixel_assignments,
                                  centers = reassigned$centers)
# to reset graphical parameters:
current_par <- graphics::par(no.readonly = TRUE)

layout(matrix(1:2, nrow = 2))
hist(color_residuals$sq_residuals,
 breaks = 30, border = NA, col = "tomato",
 xlim = c(0, 1), xlab = "Squared residual",
 main = "Original centers")

hist(color_residuals_adjust$sq_residuals,
breaks = 30, border = NA, col = "cornflowerblue",
xlim = c(0, 1), xlab = "Squared residual",
main = "Adjusted centers")


graphics::par(current_par)