【问题标题】:Generate pixel based image in R from character array从字符数组在 R 中生成基于像素的图像
【发布时间】:2017-04-16 21:07:50
【问题描述】:

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

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

【问题讨论】:

  • 你能展示一些示例数据吗?给字符分配数值怎么样?
  • @din。示例数组是 txt

标签: r bitmap raster


【解决方案1】:

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

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

【讨论】:

  • 感谢@digEmAll 的快速解决方案。我们如何使用 tiff 而不是 png,因为对于大型字符数组,png 会压缩图像。我需要没有压缩的位图图像。再次感谢。
  • @user7639992 嗯,PNG 使用无损压缩。或者你的意思是8位颜色信息还不够?
  • @lukeA 据我了解,writePNG 以 png 格式压缩图像。即使它是无损压缩,它与 Tiff 有何不同?
  • @user7639992 是的,它以 png 格式压缩图像。但它不像 jpg 那样有损压缩。压缩会保留所有信息 - 如果您有超过 256 种颜色,则 8 位 PNG 的颜色除外。但这里似乎并非如此。
  • @lukeA 好的。很好的解释。最后一个问题是 tiff 只是不做任何压缩,对吧?如果 tiff 使用 8 位而不是与 png 相同?谢谢
猜你喜欢
  • 1970-01-01
  • 2018-04-14
  • 2018-06-25
  • 2020-02-08
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多