#run in directory containing neural network output masks and corresponding max gfp projections (named MAX_* where * is name of neural network output mask)
#script output is .csv file for each image containing median gfp & size of each cell 
#image dimensions (1024x1024) and channel for GFP (2) are hardcoded 
#dependencies: EBImage package from BioConductor
# author: Taraneh Zarin
# email: taraneh.zarin@mail.utoronto.ca
# Copyright (C) 2018 Taraneh Zarin

img_masks <- list.files(pattern="*.tif")[-grep("MAX", list.files(pattern="*.tif"))]
img_gfp <- list.files(pattern="*.tif")[grep("MAX", list.files(pattern="*.tif"))]
#make sure names match
if(identical(unlist(lapply(img_masks, FUN=function(x){
  paste("MAX_", x, sep="")
})), img_gfp)==T){
  print("Filenames match")}else{stop("Filenames of output masks and corresponding images don't match")}
library(EBImage)
img_masks_read <- lapply(img_masks, readImage)
img_gfp_read <- lapply(img_gfp, readImage)
#function to get median gfp intensity of each cell for each image
get_median_gfp_each_cell <- function(mask_file, gfp_file){
  med_gfp_cell <- NULL
  size_each_cell <- NULL
  for(i in levels(as.factor(as.vector(mask_file)[which(as.vector(mask_file!="0"))]))){
    med_gfp_cell[i] <- median(gfp_file[1:1024,1:1024,2][(which(mask_file==i, arr.ind = T))])
    size_each_cell[i] <- nrow(which(mask_file==i, arr.ind = T))
  }
  return(cbind(med_gfp_cell, size_each_cell))
}
all_imgs_med_gfp <- NULL
for (i in 1:length(img_masks)){
  all_imgs_med_gfp[[i]] <- get_median_gfp_each_cell(img_masks_read[[i]], img_gfp_read[[i]])
}
library(tools)
for (i in 1:length(all_imgs_med_gfp)){
  write.csv(data.frame(all_imgs_med_gfp[[i]]), paste(file_path_sans_ext(img_gfp[i]), ".csv", sep=""))
}