Personal tools
You are here: Home Users Geoffrey Morris Plant Image Analysis

Plant Image Analysis

Define grid

  • Coordinates file: /home/gmorris/image_coords.Rdata
# Run R from: /usr/local/lib64/R/bin/R  --no-restore

## Define a grid for plants in flats
library(EBImage)

# Convert from plot coordinates to matrix coordinates
get_matrix_coord <- function(coord_list, pixel_matrix) {
   len <- length(coord_list[[1]])
   coord_list$y <- rep(1,len) - coord_list$y # Flip y-coordinates back
   coord_list$x <- coord_list$x*dim(pixel_matrix)[1] 
   coord_list$y <- coord_list$y*dim(pixel_matrix)[2]
   return(coord_list)
}

# Test: filename <- '/home/gmorris/plant_flat.jpg'
filename <- '/home/g2data/albums/2019-03-03/IMG_3980.JPG'
img <- readImage(filename, TrueColor)
pix <- channel(img,'green')@.Data # Extract pixel data
dim(pix) <- dim(pix)[1:2] # Convert to matrix
image(pix[,ncol(pix):1], col=gray(1:100/100)) # Flip to retain orientation

# Get pot size
cat('Click: [1] plot window to select, [2] top left, [3] bottom right\n')
pot_img <- locator(2) # Clockwise, starting from top left
pot <- get_matrix_coord(pot_img, pix)
x_pix <- round((pot$x[2]-pot$x[1])/2)
y_pix <- round((pot$y[2]-pot$y[1])/2)

n_rows <- 5
n_cols <- 6
n_missing <- 0 # Number of missing cells
n_plant <- n_rows*n_cols - n_missing

centers_img <- locator(n_plant) # Clockwise, starting from top left
centers <- get_matrix_coord(centers_img, pix)

centers <- data.frame(centers)
top_left     <- data.frame(x = centers$x - x_pix, y = centers$y - y_pix)
top_right    <- data.frame(x = centers$x + x_pix, y = centers$y - y_pix)
bottom_right <- data.frame(x = centers$x + x_pix, y = centers$y + y_pix)
bottom_left  <- data.frame(x = centers$x - x_pix, y = centers$y + y_pix)

outdir <- '/home/gmorris/image'
for (i in 1:n_plant ) {
   tmp <- img[ top_left[i,1]:top_right[i,1], top_left[i,2]:bottom_left[i,2], 1]   
   writeImage(tmp, file.path(outdir, paste(i, '_crop.jpg', sep='')) ) 
}

## Plot centers and rectangles for quality control
png('/home/gmorris/microclimate/www/image_coords.png', width=dim(pix)[1]/4, height=dim(pix)[2]/4)
image(pix[,ncol(pix):1], col=gray(1:100/100)) # Flip to retain orientation
x_left   <- top_left$x/dim(pix)[1]
y_bottom <- rep(1,nrow(top_left)) - bottom_right$y/dim(pix)[2]
x_right  <- top_right$x/dim(pix)[1]
y_top    <- rep(1,nrow(top_left)) - top_left$y/dim(pix)[2]
rect(xleft=x_left, ybottom=y_bottom, xright=x_right, ytop=y_top, border='red', lwd=5)
points(I(rep(1,nrow(centers)) - centers$y/dim(pix)[2])~I(centers$x/dim(pix)[1]), col='red')
dev.off()

save(filename, top_left, top_right, bottom_right, bottom_left, 
   file='/home/gmorris/image_coords.Rdata')

##
# To get the green channel with much less background
display((channel(img,'green') - channel(img,'gray'))*10)

  Loading plot...

Document Actions