MATLAB: Removing Short Runs from Binary Data

MATLABshort runs

I have a large string of binary data of the form:
A = [0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0]
Within the data, if I have a group of 0s with an occasional 1, I want to convert that 1 to a zero. Similarly for a group of 1s with an occasional 0.
As a rule, I want to reset runs of 1s or 0s that are shorter than 3 consecutive values in length to the value of the surrounding elements.
So 0,0,0,1,0,0,0 would become 0,0,0,0,0,0,0
I'd also like to convert something like 1,1,1,0,0,1,0,1,1 to all 1s.
Any suggestions on how to do this? Thanks in advance.

Best Answer

There is a built-in function for this, if you have the Image Processing Toolbox. Two functions actually. You can use bwareafilt() or bwareaopen(). Try it.
[EDIT]: OK, here is the code:
A = [0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0]
% Case 1: Get rid of stretches of 1's shorter than 3.
A2 = bwareaopen(A, 3)
% Case 2: Get rid of stretches of 0's shorter than 3.
A = [1,1,1,0,0,1,0,1,1]
A3 = ~bwareaopen(~A, 3)
For Case 3: Both cases: get rid of stretches of 1's shorter than 3 AND runs of 0's shorter than 3, it depends on the order in which you do the operations. For example, what does [1, 1, 0, 1, 1 , 0, 0, 1, 1] become? All 1's or all zeros?