MATLAB: How can i select labeled images that are touching a specific axis,like x-axis,y-axis,and their paralel axis,also the one touches 2 axis at the same time,forexample touches x-axis and its paralel axis at the same time

Image Processing Toolboxselecting labeles touching the borders

in some cases i want to detect the one touches an specific border,forexample x-axis,or the parallel axis to it,or y-axis or the parallel axis to it,and in some cases i want to remove the ones whom are touching these axis,and also is it possible to select the one which touches 2 axis at the same time,mostly in my case there are some labeled images which are touching both x-axis and its parallel axis(like one of the blobs in the picture,,so im going to select them,and segment them once more,after removing the ones whom only touch x-axis,and in case of margines,im goint to remove some labels whom touch the y-axis or its parallel axis,and x-axis at the same time,so if you can tell me how i can select the one whom touching each border seperately,and also selecting the one touching 2 border at the same time,
i want to detect blobs which are shown in the picture seperately,once select the one touching the x-axis…imclearborder remove all blobs touching all 4 borders,

Best Answer

To get rid of objects touching just one border is simple. Simply store the 3 edges of the image that you want to keep. Then zero out those 3 edges and call imclearborder(). Then restore the 3 edges that you zeroed out. Let's say you wanted to delete blobs touching the bottom edge only. Then
% Save 3 edges.
topEdge = binaryImage(1, :);
leftEdge = binaryImage(:, 1);
rightEdge = binaryImage(:, end);
% Zero 3 edges.
binaryImage(1, :) = false;
binaryImage(:, 1) = false;
binaryImage(:, end) = false;
% Get rid of blob(s) touching bottom edge
binaryImage = imclearborder(binaryImage);
% Restore the 3 edges.
binaryImage(1, :) = topEdge;
binaryImage(:, 1) = leftEdge ;
binaryImage(:, end) = rightEdge ;
You could build all that into a function where you pass in the edge(s) you want to remove from.