MATLAB: Count pixel number of each white spot on a binary image

count pixel

i have two bright sopts on the same binary image. is it possible to count pixel number of each spot without image processing tool?

Best Answer

The below describes how to do "4 connectivity", where diagonal connections are not enough. The scheme can be extended without much trouble to "8 connectivity" where diagonals are permitted as well.
Scan the array in linear index order -- so first column, then second column, then third, and so on.
Keep a cell array of vectors, initialized to empty.
At any particular point, if the current point is 0, move on to the next point.
If instead the current point is 1, look to the left (one column earlier) to see whether that point is also 1. If it is, search the cell arrays of vectors to find the vector with value equal to the linear index of the point to the left. Add the linear index of the current point to the end of that vector.
Having done that (continuing the case of entry is 1), now look up (one row earlier, same column), to the point you just came from, and check to see if it is 1. If it is, then find the vector in the list that has value equal to the linear index of the point above. If it is not the same vector as the one you added the current point to, then merge those two vectors together into a single vector.
At the end of this process, every point that is 1 will have its linear index appear in exactly one of the vectors, and that vector has the linear indices of all points that are in the same blob, and the vector will not have any linear indices from different blobs.
The size of each blob (number of pixels) will be the length of the linear index vector for the blob.
Optimization hint when you extend this to include diagonals: if you check diagonal up and left and find it was 1 and do the processing for that, and then you check left and find it was 1 as well, then you can be sure that the one to your left is already in the same blob as the one diagonal up and left, because you would have merged them when you got to that column. Likewise if you process left and find it is 1 and then process left-and-down and find it is 1, you can be sure that pixel is in the same blob; it does not need to be checked. So if up-and-left is set, you can skip merge processing for left alone and go on to check down-and-left and if it is set, you can skip merge processing if left-alone was also set. And if up-and-left was not set but left is and you do merge processing on that, then you can skip merge processing for down-and-left as you can be sure it is part of the same blob as left if both are set.