[R] fidelity of generated raster images (R and perl)

Roger Bivand Roger.Bivand at nhh.no
Thu Oct 14 17:56:41 CEST 2004

On Thu, 14 Oct 2004, Scott Harrison wrote:

> Hi:
> Goal: use R to turn a matrix of 1's and 0's
>           into a corresponding image (e.g. png)
>           of black and white pixels.

Maybe use the write.pnm() function in the pixmap package:

> try1 <- matrix(0, nrow=100, ncol=100)
> try1[upper.tri(try1)] <- 1
> write.pnm(pixmapGrey(try1), file="~/tmp/try1.pbm", type="pbm")

should do it (but as an ASCII file, bits are not so easy to do one by 
one). You need to watch which row order is used if the matrix and image 
row orders are to "look" the same. This is assuming that you don't 
actually need to use a graphics device, but have an R matrix object you 
need to represent. 

Another package you could explore is rimage, which looks relevant.


> Why R: Yes, I can do this more efficiently and precisely
>             with a perl module like Image::PBM.  Been there,
>             done that many times, etc.  (Just humor me.
>             I'm trying to do this with R for a number of reasons.)
> Problem: Difficult to get a perfect rasterization.  There can
>                 be appended or removed pixel columns or pixel rows
>                 depending on plot region dimensions.  I witness this
>                 with both R version 1.8.1 and R version 2.0.
> print($out "bitmap('/usr/local/mycrow/tmp/out.png', type = 'png256', 
> height = ".(int($height*68/64)/64).", width = 
> ".(int($width*69/64)/64).", res = 64, pointsize=0)\n");
> print($out 'par(mar=c(0,0,0,0))'."\n");
> my $width1 = $width-1;
> my $height1 = $height-1;
> print($out <<END);
> plot.new()
> plot.window(c(0,$width1),c(0,$height1))
> rect(m[,1], m[,2], m[,1], m[,2], col="black", border="black")
> There are alternatives to rect (plot with type="p", pch=".", etc)
> and I have also tried png() instead of bitmap().  (I do prefer
> bitmap so this can run without x11.)
> I am guessing that R's internal region calculations are
> vector based, which generally makes sense for most statistical
> plots.  However, I do have some ideas for R and the presentation
> of cellular automata results.
> Any tips out there?  (Is it just a matter of height=50px to
> overcome the inches default, etc?).....
> Regards,
> Scott
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Breiviksveien 40, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 93 93
e-mail: Roger.Bivand at nhh.no

More information about the R-help mailing list