How to loop through a binary image by column to detect first 5 non-zero pixels in a row?
18 views (last 30 days)
Show older comments
Hugo Armando Morales Solís
on 18 Sep 2021
Commented: Hugo Armando Morales Solís
on 21 Sep 2021
I have a set of binary images from which I need to scan their pixel values by column. If there's exactly "x" number of non-zero pixels in a row, the algorithm needs to recognize this in order to draw a line or completely convert all pixels to "1" in the rows where this "x" non-zero pixels were identified. This is in order to close a region of the image and then calculate the area enclosed by it.
I started looping through the image and then saved the pixel values in a variable. Then I added a counter so as to count the total number of non-zero pixels from the column it's analyzing. However I'm having trouble with this loop for the part where it needs to count 5 non-zero pixels in a row. If it's followed by a zero pixel, then it's where the closing should happen, but if it's followed by yet another non-zero pixel, it means it isn't the region of interest. This is what I have so far, but it's doing nothing to the image:
[rows,columns] = size(I3);
cont = 0;
for column = 1:columns
for row = 1:rows
pixel = I3(row,column);
if (pixel == 1)
cont = cont+1;
end
if (pixel == 0)
cont = 0;
end
if (cont == 5)
if pixel == 1
cont = 0;
end
if pixel == 0
I3(row,columns) = 1;
break
end
end
end
end
figure
imshow(I3)
Thanks in advance. My matlab skills are just basic and so I have trouble with these kinds of loops.
Any help is greatly appreciated.
3 Comments
Accepted Answer
Harikrishnan Balachandran Nair
on 21 Sep 2021
Edited: Harikrishnan Balachandran Nair
on 21 Sep 2021
Hi,
I understand that you are trying to do a column-wise traversal on your image, and see if in any column there are two continuous non zero pixels, and if there are more than 2 continuous non zero pixels, you will skip to the next column.
In that case, you might want to reset the counter value to zero before traversing the next column.
Also, if two continuous non zero pixels are found, the value of the next pixel in the column should be checked before making the pixels in the corresponding row as one.
The following code might help .
[rows,columns] = size(I3); % Image size
cont = 0; % Initialize counter
for j = 1 : columns % Horizontal reading
cont=0;
for i = 1 : rows % Vertical reading
if(I3(i,j)==0)
cont=0;
else
cont=cont+1;
if(cont==2)
if(i==rows||I3(i+1,j)==0) %checking if third there is a third non zero pixel
I3(i,:)=1;
end
break
end
end
end
end
figure
imshow(I3);
Alternatively, you can directly use the 'diff' function in matlab to see if the adjacent pixels in the column are of same value or not.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!