I am trying to measure distances between objects of interests (in this example year rings in trees) using R. My earlier attempt was so complicated that I have difficulties reproducing the solution for a similar type of a problem using different kinds of figures. I think that there must be an easier way of doing the measurements. As nice as ImageJ might be for picture analysis, I find it too clumsy to use for repetitive work. Why not just to mark the objects of interest with different colors using an image handling program and trying to extract the information about their position? (this is not the question). Here is an example:
(Save the picture as tree.jpg). In order to measure the distance from the beginning (blue dot) to the red and green dots (representing two different arbitrary measurements), I need to extract the centroid and color characteristic (i.e. whether the dot is green, blue or red) of each dot in the picture.
The colors I have used are following:
cols <- list(red = rgb(255/255, 0/255, 0/255), green = rgb(0/255, 255/255, 0/255), blue = rgb(0/255, 0/255, 255/255))
I have managed to open the file and plot it:
library("jpeg")
img <- readJPEG("tree.jpg")
ydim <- attributes(img)$dim[1] # Image dimension y-axis
xdim <- attributes(img)$dim[2] # Image dimension x-axis
plot(c(0,xdim), c(0,ydim), type='n')
rasterImage(img, 0,0,xdim,ydim)
Dimensions in the plot are in pixels. I can also extract the information in one of the RGB channels (here in green):
plot(c(0,xdim), c(0,ydim), type='n')
rasterImage(img[,,2], 0,0,xdim,ydim)
After this I am starting to experience problems. I have found out that Momocs
package, might be able to extract the shapes from RGB channel matrices, but I doubt that it is the right tool for this problem. Maybe one of the spatial packages could work? (I did not find a function for this purpose, though). How do I extract the position (in pixels using an arbitrary coordinate system) of colored dots from an image using R?
which(img[,,1] > x, array.indices=TRUE)
will locate the dots (pick some thresholdx
value). Apologies if the first layer isn't the red one. If you then need to find centroids of clusters, see ifspatstat
can help. – Pentangular