Hi Adrian,
To remove the unwanted scratches from a binary image while preserving other objects, we need to focus on the contours of the scratches. The original approach removed entire regions within the bounding boxes, which led to the undesired removal of other objects. Instead, you can use “bwboundaries” function (https://www.mathworks.com/help/images/ref/bwboundaries.html) to identify these contours and create a contour mask. Finally, you can subtract this contour mask from the binary image to remove only the unwanted contours. Here's a snippet that illustrates this approach:
% Find boundaries using bwboundaries
[B, L] = bwboundaries(binary, 'noholes');
% Create a mask for the contours of the scratches
contourMask = false(size(binary));
% Process only the contours of the scratches
for i = find(~stats.isGreater).'
boundaries = B{i};
boundaryMask = poly2mask(boundaries(:,2), boundaries(:,1), size(binary, 1), size(binary, 2));
contourMask = contourMask | boundaryMask;
end
% Dilate the contour mask to remove thin edge artifacts
se = strel('disk', 1);
dilatedContourMask = imdilate(contourMask, se);
% Remove the contours from the original image
binary(dilatedContourMask) = false;
This should help give the desired output:

Note that I dilated the contour mask by 1 pixel using “strel” (https://www.mathworks.com/help/images/ref/strel.html) and “imdilate” (https://www.mathworks.com/help/images/ref/imdilate.html); this helps remove some undesired edge artifacts near the scratches in the filtered output.