Automated image cropping

I’m assisting in a research project and we have thousands of images to process. Each image contains multiple eggs and has a corresponding black and white mask that highlights the outline of one specific egg, the objective is to crop out each egg uniformly using the masks

Example of mask: https://imgur.com/Nl4P1pt
Example of image: https://imgur.com/0ABpEoN

The current procedure:

  • outline mask manually
  • use EnlargeAndSpecify plugin to create a 30 pixel buffer around mask
  • manually record the dimensions and placement of the rectangular selection
  • crop selection
  • save mask
  • open corresponding image
  • use IROIspecify plugin with recorded dimensions and placement (from mask) to place selection around egg
  • crop selection
  • save image

Is it possible to automate this using macros? The first obstacle is automating the selection around the mask, is there an edge finder plugin or something similar?
Thanks

I am not sure I fully understand the description of your problem, and I am not familiar with the plugins mentioned, but in principle the workflow could be automated.
Try the ImageJ macro script below after opening the images you posted as example. If it accomplishes your goal, then you can incorporate it in a batch procedure. Since imagej.net is currently under maintenance, I can only point you to this document https://imagej.nih.gov/ij/docs/pdfs/ImageJBatchProcessing.pdf , where you can find an overview of possible ways to automate a script.
I hope this helps

run("Options...", "iterations=1 count=1 black do=Nothing");

// select mask file, generate and enlarge selection
selectWindow("Nl4P1pt.png");
run("Select None");
run("Create Selection");
run("Make Inverse");
run("Enlarge...", "enlarge=30");

// transfer selection to image, crop and save
selectWindow("0ABpEoN.jpg");
run("Restore Selection");
run("Crop");
run("Select None");
saveAs("PNG", "");
1 Like

this worked well! how do I overcome the problem of having to specify the window name each time, should I separate the masks and photos into two directories?

@mnrzaf001 You can decide to separate images and masks in two separate directories, but anyway you need to have a way to link each mask to the corresponding image, either in their name assignation (e.g. img001.tif and img001_mak.tif) or in some other way. In section 4.1 of the document mentioned before you find an example of how to process multiple files from a directory. In https://imagej.nih.gov/ij/developer/macro/functions.html you should find all the macro commands needed for your script.