从字符数组在 R 中生成基于像素的图像

Generate pixel based image in R from character array

我有一个很长的字符数组。我想通过将每个字符编码为图像中的特定颜色来生成基于像素的图像(光栅图像)。例如,'A' 为红色像素,'B' 为紫色,... 'Z' 为其他颜色。我正在使用 R。

请帮助我如何生成这种基于像素的图像。我在 R 中搜索并找到了光栅和像素图包,但我是 R 的新手,不确定如何在我的案例中使用它们。任何帮助表示赞赏。谢谢

这是一个可能的解决方案:

library(png)
library(tiff)
library(abind)

# function which plots the image
createImage <- function(txt,charToColorMap,destinationFile,format=c('png','tiff'),debugPlot=FALSE){

  # helper function which finds all the divisors of a number
  divisors <- function(x){
    y <- seq_len(x)
    y[ x%%y == 0 ]
  }

  # split the string in charaters
  chars <- strsplit(txt,'')[[1]]

  # find the most "squared" rectangle that contains all the characters without padding
  d <- divisors(length(chars)) 
  y <- d[length(d) %/% 2]
  x <- length(chars) / y

  # create an array with 4 matrices (or planes) one for each RGBA channel
  RGBAmx <- col2rgb(charToColorMap,alpha=TRUE) / 255
  colorIndexes <- match(chars,names(charToColorMap))

  colorIndexesR <- matrix(RGBAmx['red',colorIndexes],nrow=y,ncol=x,byrow = TRUE)
  colorIndexesG <- matrix(RGBAmx['green',colorIndexes],nrow=y,ncol=x,byrow = TRUE)
  colorIndexesB <- matrix(RGBAmx['blue',colorIndexes],nrow=y,ncol=x,byrow = TRUE)
  colorIndexesA <- matrix(RGBAmx['alpha',colorIndexes],nrow=y,ncol=x,byrow = TRUE)

  planes <- abind(colorIndexesR,colorIndexesG,colorIndexesB,colorIndexesA,along=3)

  # write the PNG image
  if(format[1] == 'png'){
    writePNG(planes,destinationFile)
  }else if(format[1] == 'tiff'){
    writeTIFF(planes,destinationFile)
  }else{
    stop('usupported format')
  }

  # for debug purpose only we plot the image...
  if(debugPlot){
    mx <- matrix(colorIndexes,nrow=y,ncol=x,byrow = TRUE)
    image(z=t(mx[nrow(mx):1,]),col=charToColorMap)
  }

  invisible()
}

用法:

# arbitrary and incomplete LETTER -> COLOR map 
charToColorMap <- c(A='red',B='blue',C='green',D='black',E='yellow',F='orange')

txt <- "ABACDAAFFEDDADFAFAED"

createImage(txt,charToColorMap,destinationFile = "test.png",debugPlot=TRUE)

生成的 PNG 图像(缩放 800% 以查看像素):