0
votes

I have an RGB image which is read as a matrix with 3 dimensions, img, and I have a binary mask which represents a segmentation of the image, mask.

How can I crop the image based on the binary mask in matlab? I tried to select only the pixels marked by the binary mask but the resulted image does not have the original colors.

centralPoints = find(mask > 0);
denoisedImage = zeros(424, 424, 3);
slice1 = zeros(424, 424);
origSlice = img(:, :, 1);
slice1(centralPoints) = origSlice(centralPoints);
slice2 = zeros(424, 424);
origSlice = img(:, :, 2);
slice2(centralPoints) = origSlice(centralPoints);
slice3 = zeros(424, 424);
origSlice = img(:, :, 3);
slice3(centralPoints) = origSlice(centralPoints);

denoisedImage(:, :, 1) = slice1;
denoisedImage(:, :, 2) = slice2;
denoisedImage(:, :, 3) = slice3;

This is the code. img is the original image, centralPoints are the coordinates of the foreground pixels and denoisedImage represents the cropped matrix.

However, denoisedImage does no maintain the colors of the original image inside the cropped region. The foreground pixels do not form a rectangular region, however, they form one connected component.

1
Is the mask rectangular? - Divakar
No, mask is not rectangular, but it is connected, all the foreground pixels form one connected graph component. - Simon
You said centralPoints represents the coordinates, so is it a Nx2 matrix of X-Y coordinates? - Divakar
I have added a piece of code where I illustrate for I obtained the coordinates. - Simon
It was because denoisedImage was double and img was uint8. After converting denoisedImage to uint8 everything was ok. Thanks! - Simon

1 Answers

1
votes

Have you tried

denoisedImage = bsxfun( @times, im2double(img), mask > 0 );