MATLAB: Can I apply a graylevel mask on a color image

Image Processing Toolboximage segmentationmask regions graylevelmasking

Hi everyone, I have an RGB image(n by m by 3) that i segmented it using watershed algorithm. The output of the segmentation is a graylevel image (n by m) which contains the labels assigned to each region of the image. I want to calculate the average of each region's color of the original image but i don't find how to define each region of the original color image. Is it possible to consider the output of the watershed (the graylevel image) as a mask of my original image? If not, can anyone please suggest another solution? Thank you for your answer.

Best Answer

It can be done any numbers of ways. Probably the simplest is to use regionprops on your label image and ask for the 'PixelIdxList' of each blob. This is gives you the linear pixel index of each blob in each channel. You could then just loop over the blobs and channels to compute the mean:
blobprops = regionprops(yourlabelimage, 'PixelIdxList');
channelmeans = zeros(numel(blobprops), size(yourimage, 3)); %using size(img, 3) so that it works with rgb and greyscale images
for channel = 1:size(yourimage, 3)
imagechannel = yourimage(:, :, channel);
for blob = 1:numel(blobprops)
channelmeans(blob, channel) = mean(imagechannel(blobprops(blob).PixelIdxList));
end
end
Or you can use the 'PixelList' instead, repmat that for each colour channel, convert to linear index, extract the pixels and reshape into 3D to avoid the channel loop:
blobprops = regionprops(yourlabelimage, 'PixelList');
channelmeans = zeros(numel(blobprops), size(yourimage, 3)); %using size(img, 3) so that it
for blob = 1:numel(blobprops)
allpixelsidx = reshape(sub2ind(size(yourlabelimage), [repmat(blobprops(blob).PixelList, [3 1]), repelem([1;2;3], size(blobprops(blob).PixelList, 1)]), [], 3);
channelmeans(blob, :) = mean(yourimage(allpixelsidx), 2);
end