MATLAB Answers

Setting lone 1s to 0s in a logical vector/matrix

30 views (last 30 days)
If I have this vector for example: [ 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0]
And I want to replace the lone 1 (the sixth element in this case) with a zero, is there an existing algorithm which can do this?
i.e. [ 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0] ----> [ 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0]
For context, this is an example of a row of pixels which has been colour thresholded to return 1s in areas of green and 0s otherwise.
The lone 1 represents an anomalous point, there is no green there and hence I wish to replace it with a 0.
For a further condition, I'd like to do the same for any section of 1s less than 3 in length.
i.e. [0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0] would go to [0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0]

Accepted Answer

Image Analyst
Image Analyst on 2 Apr 2021
You can use bwareaopen() in the Image Processing Toolbox. You specify the smallest region length you want to keep, like to get rid of single 1's keep runs of 2 or longer
v = [ 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0]
v2 = bwareaopen(v, 2) % Keep runs of 2 or longer
  6 Comments

Sign in to comment.

More Answers (1)

Jan
Jan on 2 Apr 2021
Edited: Jan on 2 Apr 2021
a = [0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0];
[val, n] = RunLength(a);
del = (val == 1) & (n == 1); % Or: n < limit
val(del) = 0;
b = RunLength(val, n);
% b = [0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0];

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by