Learn R Programming

⚠️There's a newer version (0.45.8) of this package.Take me there.

Imager is an image/video processing package for R, based on CImg, a C++ library by David Tschumperlé. CImg provides an easy-to-use and consistent API for image processing, which imager largely replicates. CImg supports images in up to four dimensions, which makes it suitable for applications like video processing/hyperspectral imaging/MRI.

Installing the package

Imager is on CRAN, so

install.packages("imager")

should do the trick. You may also want to install ImageMagick and ffmpeg, see "External Dependencies" below.

The version of CRAN will often lag the one on github. If you'd like to install the latest version, you'll have to build the package from source.

Install the devtools package if you haven't already. Run:

devtools::install_github("dahtah/imager")

If that doesn't work then you're probably missing a build environment or a library, see below.

OS X

Install XQuartz if you haven't already (it's required for the interactive functions). You'll need Xcode (OS X's development environment) to compile source packages. The FFTW library is needed, and the easiest way to install it is via Homebrew. Install Homebrew, then run: brew install fftw

Optionally, install libtiff for better support of TIFF files.

Windows

Building R packages on Windows is a bit of a pain so you're probably better off with the binary package (which may not be up-to-date). If you need the latest version of imager, you'll have to:

  • Install Rtools
  • Install additional libraries for Rtools. You want the package that's called "local tree". Put those libraries somewhere gcc can find them.

Linux

To build under Linux make sure you have the headers for libX11 and libfftw3 (optionally, libtiff as well). On my Ubuntu system this seems to be enough:

sudo apt-get install libfftw3-dev libX11-dev libtiff-dev

External dependencies

OS X users need XQuartz. On its own imager supports JPEG, PNG, TIFF and BMP formats. If you need support for other file types install ImageMagick. To load and save videos you'll need ffmpeg, no file formats are supported natively.

Getting started

Here's a small demo that actually demonstrates an interesting property of colour perception:

library(imager)
library(purrr)
parrots <- load.example("parrots")
plot(parrots)
#Define a function that converts to YUV, blurs a specific channel, and converts back
bchan <- function(im,ind,sigma=5) { 
	im <- RGBtoYUV(im)
	channel(im,ind) <- isoblur(channel(im,ind),sigma); 
	YUVtoRGB(im)
}
#Run the function on all three channels and collect the results as a list
blurred <- map_il(1:3,~ bchan(parrots,.))
names(blurred) <- c("Luminance blur (Y)","Chrominance blur (U)","Chrominance blur (V)")
plot(blurred)

We're much more sensitive to luminance edges than we are to colour edges.

Documentation is available here. To get a list of all package functions, run: ls(pos = "package:imager")

Important warning on memory usage

All images are stored as standard R numeric vectors (i.e., double-precision), meaning that they take up a lot of memory. It's easy to underestimate how much storage you need for videos, because they take up so little space in a compressed format. Before you can work on it in R a video has to be fully decompressed and stored as double-precision floats. To get a sense of the size, consider a low-resolution (400x300), colour video lasting 120 sec. The video might take up a few MBs when compressed. To store it in memory, you'll need: (400x300) x (25x120) x 3 values, corresponding to (space)x(time)x(colour). In addition, each value costs 8 bytes of storage, for a grand total of 8GB of memory.

For out-of-memory processing of videos, see the experimental package imagerstreams.

Current status

Imager is fully functional but still young, so the API might change. Open an issue on Github or email me if you've found a bug or would like to suggest a feature.

Contributing to imager

If you want to add features or fix a bug, just fork this repository and send me a pull request (they're welcome). Consider contributing documentation too: imager has got quite large over time, and it's in need of more how-to's and tutorials!

Contributors

The package's author is Simon Barthelmé (Gipsa-lab, CNRS). The following people have gracefully contributed code, bug fixes or testing:

  • Stefan Roediger
  • Aaron Robotham
  • Martin Roth
  • Jan Wijffels
  • Hong Ooi

Let me know if you're missing from the list!

Test pictures

Imager ships with four test pictures and a video. Two (parrots and boats) come from the Kodak set. Another is a sketch of birds by Leonardo, from Wikimedia. Also from Wikimedia: the Hubble Deep field. The test video comes from xiph.org's collection.

Copy Link

Version

Install

install.packages('imager')

Monthly Downloads

8,961

Version

0.41.2

License

LGPL

Issues

Pull Requests

Stars

Forks

Maintainer

Simon Barthelme

Last Published

January 23rd, 2019

Functions in imager (0.41.2)

FFT

Compute the Discrete Fourier Transform of an image
autocrop

Autocrop image region
add.colour

Add colour channels to a grayscale image or pixel set
as.cimg

Convert to cimg object
display

Display object using CImg library
as.data.frame.pixset

Methods to convert pixsets to various objects
as.igraph.cimg

Form a graph from an image
capture.plot

Capture the current R plot device as a cimg image
display.cimg

Display image using CImg library
center.stencil

Center stencil at a location
cimg.extract

Various shortcuts for extracting colour channels, frames, etc
cimg.use.openmp

Control CImg's parallelisation
draw_circle

Draw circle on image
bbox

Compute the bounding box of a pixset
draw_rect

Draw rectangle on image
blur_anisotropic

Blur image anisotropically, in an edge-preserving way.
boxblur

Blur image with a box filter (square window)
get.stencil

Return pixel values in a neighbourhood defined by a stencil
boxblur_xy

Blur image with a box filter.
cimg2im

Convert cimg to spatstat im object
get_gradient

Compute image gradient.
circles

Add circles to plot
coord.index

Coordinates from pixel index
correlate

Correlation/convolution of image by filter
grow

Grow/shrink a pixel set
gsdim

Grayscale dimensions of image
idply

Split an image along axis, apply function, return a data.frame
iiply

Split an image, apply function, recombine the results as an image
hough_circle

Circle detection using Hough transform
hough_line

Hough transform for lines
%inr%

Check that value is in a range
grayscale

Convert an RGB image to grayscale
RGBtoHSL

Colour space conversions in imager
imager.combine

Combining images
imhessian

Compute image hessian.
imlap

Compute image Laplacian
iminfo

Return information on image file
imlist

Image list
interp

Interpolate image values
is.cimg

Checks that an object is a cimg object
is.imlist

Check that an object is an imlist object
imager.replace

Replace part of an image with another
load.example

Load example image
imager.subset

Array subset operator for cimg objects
load.image

Load image from file or URL
imappend

Combine a list of images into a single image
is.pixset

Check that an object is a pixset object
load.video

Load a video using ffmpeg
play

Play a video
imchange

Modify parts of an image
magick

Convert a magick image to a cimg image or image list
plot.cimg

Display an image using base graphics
periodic.part

Compute the periodic part of an image, using the periodic/smooth decomposition of Moisan (2011)
imrotate

Rotate an image along the XY plane.
imrep

Replicate images
as.cimg.array

Turn an numeric array into a cimg object
permute_axes

Permute image axes
rm.alpha

Remove alpha channel and store as attribute
save.image

Save image
as.cimg.data.frame

Create an image from a data.frame
isoblur

Blur image isotropically.
split_connected

Split pixset into connected components
medianblur

Blur image with the median filter. In a window of size n x n centered at pixel (x,y), compute median pixel value over the window. Optionally, ignore values that are too far from the value at current pixel.
label

Label connected components.
mirror

Mirror image content along specified axis
as.igraph.pixset

Form an adjacency graph from a pixset
patch_summary_cimg

Extract a numerical summary from image patches, using CImg's mini-language Experimental feature.
squeeze

Remove empty dimensions from an array
patchstat

Return image patch summary
px.na

A pixset for NA values
rotate_xy

Rotate image by an arbitrary angle, around a center point.
as.imlist.list

Convert various objects to image lists
renorm

Renormalise image
stencil.cross

A cross-shaped stencil
threshold

Threshold grayscale image
boats

Photograph of sailing boats from Kodak set
boundary

Find the boundary of a shape in a pixel set
cimg

Create a cimg object
vanvliet

Young-Van Vliet recursive Gaussian filter.
cimg.dimensions

Image dimensions
distance_transform

Compute Euclidean distance function to a specified value.
display.list

Display image list using CImg library
frames

Split a video into separate frames
get.locations

Return coordinates of subset of pixels
as.data.frame.cimg

Convert a pixel image to a data.frame
as.data.frame.imlist

Convert image list to data.frame
bucketfill

Bucket fill
cannyEdges

Canny edge detector
get_hessian

Return image hessian.
grab

Select image regions interactively
ilply

Split an image along axis, apply function, return a list
common_pixsets

Various useful pixsets
im2cimg

Convert an image in spatstat format to an image in cimg format
contours

Return contours of image/pixset
imfill

Create an image of custom size by filling in repeated values
crop.borders

Crop the outer margins of an image
imgradient

Compute image gradient
deriche

Apply recursive Deriche filter.
imnoise

Generate (Gaussian) white-noise image
implot

Plot objects on image using base graphics
draw_text

Draw text on an image
erode

Erode/dilate image by a structuring element.
liply

Apply function to each element of a list, then combine the result as an image by appending along specified axis
as.cimg.function

Create an image by sampling a function
haar

Compute Haar multiscale wavelet transform.
load.dir

Load all images in a directory
highlight

Highlight pixel set on image
as.cimg.raster

Convert a raster object to a cimg object
as.pixset

Methods to convert various objects to pixsets
imcoord

Coordinates as images
as.raster.cimg

Convert a cimg object to a raster object for plotting
channels

Split a colour image into a list of separate channels
imdirac

Generates a "dirac" image, i.e. with all values set to 0 except one.
imsharpen

Sharpen image.
ci

Concatenation for image lists
nfline

Plot a line, Hesse normal form parameterisation
pad

Pad image with n pixels along specified axis
imshift

Shift image content.
clean

Clean up and fill in pixel sets (morphological opening and closing)
imwarp

Image warping
plot.imlist

Plot an image list
index.coord

Linear index in internal vector from pixel coordinates
make.video

Make/save a video using ffmpeg
colorise

Fill in a colour in an area given by a pixset
diffusion_tensors

Compute field of diffusion tensors for edge-preserving smoothing.
map_il

Type-stable map for use with the purrr package
displacement

Estimate displacement field between two images.
px.flood

Select a region of homogeneous colour
where

Return locations in pixel set
extract_patches

Extract image patches and return a list
flatten.alpha

Flatten alpha channel
pixel.grid

Return the pixel grid for an image
im_split

Split an image along a certain axis (producing a list)
pixset

Pixel sets (pixsets)
imager

imager: an R library for image processing, based on CImg
imdraw

Draw image on another image
resize

Resize image
imeval

Evaluation in an image context
resize_doubleXY

Resize image uniformly
warp

Warp image
watershed

Compute watershed transform.
imsplit

Split an image along a certain axis (producing a list)
imsub

Select part of an image
inpaint

Fill-in NA values in an image
interact

Build simple interactive interfaces using imager
at

Return or set pixel value at coordinates
RasterPackage

Convert a RasterLayer/RasterBrick to a cimg image/image list