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

时间:2017-04-16 08:41:10

标签: r bitmap raster

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

请帮助我如何生成这样的基于像素的图像。我搜索并在R中找到了光栅和像素图包,但我是R的新手,不知道如何在我的情况下使用它们。任何帮助表示赞赏。感谢

1 个答案:

答案 0 :(得分:3)

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

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%缩放以查看像素):

enter image description here