MATLAB: Counting the number of ‘gaps’ in a binary image

binaryImage Processing ToolboxMATLABpixel count

I have a binary image (attached a resized png for a better idea of what I'm working with) that I want to count the number of 'gaps' per row on. I've added it as a matrix and it's perfect with white cells as '255' and black cells as '0'.
My thinking for how to do this would be for each row, create a count of how many times a 0 value is followed by a 255 value (and then subtract 1, since I'm only interested in the white cells that fall between black cells). Alternatively, counting the number of times strings of 255 appear I think would work. What code should I use to do that?

Best Answer

sum(diff(yourimage, [], 2) > 0, 2) - 1
Will give you the number of transition from 0 to 1 (or 255) minus 1, per row. Note that it will still be one too many if the row starts with 0.