imager (version 0.41.2)

as.igraph.cimg: Form a graph from an image

Description

In this graph representation, every pixel is a vertex connected to its neighbours. The image values along edges are stored as graph attributes (see examples).

Usage

# S3 method for cimg
as.igraph(x, mask = px.all(channel(im, 1)))

Arguments

x

an image (must be 2D, 3D not implemented yet)

mask

optional: a pixset. if provided, pixels are only connected if they are both in the pixset.

...

ignored

Value

a graph (igraph format) with attributes value.from, value.to and dist

See Also

as.igraph.pixset

Examples

Run this code
# NOT RUN {
library(igraph)
im <- imfill(5,5)
G <- as.igraph(im)
plot(G)
#Shortest-path distance from pixel 1 to all other pixels
d <- igraph::distances(G,1) %>% as.vector
as.cimg(d,dim=gsdim(im)) %>% plot(interpolate=FALSE)
#Notice that moving along the diagonal has the same cost
#as moving along the cardinal directions, whereas the Euclidean distance
#is actually sqrt(2) and not 1. 
#Modify weight attribute, to change the way distance is computed
igraph::E(G)$weight <- G$dist
d2 <- igraph::distances(G,1) %>% as.vector
as.cimg(d2,dim=gsdim(im)) %>% plot(interpolate=FALSE)
#More interesting example
im <- grayscale(boats)
G <- as.igraph(im)
#value.from holds the value of the source pixel, value.to the sink's
#set w_ij = (|v_i - v_j|)/d_ij
igraph::E(G)$weight <- (abs(G$value.from - G$value.to))/G$dist
igraph::distances(G,5000) %>% as.vector %>%
    as.cimg(dim=gsdim(im)) %>% plot
# }

Run the code above in your browser using DataCamp Workspace