我有一个非常长的字符数组。我想通过将每个字符编码为图像中的某种颜色来生成基于像素的图像(光栅图像)。例如,'A'为红色像素,'B'为紫色,...和'Z'为其他颜色。我正在使用R。从字符数组中生成基于像素的图像R
请帮我我如何生成这样的基于像素的图像。我在R中搜索并找到了光栅和像素图包,但我是R新手,不确定如何将它们用于我的情况。任何帮助表示赞赏。由于
我有一个非常长的字符数组。我想通过将每个字符编码为图像中的某种颜色来生成基于像素的图像(光栅图像)。例如,'A'为红色像素,'B'为紫色,...和'Z'为其他颜色。我正在使用R。从字符数组中生成基于像素的图像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%缩放看到像素):
感谢您使用快速解决方案@digEmAll。而不是png我们如何使用tiff,因为对于大字符数组,png会压缩图像。我需要没有压缩的位图图像。再次感谢。 – user7639992
@ user7639992嗯PNG使用无损压缩。或者你的意思是8位色彩信息不够? – lukeA
@lukeA在我的理解中,writePNG以png格式压缩图像。即使它的无损压缩与Tiff有什么不同? – user7639992
可以显示一些示例数据?如何为数字赋予字符? – din
@ din。示例数组是txt < - “ABACDAAFFEDDADFAFAEDDGJHGHJKL ...” – user7639992