R grid arrange tiff microscopy RGB - r

I have a RGB tiff files (from cellProfiler) which I want to import to R, label and arrange - as part of a high throughput analysis. The closest I get is using:
library(tiff)
library(raster)
imageTiff <- tiff::readTIFF(imagePath[i])
rasterTiff <- raster::as.raster(imageTiff)
raster::plot(rasterTiff)
raster::plot plots the image nicely but I can't catch the output and use it with gridExtra or add labels.
In addition I tried rasterVis with levelPlot and multiple other ways importing the tiff and then converting them to grob or ggplots.
However, I can't get anything to work and would like to ask if R is even suited at all for that task?
Thank you very much for your help!

Okay, I think that is the most straight forward way and possible also the most obvious one.
I import JPEG or TIFF files with jpeg::readJPEG or tiff::readTIFF respectively. Both transform the images to a raster format which is compatible with rasterGrid() and following grid.arrange etc.
library(jpeg)
library(tiff)
library(grid)
imageJPEG <- grid::rasterGrob(jpeg::readJPEG("test.jpeg"))
imageTIFF <- grid::rasterGrob(tiff::readTIFF("test.tiff"))
grid.arrange(imageJPEG , imageJPEG , imageJPEG)
grid.arrange(imageTIFF , imageTIFF, imageTIFF)
For my purpose that is perfect since tasterGrob does not alter the raster matrix values. Labeling might be a bit tricky but overall it is a grid/grob problem from here on.

Related

creating multiple file types while plotting

I would like to produce a series of plots in both high-resolution and low-resolution versions, or stated differently using two different file types (.png and .eps). I'd like to know the best/least repetetive way to do this. I am using the gplot function in sna, and the plot has a custom legend outside the plot area. I wrote a function something like this:
library(sna)
plotfun <- function(net){
png("test.png",width=800)
p <- gplot(net)
par(xpd=T)
legend(max(p[,1])+1,max(p[,2]),legend=letters[1:10],title="custom legend")
dev.off()
seteps()
postscript(test.eps)
#repeat all the plotting commands, which are much longer in real life
dev.off()
}
#try it with some random data
plotfun(rgraph(10))
This is perfectly functional but seems inefficient and clumsy. The more general version of this question is: if for any reason I want to create a plot (including extra layers like my custom legend), store it as an object, and then plot it later, is there a way to do this? Incidentally, this question didn't seem sna specific to me at first, but in trying to reproduce the problem using a similar function with plot, I couldn't get the legend to appear correctly, so this solution to the outside-the-plot-area legend doesn't seem general.
I would recommend generate graphs only in Postscript/PDF from R and then generate bitmaps (e.g. PNG) from the Postscript/PDF using e.g. ImageMagick with -density parameter (http://www.imagemagick.org/script/command-line-options.php#density) set appropriately to get desired resolution. For example
convert -density 100 -quality 100 picture.pdf picture.png
assuming picture.pdf is 7in-by-7in (R defaults) will give you a 700x700 png picture.
With this approach you will not have to worry that the picture comes out formatted differently depending which R device (pdf() vs png()) is used.

convert jpg to greyscale csv using R

I have a folder of JPG images that I'm trying to classify for a kaggle competition. I have seen some code in Python that I think will accomplish this on the forums, but was wondering is it possible to do in R? I'm trying to convert this folder of many jpg images into csv files that have numbers showing the grayscale of each pixel, similar to the hand digit recognizer here http://www.kaggle.com/c/digit-recognizer/
So basically jpg -> .csv in R, showing numbers for the grayscale of each pixel to use for classification. I'd like to put a random forest or linear model on it.
There are some formulas for how to do this at this link. The raster package is one approach. THis basically converts the RGB bands to one black and white band (it makes it smaller in size, which I am guessing what you want.)
library(raster)
color.image <- brick("yourjpg.jpg")
# Luminosity method for converting to greyscale
# Find more here http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
color.values <- getValues(color.image)
bw.values <- color.values[,1]*0.21 + color.values[,1]*0.72 + color.values[,1]*0.07
I think the EBImage package can also help for this problem (not on CRAN, install it through source:
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
library(EBImage)
color.image <- readImage("yourjpg.jpg")
bw.image <- channel(color.image,"gray")
writeImage(bw.image,file="bw.png")

Arrange multiple (32) .png files in a grid

I've been pulling my hair out for the past week trying to figure out elementary R coding but can't seem to get anywhere (haven't used R since 2013 not that its a great excuse).
All I want is a 4x8 grid made up of 32 .png files (maps I've made), and I want to do it without loading one image file at a time (http://www.statmethods.net/advgraphs/layout.html).
So I think I can load the images within the folder writing (please correct me if my beliefs are bs)
img <- list.files(path='c:/a',patt='compo[0-32].*',full.names=T)
Then I was thinking maybe in the lines of par(mfrow=c()), layout, grid.arrange (writing png plots into a pdf file in R), grid.raster (How to join efficiently multiple rgl plots into one single plot?) - which I've read up on and experimented with accordingly not resulting in anything worthwhile..
The latter I employed only with the following outcome
It made me giggle.
I don't really think lattice is the way to go anyway.
Any help would be greatly appreciated!
Another approach is to read the PNG images with readPNG then use grid and gridExtra:
library(png)
library(grid)
library(gridExtra)
plot1 <- readPNG('plot1.png')
plot2 <- readPNG('plot2.png')
grid.arrange(rasterGrob(plot1),rasterGrob(plot2),ncol=1)
Alternative: If you want to save the plot using ggsave, instead of grid.arrange you can use
tmp <- arrangeGrob(rasterGrob(plot1),rasterGrob(plot2),ncol=1)
ggsave('filename.png',tmp,width=12,height=5)
Not sure what your concern is about loading all the image files -- how else could you read their data to create the new image?
ETA: to load the files, I'd just use png::readPNG . One way to collect the images would be(12 images selected here)
filenames<-dir(pattern='compo')
foo<-list()
for(j in 1:12) foo[[j]]<-readPNG(filenames[j]
If you're willing to load them and use the base plot tools, then layout is the command you want. E.g., for 12 images loaded
layout(matrix(1:12,nr=4,byr=T))
for (j in 1:12) plot(foo[[j]])

How to add a picture as datapoints in a map in R

I am using maps package in R to draw a simple geographic map and then put my data points in it.
My question is that whether there is any way in R to represent data points with a picture of interest, for example, the animal I am working on in my example.
This is just to give a better representation of the distribution of my data points relative to each other for my reader.
You can also use grid package. The grid.raster can be used to put some pictures.
Since maps is graphic base package , you need to gridBase to combine the grid/base graphics.
Here an example:
library(maps)
map('usa',boundary=T,fill=T,col='grey')
library(gridBase)
library(grid)
library(png)
vps <- baseViewports()
pushViewport(vps$figure,vps$plot)
camel <- readPNG("camel.png") ## some animal picture
grid.rect(gp = gpar(fill=NA))
x <- c(-110,-100,-70)
y <- c(30,40,40)
grid.raster(image=camel,x=x,y=y,width=5, ## it is vectorized
interpolate=FALSE,default.units = 'native')
upViewport(1)
PS: I am not sure that there are camels in USA...
rasterImage is one way, albeit somewhat laborious. Once you've got the images of interest formatted as raster objects, you can then place them at designated locations (and frame sizes) inside your plot region.
In addition to the rasterImage function mentioned by #CarlWitthoft there is also the combination of my.symbols and ms.image from the TeachingDemos package for adding images to a plot (base graphics). The rasterImage approach gives the most control, but my.symbols is more like the regular plotting functions in that you say plot the images centered at these coordinates (and set other options to specify size etc.)

R How to make smoother looking plots of oscillations

When plotting oscillations in R, e.g., using the package desolve,
df1 <-function(t,y,mu)( list(c(y[2],mu*y[1]^3-y[1]+0.005*cos(t))))
library (deSolve)
yini<-c(y1=0,y2=0)
df2 <-ode(y=yini,func=df1, times=0:520,parms=0.1667)
plot(df2,type="l",which="y1",ylab="Displacement",xlab="Time", main="")
I get raggedy plots such as:
instead of a smooth plot (not done in R) such as:
Does anyone know of a way to obtain a smoother plot in R instead of a raggedy one when displaying oscillations? Note that it is not just a matter of the difference in scale and I am not looking for a smoothing filter.
Thanks,
I generated your plot in R and exported it as PDF. I zoomed in on it and it's quite lovely. I can't see the problem you're talking about there. Therefore, there are some scaling issues or something with a raster format that are causing the issue. Perhaps you're pasting into Word and that's giving you a raster image that's bad. The plot that R is making, at a logical level, is great in spite of the one you posted. It's even better than the comparison plot you put up.
It's possible that you're generating the plot in a raster format and not setting a high enough resolution and size. Try tiff('filname', 1200, 1200, 300) for a good raster image of it. I did notice that when exporting to raster formats it was easy to make your plot into a fine mess with default png or jpg settings that would just smear things.
Maybe you really wanted to sample in your function at a higher resolution, something not done in the comparison plot. If that's the case then it's relatively easy. Change 0:520 to seq(0, 520, 0.1). That's an even nicer plot, as shown below (much better than shown as PDF, EPS, or SVG).

Resources