【问题标题】:Save multiple PNG from RGB data frame in R从 R 中的 RGB 数据帧中保存多个 PNG
【发布时间】:2018-04-25 07:12:34
【问题描述】:

我有一个如下所示的数据框。我想从这个数据框中保存两个 png 文件,基于 sample 列命名,1.png2.png 使用各自列上的 rgb 值都是 2x3 像素。

据我所知,我需要为每个通道准备一个 3d 数组,然后为每个数组使用 writePNG 函数以保存为 PNG 文件,但是在为每个样本嵌套 rgb 值后我卡住了。

任何帮助将不胜感激(tidyversepurrr 方式的帮助将不胜感激;)

数据框:

|样品|像素|红色|绿色|蓝色| |------:|-----:|---:|-----:|----:| | 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))))) 

【问题讨论】:

  • 你能展示你用来嵌套 rgb 值的代码吗?
  • 你已经回答了,但我刚刚注意到评论并且仍然想回答。我使用以下命令嵌套值:test_df %&gt;% group_by(sample) %&gt;% nest()

标签: r png rgb tidyverse purrr


【解决方案1】:

例如:

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)

或者以更“循序渐进”的方式:

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))  

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多