Given a matrix:
0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0
0 0 1 1 0 1 0 1
0 0 1 1 0 1 0 0
0 0 0 0 1 0 0 0
notice how the 1’s are mainly clustered except for the 1 in the 3rd row, last column
what I want to do is get rid of excess 0’s and keep only the cluster of 1’s. This is what I’m trying to do with an image, so the cropped result should be rectangular:
0 1 1 1
1 1 0 1
1 1 0 1
0 0 1 0
the above crop is the smallest rectangular crop I can do to cover the most amount of 1’s.
The problem I have right now is how do to this in matlab? I can’t simply strip all 0’s and I have to watch out for outlier 1’s. What is the most efficient method to tackle this problem?
I can only think of manually going row by row, column by column to look for clusters.
What you’re trying to do is equivalent to labeling 2D connected components in a binary image. If you have access to the image processing toolbox, the function is
bwlabel: http://www.mathworks.com/help/toolbox/images/ref/bwlabel.htmlIf you don’t have acccess to
bwlabel, there are several algorithms out there. The fastest one I know of is the one that OpenCV uses, which finds closed contours in the image and is based onF. Chang, C.-J. Chen, and C.-J. Lu, “A linear-time component-labeling
algorithm using contour tracing technique,” Computer Vision and Image
Understanding, vol. 93, no. 2, pp. 206–220, 2004