How to determine the number of white lines in a BW image/vector
Show older comments
Say, I have a vector [ 0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 1 1 ]. I want to know how many consecutive '1's in this vector, their lengths, and location.
In this example, we know that there are three consecutive '1's (or white lines). The length is 3 for first one, 5 for second one, and 2 for third one. The location (of the beginning of the white line) is 4 for first one, 12 for the second one, and 20 for the third one.
Eventually I want to have an array to store these info, such as
x = [length, location]
Take the previous example, then x = [3,4; 5,12; 2,20]
How can I realize it with matlab? Prefer a FAST code without running loops! Thank you!!
Accepted Answer
More Answers (1)
Image Analyst
on 29 Apr 2015
I know you already accepted an answer, but if you have the Image Processing Toolbox, you can get all the lengths simply and directly in a single, simple line of code:
measurements = regionprops(logical(vect), 'Area')
Perhaps it might help someone else. Here's a full demo:
vect = [0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 1 1 ];
measurements = regionprops(logical(vect), 'Area')
% measurements has the lengths of your 1 regions.
% To show you, you can print them out
for k = 1 : length(measurements);
fprintf('Region %d has a length of %d elements.\n',k, measurements(k).Area);
end
% If you want, you can get all the lengths into a single array:
allLengths = [measurements.Area]
In the command window you'll see:
measurements =
3x1 struct array with fields:
Area
Region 1 has a length of 3 elements.
Region 2 has a length of 6 elements.
Region 3 has a length of 2 elements.
allLengths =
3 6 2
Categories
Find more on Object Detection in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!