Problem:
I want to convert a Hue, Saturation, Value (HSV) raster to the RGB color space. I have already successfully converted from RGB to HSV, but I'm having trouble with the reverse.
I'm using the following code, where stack
is a raster stack object.
final_rgb <- overlay(brick(stack), fun=hsv2rgb)
I get the error:
"Error in .overlayList(x, fun = fun, filename = filename, forcefun = forcefun, :
cannot use this formula, probably because it is not vectorized"
Solutions I've tried so far:
(1) The solution from this post, that is, a custom function (hsv2rbgna()
) that drops potential NA values. I still get the same behavior.
(2) I've tried using a hsv2rgb()
function from the package ColorMod. I get the error shown.
rgb <- colormod::hsv2rgb(stack)
"Error in dimnames(x) <- list(n) : 'dimnames' applied to non-array"
(3) And a hsv2rgb()
function from the package ColorPalette:
rgb <- ColorPalette::hsv2rgb(stack[[1]], stack[[2]], stack[[3]])
"Error in rgbVector + m : non-numeric argument to binary operator"
(4) Convert raster to a matrix. I previously removed NA values from my raster, so I'm not sure what the non-finite values mentioned in the error message could be.
stack_matrix <- raster::as.matrix(stack)
final_rgb <- hsv2rgb(stack_matrix )
"Error in hsv(h = x["h"], s = x["s"], v = x["v"]) : inputs must be finite"
(5) The documentation for hsv2rgb() says that the input matrix should contain (h, s, v)
rows, rather than columns, so I tried transposing the matrix, with the function t()
. I get the same error as (4).