【问题标题】:Adding RGB channel to the 2D matrix [R]将 RGB 通道添加到 2D 矩阵 [R]
【发布时间】:2022-01-03 19:10:05
【问题描述】:

这是一个示例矩阵:

mymat <-matrix(runif(24*24), ncol=24) 

我可以使用 ggplot2 绘制这个矩阵,所以我可以获得值的颜色表示:

plot_mat <- function(mat){
  mat_df<- reshape2::melt(mat)
  plt <- mat_df %>% ggplot2::ggplot(aes(Var2, Var1)) + geom_raster(aes(fill = value)) +scale_fill_gradientn(colours = c('blue', 'green', 'yellow', 'red')) + theme_bw()
  return(plt)
}

plot_mat(mymat)

但我想将 RGB 通道添加到我的数据中,而不将它们转换为图像。我想为我的 mymat 添加另一个维度,因此 dim(mymat) 输出看起来是 24、24、3。不幸的是,我不知道该怎么做。

感谢您的帮助。

【问题讨论】:

    标签: r matrix multidimensional-array rgb


    【解决方案1】:

    您可以使用ggplot_build() 提取绘图中使用的颜色,它们以十六进制颜色存储,使用col2rgb() 将其转换为RGB 颜色,并使用array() 对其进行整形。如果结果数组没有正确排序,您可以通过将t() 转置到最终结果上来修复它,或者整个步骤中的输出之一就足够了。

    set.seed(123) # For reproducibility
    
    mymat <-matrix(runif(24*24), ncol=24) 
    
    plot_mat <- function(mat){
      mat_df<- reshape2::melt(mat)
      plt <- mat_df %>% ggplot2::ggplot(aes(Var2, Var1)) + geom_raster(aes(fill = value)) +scale_fill_gradientn(colours = c('blue', 'green', 'yellow', 'red')) + theme_bw()
    
      pg <- ggplot_build(plt) # Extract data from the plot
      RGBcolors <- col2rgb(pg$data[[1]]$fill, alpha = FALSE) # Transform the fill column to RGB 2D matrix
    
      RGB_array <- array(t(RGBcolors), c(24,24,3)); # create new array reshaping to 24x24x3
    # t() to transpose RGBcolors matrix to fit new third dimension
      RGB_array <- DescTools::Rev(RGB_array, margin=1) # RGB_array  array is flipped
      return(RGB_array)
    }
    

    【讨论】:

    • 谢谢。我注意到生成的 RGB 数组被翻转了,所以我沿第一个暗淡(行)使用了 DescTools::Rev() 函数,所以现在应该是这样了。
    • 好的,所以我编辑了帖子以防有人阅读。你用过RGB array &lt;-DescTools::Rev(RGB array ) 这样的吗?
    • 我这样做了:翻转
    • 我不知道 :( 我从来没有使用过 melt 功能。诀窍是利用 ggplot 定义颜色。也许你可以尝试从特定的调色板中获取颜色并使用定义颜色但使用数组的函数。但我不知道。
    • 我找到了一个非 ggplot 解决方案。如果有人对此感兴趣,我会将其作为答案发布在这里。
    【解决方案2】:

    经过一些试验和错误,我发现了以下非 ggplottish 解决方案:

    #values in matrix converted to hex colors
    colored_mymat <- paintmap::color_matrix(mymat, colors=rainbow(100))
    #the rest is the same as in Robertos answer
    RGB_mymat <- grDevices::col2rgb(colored_mymat, alpha = FALSE)
    ar <- array(t(RGB_mymat), c(24,24,3))
    
    #and this is for plotting purposes
    flipped <- DescTools::Rev(ar, margin=1)
    
    #rescaling values in matrix so the image would accept an input
    rescaled_mymat <- apply(flipped, MARGIN = 2, FUN = function(X) (X - min(X))/diff(range(X)))
    
    numbers_mymat <- unlist(apply(rescaled_mymat, 2, rev))
    par(mar=c(0, 0, 0, 0))
    image(numbers_mymat, useRaster=TRUE, axes=TRUE, col = grey(seq(0, 1, length = 256)))
    

    我希望有一天这会对某人有所帮助。

    【讨论】:

    • 很好的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    相关资源
    最近更新 更多