从 R 中的 RGB 数据帧保存多个 PNG
Save multiple PNG from RGB data frame in R
我有一个如下所示的数据框。我想从这个数据框中保存两个 png 文件,根据 sample
列命名,1.png
和 2.png
都是 2x3 像素大,使用各自列上的 rgb 值。
据我所知,我需要为每个通道准备一个 3d 数组,然后对每个数组使用 writePNG
函数以保存为 PNG 文件,但是在为每个通道嵌套 rgb 值后我卡住了样本。
如有任何帮助,我们将不胜感激(以 tidyverse
和 purrr
方式提供的帮助将不胜感激;)
数据框:
| sample| pixel| red| green| blue|
|------:|-----:|---:|-----:|----:|
| 1| 1| 255| 0| 0|
| 1| 2| 255| 32| 0|
| 1| 3| 255| 64| 0|
| 1| 4| 255| 96| 0|
| 1| 5| 255| 128| 0|
| 1| 6| 255| 159| 0|
| 2| 1| 255| 191| 0|
| 2| 2| 255| 223| 0|
| 2| 3| 255| 255| 0|
| 2| 4| 255| 255| 42|
| 2| 5| 255| 255| 128|
| 2| 6| 255| 255| 213|
这是生成此数据框的代码:
test_df <- data_frame(sample=rep(1:2,each=6), pixel=rep(1:6,2)) %>%
bind_cols(as_data_frame(t(col2rgb(heat.colors(12)))))
例如:
library(purrr)
test_df %>%
split(.$sample) %>%
setNames(paste0(names(.), ".png")) %>%
map(~ array(c(.x$red, .x$green, .x$blue), c(2, 3, 3)) / 255) %>%
iwalk(png::writePNG)
或者更 "step-by-step" 的方式:
test_df %>%
split(.$sample) %>%
setNames(paste0(names(.), ".png")) %>%
map(`[`, 3:5) %>%
map(as.matrix) %>%
map(`/`, 255) %>%
map(array, c(2, 3, 3)) %>%
iwalk(png::writePNG)
或者没有 tidyverse:
z <- split(test_df, test_df$sample)
mapply(function(x, y) {
png::writePNG(array(as.matrix(x[3:5]), c(2, 3, 3)) / 255, paste0(y, ".png"))
}, z, names(z))
我有一个如下所示的数据框。我想从这个数据框中保存两个 png 文件,根据 sample
列命名,1.png
和 2.png
都是 2x3 像素大,使用各自列上的 rgb 值。
据我所知,我需要为每个通道准备一个 3d 数组,然后对每个数组使用 writePNG
函数以保存为 PNG 文件,但是在为每个通道嵌套 rgb 值后我卡住了样本。
如有任何帮助,我们将不胜感激(以 tidyverse
和 purrr
方式提供的帮助将不胜感激;)
数据框:
| sample| pixel| red| green| blue| |------:|-----:|---:|-----:|----:| | 1| 1| 255| 0| 0| | 1| 2| 255| 32| 0| | 1| 3| 255| 64| 0| | 1| 4| 255| 96| 0| | 1| 5| 255| 128| 0| | 1| 6| 255| 159| 0| | 2| 1| 255| 191| 0| | 2| 2| 255| 223| 0| | 2| 3| 255| 255| 0| | 2| 4| 255| 255| 42| | 2| 5| 255| 255| 128| | 2| 6| 255| 255| 213|
这是生成此数据框的代码:
test_df <- data_frame(sample=rep(1:2,each=6), pixel=rep(1:6,2)) %>%
bind_cols(as_data_frame(t(col2rgb(heat.colors(12)))))
例如:
library(purrr)
test_df %>%
split(.$sample) %>%
setNames(paste0(names(.), ".png")) %>%
map(~ array(c(.x$red, .x$green, .x$blue), c(2, 3, 3)) / 255) %>%
iwalk(png::writePNG)
或者更 "step-by-step" 的方式:
test_df %>%
split(.$sample) %>%
setNames(paste0(names(.), ".png")) %>%
map(`[`, 3:5) %>%
map(as.matrix) %>%
map(`/`, 255) %>%
map(array, c(2, 3, 3)) %>%
iwalk(png::writePNG)
或者没有 tidyverse:
z <- split(test_df, test_df$sample)
mapply(function(x, y) {
png::writePNG(array(as.matrix(x[3:5]), c(2, 3, 3)) / 255, paste0(y, ".png"))
}, z, names(z))