Last active
August 23, 2023 15:20
-
-
Save kadyb/8ef273b5c31bf683583dfdc91770b6fc to your computer and use it in GitHub Desktop.
Animation example of multithreaded raster processing using {stars} in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library("sf") | |
library("stars") | |
library("gganimate") | |
library("ggnewscale") | |
tif = system.file("tif/L7_ETMs.tif", package = "stars") | |
bands = paste0("B", c(1:5, 7)) | |
r = read_stars(tif) | |
r = st_set_dimensions(r, 3, values = bands, names = "band") | |
r_bbox = st_as_sfc(st_bbox(r)) | |
blocks = st_make_grid(r, cellsize = c(2048, 2048)) | |
blocks = st_intersection(blocks, r_bbox) | |
blocks = st_as_sf(blocks) | |
blocks$cpu = rep(1:5, times = 5) | |
blocks$iter = rep(1:5, each = 5) | |
# blocks$iter = sample(1:7, 49, replace = TRUE) # random order | |
r_df = as.data.frame(split(r)) | |
r_df$rgb = rgb(r_df$B3, r_df$B2, r_df$B1, maxColorValue = 255) | |
p = ggplot() + | |
geom_raster(data = r_df, aes(x = x, y = y, fill = rgb)) + | |
labs(title = "Parallel processing") + | |
scale_fill_identity() + | |
new_scale_fill() + | |
geom_sf(data = blocks, aes(fill = as.factor(cpu)), alpha = 0.3) + | |
scale_fill_brewer(palette = "Set1", name = "CPU") + | |
transition_manual(iter, cumulative = TRUE) + | |
theme_void() + | |
theme( | |
plot.title = element_text(size = 26, face = "bold", hjust = 0.5) | |
) | |
animate(p) | |
anim_save("gif.gif", p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment