How to remove the background from an image automatically?

Hello,
So I want to ask if anyone knows if there is a macro code that could remove de background by analysing the color of the pixels or other way?

I have this example of image and I have to cut the background
image

And at first I used this code :
makeRectangle(175, 114, 159, 157);
run(“Crop”);

But the problem here is that I have to put the numbers of the region I want to cut and What I really have to do is a code which evaluates pixels and cuts the region when they are evaluated with the black color. It is that possible?

King regards!

I would suggest to first threshold the image to select the lighter coloured bars (without applying the threshold). You can then create a selection based on the thresholded part of the image. You can then either crop the image to the selection or use the coordinates of the thresholded selection to determine the cropping area.
Hope this gives you some ideas,
Volko

1 Like

@Filipa_Neves
If the separation of the bands seems easy enough it is not the same for placing the labels of the ROIs.

The bands do not have the same height!
Use the “Statistical Region Merging” plugin
then // setTool (“wand”);
bandes

Hello @Mathew!
Thank you so much for your advice, I used the “Statistical Region Merging” plugin in this macro:

Title= getTitle();
selectWindow (Title);

setAutoThreshold(“Huang”);
run(“Statistical Region Merging”);
setTool(“wand”);
run(“Crop”);

But this error appeared, what can I do?

Thank you once again!

@Filipa_Neves
Test this macro

run("Duplicate...", "title=1");
close("\\Others");
run("Duplicate...", "title=2");
run("Invert");
run("Statistical Region Merging", "q=25 showaverages");
//setTool("wand");
doWand(187, 182);
roiManager("Add");
roiManager("Select", 0);
roiManager("Rename", "1");
doWand(218, 166);
roiManager("Add");
roiManager("Select", 1);
roiManager("Rename", "2");
doWand(245, 192);
roiManager("Add");
roiManager("Select", 2);
roiManager("Rename", "3");
doWand(270, 234);
roiManager("Add");
roiManager("Select", 3);
roiManager("Rename", "4");
doWand(298, 225);
roiManager("Add");
roiManager("Select", 4);
roiManager("Rename", "5");
roiManager("Select", newArray(0,1,2,3,4));
roiManager("Combine");
roiManager("Add");
roiManager("Show All without labels");
roiManager("Select", 5);
selectWindow("1");
run("Restore Selection");
run("Crop")
run("Select None");
selectWindow("2");
roiManager("Select", 0);
RoiManager.setPosition(0);
roiManager("Set Fill Color", "red");
roiManager("Select", 1);
roiManager("Set Fill Color", "green");
roiManager("Select", 2);
roiManager("Set Fill Color", "blue");
roiManager("Select", 3);
roiManager("Set Fill Color", "white");
roiManager("Select", 4);
roiManager("Set Fill Color", "yellow");
roiManager("Show All");