MATLAB: Find mean of 2d slice in 3d segmented volume

arraymean

I have a 3d variable with slices containing segmented rois (128x128x10) . I am trying to find the mean value for each slice in such a way that it does not average the zero pixels around the roi. i want a 1 x 10 array containing the mean value for each slice.

Best Answer

Try this:
[rows, columns, slices] = size(image3d);
% image3d is your masked gray level image with some zeros in it.
sliceMeans = zeros(1, slices);
for slice = 1 : slices
% Get this slice
thisSlice = image3d(:, :, slice);
% Find out what pixels are nonzero
nonZeroIndexes = thisSlice ~= 0;
% Compute the means of only non-zero pixels.
sliceMeans(slice) = mean(thisSlice(nonZeroIndexes))
end