How to determine the number of white lines in a BW image/vector

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!!

 Respuesta aceptada

Well you'd start off by detecting the transition from 0 to 1 or 1 to 0. you this can be done by
vect = [0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 1 1 ];
det = [vect 0]-circshift([vect 0],[0 1])
start = find(det==1)
stop = find(det==-1)
outputarray = [(stop-start)' start']

4 comentarios

If you want this approach, look at DIFF too.
Thanks Joseph! So smart!
Yang Zhao
Yang Zhao el 29 de Abr. de 2015
Editada: Yang Zhao el 29 de Abr. de 2015
Hey Ashish. Thanks. It work too! So i just change a piece of Jos's codes to
det = diff([0 vect 0])
yup. i used circshift in my test code as some flexibility to shift it in either direction.

Iniciar sesión para comentar.

Más respuestas (1)

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

Categorías

Etiquetas

Preguntada:

el 29 de Abr. de 2015

Respondida:

el 29 de Abr. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by