Skip to content

Instantly share code, notes, and snippets.

@allenaven
Last active August 29, 2015 14:03
Show Gist options
  • Save allenaven/03907d67d8b14d36275a to your computer and use it in GitHub Desktop.
Save allenaven/03907d67d8b14d36275a to your computer and use it in GitHub Desktop.
An R port of CDP's Python script to sort RGB color values using principal components analysis
##### Recreate Cam Davidson Pilon's Python script to sort RGB color values
##### using Principal Components Analysis:
library(scatterplot3d)
## Make a function to plot a series of color values in rectangles:
plot_colors <- function(values) {
# Note, this function takes an matrix of dimensions (n, 3) of numbers
# between 0 and 1 for RGB values. Plotspace is between 0 and 100 for x and y
x <- 0:100
y <- 0:100
n_rects <- nrow(values)
# I'm going to plot the colors by making a bunch of rectangles in a blank plot, then
# coloring those rectangles in whatever order that is fed to the function.
# What width should each rect take? Simply, 100 divided by the number of rects!
width <- 100 / n_rects
starts <- seq(0, 100-width, length.out=n_rects) # Starting (lower left) x-coordinates for each rectangle
plot(x, y, type='n', xaxt='n', yaxt='n', xlab='', ylab='') # Make a blank plot with plotspace x and y
for (i in 1:n_rects) { # Loop through the input color values, plotting rectangles
polygon(x=c(starts[i], starts[i] + width, starts[i] + width, starts[i]),
y=c(25, 25, 75, 75), col=rgb(values[i,1], values[i,2], values[i,3]))
}
}
# Some random data:
n = 55
test_mat <- matrix(runif(n * 3, 0, 255), ncol=3, byrow=TRUE) / 255
# Plot the random RGB colors as a 3d plot
par(mfrow=c(1,1))
scatterplot3d(test_mat[,1], test_mat[,2], test_mat[,3], pch=16,
color=rgb(test_mat[,1], test_mat[,2], test_mat[,3]))
# Do a PCA
pca <- prcomp(test_mat, cor=TRUE)
# Use the values of the first principal component to sort the values of original data
# and store that in a new matrix (containing the sorted RGB values)
new_order <- order(pca$x[,1])
new_color_mat <- test_mat[new_order,]
## Plot orig and results:
par(mfrow=c(2,1), mgp=c(0,0,0), mar=c(2, 1, 1, 1))
plot_colors(test_mat)
plot_colors(new_color_mat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment