What package for loading and saving images in R - r

I know this has been asked before but the existing answers seem out of date, as I can't install either Bio7 or rimage using install.packages and searching the cran repository for Bio7 gives a 404 link (am I missing something?).
So as of now, what are the right packages for loading / saving images in R so one can process the pixels from within R?
I don't need it to provide processing routines. As long as it can reliably turn a jpeg into a grid of pixel values and vice versa (and preferably do the same for a png) I can write processing code.

I think raster is what you need.
library(png)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
## convert it to a raster, interpolate =F to select only sample of pixels of img
img.r <- as.raster(img,interpolate=F)
Now you have a vector of color:
str(img.r)
'raster' chr [1:76, 1:100] "#00000000" "#0

Related

Using SRTM tif file in R

I'm trying to import a SRTM dataset into R. I've downloaded the data in a tif file however am having trouble reading it in "R".
Ive tried using the following code:
t = readTIFF("srtm_56_06/srtm_56_06.tif", as.is=TRUE)
load('srtm_56_06/srtm_56_06.tif')
read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif")
However I am still getting error messages:
load('srtm_56_06/srtm_56_06.tif')
# Error: bad restore file magic number (file may be corrupted) -- no data loaded
# In addition: Warning message:
# file ‘srtm_56_06.tif’ has magic number 'II*'
# Use of save versions prior to 2 is deprecated
library(raster)
t = readTIFF("srtm_56_06/srtm_56_06.tif", as.is=TRUE)
# Error: could not find function "readTIFF"
read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif") + min(read_file)
# Error: unexpected symbol in:
# "read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif")
# min"
Can anyone help me with the commands to import this data. I'm a novice at "R" and a little lost.
Just read it with raster, but note you depend on rgdal being installed as well to read a .tif.
library(raster)
library(rgdal)
r <- raster("srtm_56_06/srtm_56_06.tif")
If that works, try
plot(r)
r
If it's really a "TIFF" then that should be fine, if it's really a GeoTIFF then you'll have a sensible map as well. (If it's something else that GDAL can read you might get a good result anyway, remember the extension of a file is not a reliable indicator of its contents).
The SRTM clue suggests that this is a single band DEM file from the tiled global SRTM data set. If it's somehow a "multi-band image" then you could read that with brick and plot with plotRGB (but I really doubt that is the case here). Note that there is a native binary format for SRTM that raster/rgdal could read as well but either they distributed .tif as well or someone else converted it.
There are a number of misconceptions in your code:
load is for a particular file type created from R (not these .tifs)
readTIFF is not in package raster
read_file would be a sensible matrix, if you have rgdal installed (which raster must use to load a .tif), but why throw away the spatial metadata?

R: Error thrown while using RGDAL and RASTER packages

To whom this may concern:
Here is the source code:
GRA_D1<- raster(files[[1]])
//Sets up an empty output raster:
GRA_D1<- writeStart(GRA_D1,filename='GRA_D1.tif', format='GTiff', overwrite=TRUE)
//Write to the raster, for loop:
for(i in 1:dim(GRA_D1)[1]){
//Extract raster values at rows
d.Frame<- matrix(NA,ncol=2,nrow=dim(GRA_D1)[2])
d.Frame[,1]<- getValues(r1[[1]],i)
d.Frame[,2]<- getValues(r1[[2]],i)
w.Frame<- as.data.frame(d.Frame)
names(w.Frame)<- c("D1_pred_disAg","D1_pred_RK")
//Apply the predictive model:
m.pred<-predict(mod.1, w.Frame)
//Write the predictions to the empty TIFF raster
GRA_D1<-writeValues(GRA_D1,m.pred,i)
print(i)}
//Finish writing to the raster
GRA_D1<- writeStop(GRA_D1)
I am attempting to write output to an empty TIFF raster, but I keep receiving the following error message:
#Error in .local(.Object, ...) :
`general_file_path\GRA_D1.tif' does not exist in the file system,
and is not recognised as a supported dataset name.
I wonder if this is related to misusing functions in either the RGDAL or RASTER package.
Could someone please assist me?
Thanks in advance for your generosity.
Cheers,
AD
Super simple fix. Cannot believe that it is this simple and that it took me this long, but here is the answer:
"rgdal" and/or "GTiff" files don't like the use of underscores in their dataset names.
When running the code with "GRAD1.tif" (instead of "GRA_D1.tif"), all works well.
You really should not be doing any of this, I think, as you could do:
p <- predict(r1, mod.1, filename='GRA_D1.tif')
(and that filename works just fine)

how to read.jpeg in R 2.15

It seems very trivial but I can't read in jpeg, or any type of image into R 2.15. In R 2.10 I could do it using rimage library or ReadImage library - with read.jpeg for example - but there seems to be no way to do it in R 2.15 and later versions. Any thoughts on this?
library('ReadImages')
Error in library("ReadImages") : there is no package called ‘ReadImages’ >
install.packages('ReadImages') Installing package(s) into ‘C:/Program Files/R/R-2.15.1/library’ (as ‘lib’ is unspecified)
Warning in install.packages : package ‘ReadImages’ is not available (for R version 2.15.1)
As pointed out in comments, try the jpeg package.
install.packages("jpeg") ## if necessary
library(jpeg)
## get help
library(help = jpeg)
## get more help
?readJPEG
Example, from the help:
# read a sample file (R logo)
img <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))
Another option is rgdal, which can read from a massive bestiary of formats. Plotting and manipulation are handled differently.
install.packages("rgdal") ## if necessary
library(rgdal)
img <- readGDAL(file.path(R.home(), "doc", "html", "logo.jpg"))
There is also the readbitmap package on CRAN, it's always worth a basic search of the packages list for what you are looking for.
also:
## if not already installed
install.packages("jpeg")
library(jpeg)
?readJPEG()
img <- readJPEG("/Users/name/locationInFileDirectory/image.jpg", native = TRUE)
#this will display your image to test you read it correctly
if(exists("rasterImage")){
plot(1:2, type='n')
rasterImage(img,1,1,2,2)
}

How to use R for basic image processing

I am currently working on an application of Principal Component Analysis to visual data in R.
In Matlab, one can invoke commands such as "im2double" and "mat2gray" to convert a bitmap into a numerical matrix and back again to an image.
I was wondering whether this can be achieved in R, maybe via additional packages.
I've used the EBImage package (vignette here) available on bioconductor to work with and manipulate images:
# installing package if needed
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
library(EBImage)
f = readImage(system.file("images", "lena-color.png", package="EBImage"))
str(f)
#Formal class 'Image' [package "EBImage"] with 2 slots
# ..# .Data : num [1:512, 1:512, 1:3] 0.886 0.886 0.875 0.875 0.886 ...
# ..# colormode: int 2
I was curious enough to try this out; clearly a package is a better solution, but if you really want to stick to base R, this will load a png (albeit upside down and backwards; that's probably fixable). It assumes the presence of the netpbm tools, so probably won't work out of the box on Windows systems.
readPng <- function(pngFile) {
contents <- system(paste('pngtopnm',pngFile,'| pnmtoplainpnm'),intern=TRUE)
imgDims <- strsplit(contents[2], ' ')
width <- as.numeric(imgDims[[1]][1])
height <- as.numeric(imgDims[[1]][2])
rawimg <- scan(textConnection(contents),skip=3)
return(list(
x=1:width,
y=1:height,
z=matrix(rawimg,width),
width=width,
height=height))
}
You can run image(img) on the list returned from this function directly, or access the per-pixel values using img$z.
Two methods to install the package.
install through command line if you have no Editor like RStudio
install the command line by entering into R interpreter using R command in bash.
Go to prompt where you can execute R commands. here these the basic image processing command.
execute this command to install the Bio conductor backage biocLite, which will help to install the EBIMage package( This package is used widely for image processing)
source("http://bioconductor.org/biocLite.R")
install the EMImage package to use image processing commands.
biocLite("EBImage")
Load the EBIMage package to use the image processing
library("EBImage")
# Reading image from computer
img=readImage(files="~/Desktop/Prog/R/tinago.JPG")
display(img)
img1=img+ 0.2 # increase brightness
img2=img- 0.2 # decrease brightness
display(img1) # Display images in browser or graphical window
display(img2) # Display images in browser or graphical window
img3= img * 0.5 # decrease contrast
img4=img * 2 # increase contrast
display(img3); display(img4) # show result images
img5=img^2 # increase Gamma correction
img6=img^0.7 # decrease Gamma correction
display(img5); display(img6) # Display result images
Note : readImage to read the image. Display is used to view the image in Graphical Window.
The relatively new package tiff will read and write TIF images quite nicely.
All the same, for anything other than relatively simple image manipulation, I'd recommend using ImageJ or SAOImage9 from the Harvard-Smithsonian group: http://www.cfa.harvard.edu/resources/software.html .
I've written tools in R to do pixel merging, pixel splitting, Sobel & Hough transforms, decolorization, etc., with great success. Ultimately the choice of application depends on the size of your images and the type of processing you need to do.

available CRAN vignettes

There's the available.packages() function to list all packages available on CRAN. Is there a similar function to find all available vignettes? If not how would I get a list of all vignettes and the packages they're associated with?
As a corner case to keep in mind the data.table package has 3 vignettes associated with it.
EDIT: Per Andrie's response I realize I wasn't clear. I know about the vignette function for finding all the available local vignettes, I'm after a way to get all the vignettes of all packages on CRAN.
I seem to recall looking at this in response to some SO question (can't find it now) and deciding that since the information isn't included in the output of available.packages(), nor in the result of applying readRDS to #CRAN/web/packages/packages.rds (a trick from Jeroen Ooms), I couldn't think of a non-scraping way to do it ...
Here's my scraper, applied to the first 100 packages (leading to 44 vignettes)
pkgs <- unname(available.packages()[, 1])[1:100]
vindex_urls <- paste0(getOption("repos"),"/web/packages/", pkgs,
"/vignettes/index.rds", sep = "")
getf <- function(x) {
## I think there should be a way to do this directly
## with readRDS(url(...)) but I can't get it to work
suppressWarnings(
download.file(x,"tmp.rds",quiet=TRUE))
readRDS("tmp.rds")
}
library(plyr)
vv <- ldply(vindex_urls,
.progress="text",
function(x) {
if (inherits(z <- try(getf(x),silent=TRUE),
"try-error")) NULL else z
})
tmpf <- function(x,n) { if (is.null(x)) NULL else
data.frame(pkg=n,x) }
vframe <- do.call(rbind,mapply(tmpf,vv,pkgs))
rownames(vframe) <- NULL
head(vframe[,c("pkg","Title")])
There may be ways to clean this up/make it more compact, but it seems to work OK. Your scrape once/update occasionally strategy seems reasonable. Or if you wanted you could scrape daily (or weekly or whatever seems reasonable) and save/post the results somewhere publicly accessible, then include a function with that URL hard-coded in the package ... or even create a nicely formatted HTML table, with links, that the whole world could use (and then add Viagra ads to the page, and $$PROFIT$$ ...)
edit: wrapped both the download and the readRDS in a function, so I can wrap the whole thing in try
The functions vignette() and browseVignettes() list all vignettes of packages installed on your machine.
vignette(package="data.table")
Vignettes in package ‘data.table’:
datatable-faq Frequently asked questions (source, pdf)
datatable-intro Quick introduction (source, pdf)
datatable-timings Timings of common tasks (source, pdf)
browseVignettes() is especially helpful since it creates a web page with hyperlinks:
browseVignettes(package="data.table")
Vignettes found by browseVignettes(package = "data.table")
Vignettes in package data.table
Frequently asked questions - PDF R LaTeX/noweb
Quick introduction - PDF R LaTeX/noweb
Timings of common tasks - PDF R LaTeX/noweb

Resources