MATLAB: BWDIST label matrix not returning expected labels

bwdistimage processingImage Processing Toolbox

I am trying to use the label matrix feature of bwdist, but am encountering a problem. Instead of returning the linear index of the nearest non-zero pixel, the function is returning a matrix where every pixel's value is its own linear index. I am assuming I am misusing or misunderstanding the function, but am not sure how?
Example:
% Generate test image
BW = zeros(500);
BW(50:90,1:500) = 1; figure,imshow(BW)
[distMap,labelMask] = bwdist(~BW);
figure,imshow(labelMask,[]) % It's a gradient because of the issue noted above
It is my understanding that the labelMask here should contain mostly zeros with linear index values in the rectangular region, or at least some deviation in the rectangular region from the rest of the image.

Best Answer

I think you really want the distMap output, which gives you the distance to the nearest non-zero pixel.
labelMask gives you the index of the nearest non-zero pixel. For most of these pixels, that index is itself. Since the index is computed as i = row + col*numrows, this increases linearly with the row and col value of the pixel.
Check out the matrix itself (labelMask(45:50,1:4)) the values increase and then BOOM! When you hit 50 they flatten off - because the last pixel was the non-zero one.