Reputation: 5039
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.
Upvotes: 0
Views: 933
Reputation: 114786
Have you tried
denoisedImage = bsxfun( @times, im2double(img), mask > 0 );
Upvotes: 1