Closed zeehio closed 5 months ago
Somewhat related: if you are interested in converting a matrix with intensity values to a native raster given a certain colour palette, I noticed that
# function to convert matrix to nativeRaster given a colour palette col
mat2natrast = function(mat, col) {
idx = findInterval(mat, seq(0, 1, length.out = length(col)))
colors = col[idx]
natrast = nara::raster_to_nr(t(matrix(colors, ncol = ncol(mat), nrow = nrow(mat), byrow = TRUE)))
return(natrast)
}
would be more than twice as fast than
# alt function to convert matrix to nativeRaster given a colour palette col
# this was somehow slower than function above
mat2natrast2 = function(mat, col) {
idx = findInterval(mat, seq(0, 1, length.out = length(col)))
colints = farver::encode_native(col[idx]) # hex colours as integers representing RGBA
# colints = nara::colour_to_integer(col[idx]) # this would be 2x slower still
natrast = t(matrix(colints, ncol = ncol(mat), nrow = nrow(mat), byrow = TRUE))
class(natrast) = "nativeRaster"
return(natrast)
}
Might be worth perhaps of including a computationally efficient function to convert a given numeric matrix to nativeRaster
, given a certain colour palette, as this will be a common usage case of nara & potentially display it... This could be the basis for a fast version of the image()
function, which could also be nice...
colour_to_integer()
is now faster than it was, and on par with {farver}
the introduction matrix_to_nr()
now addresses @tomwenseleers issue.
Thanks for letting me discover nativeRaster objects through your nara package. They are blazingly fast!
Just in case you are looking for further optimizations, my benchmark on
nara::colour_to_integer()
with both a 512 long vector and a 10 million vector shows thatfarver::encode_native()
is close to twice as fast.with a 10 million long vector:
With a 512 long vector, similar behaviour:
Created on 2022-09-06 by the reprex package (v2.0.1)