从字符数组生成R中基于像素的图像 [英] Generate pixel based image in R from character array

查看:82
本文介绍了从字符数组生成R中基于像素的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very long character array. I want to generate pixel based image (raster image) by encoding each character to certain color in image. For example, 'A' as red pixel, 'B' as purple, ... and 'Z' by some other color. I am using R for it.

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

Please help me how can i generate such pixel based image. I search and found raster and pixmap packages in R but i am new to R and not sure how to use them for my case. Any help is appreciated. Thanks

推荐答案

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

Here's a possible solution :

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

Resulting PNG image (800% zoom to see the pixels) :

这篇关于从字符数组生成R中基于像素的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆