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.
maskrectangular? - DivakarcentralPointsrepresents the coordinates, so is it a Nx2 matrix of X-Y coordinates? - DivakardenoisedImagewasdoubleandimgwasuint8. After convertingdenoisedImagetouint8everything was ok. Thanks! - Simon