rgb2sph <- function(rgb, nbits)
{
## Purpose: Convert RGB Color Value to Spherical Coordinates
## Arguments:
## rgb: a (N X 3) matrix of RGB values (each row is a triplet of R, G, B).
## Assume each integer value range from 0 to (2^nbits - 1).
## nbits: number of bits used to code each of R, G, B channel.
## Return: a (N X 3) matrix of Shperical Coordinates (each row is a triplet of M, Theta, Phi), which are scaled to be within (0, 1).
## Author: Feiming Chen, Date: 5 Apr 2017, 10:21
## ________________________________________________
max.scale <- 2^nbits
M.scale <- sqrt(3 * max.scale^2)
angle.scale <- pi / 2
t(apply(rgb + 1, 1, function(x) {
M <- sqrt(sum(x^2)) # Color Intensity/Luminosity (0-1)
Theta <- atan(x[2] / x[1]) # Azimuthal Angle
Phi <- acos(x[3] / M) # Zenith Angle
c(M / M.scale, Theta / angle.scale, Phi / angle.scale)
}))
}
if (F) { # Unit Test
rgb <- matrix(c(0, 0, 0, 4095,4095,4095, 3527, 3513, 3504, 2470, 3034,3218), ncol=3, byrow = T)
rgb2sph(rgb, nbits = 12)
## [,1] [,2] [,3]
## [1,] 0.00024414 0.50000 0.60817
## [2,] 1.00000000 0.50000 0.60817
## [3,] 0.85832017 0.49873 0.60954
## [4,] 0.71428036 0.56498 0.56181
}
No comments:
Post a Comment