Q: Find number of white/black pixels in binary image I have an binary word image with grid and i want to find the foreground pixels (number of black and white in each segments) in each segments

A: So I just wanted to get the total number of black pixels for an image and I didn't want to segment it. Didn't feel like having to learn how to segment a matrix.
Easy fix to get the sum of the black pixels:
sum(sum(bw == 0)) 

Conversely to get the white pixels
sum(sum(bw == 1))

The operation function sum(bw == 0) just gets everything to a [1xn] matrix, so you will need to perform sum and you will get the whole image matrix summed.
Thought that cumsum would do the trick, but sum(sum()) is just better for this case. Tells you how little I know about coding. Have fun with this info, note that I'm just using this to determine the area coverage of a binarized image, but for anything else particularly useful.

A: That is easy with logical indexing. 
For each segment, do:
n_white=sum(segment(:)==1);
n_black=sum(segment(:)==0);


A: Assume your black and white image is bw
 sum(bw==0) // number of black pixels
 sum(bw==1) // number of white pixels

For each grid find the range in both directions, then apply the same idea.
For example, from x1 to x2 and y1 to y2 is one grid:
  sum(bw(x1:x2, y1:y2) == 0) // will give you the black pixels you want

