manually cropping an rgb image to get output in rgb

4 vues (au cours des 30 derniers jours)
shreya devkar
shreya devkar le 1 Nov 2019
Réponse apportée : DGM le 24 Mai 2023
I want to crop tongue out of an image I have and in output i want the rgb image of the tongue but i get green section of mask along with my cropped color image
my code is:
img= imread('C:\Users\Shrek\normal\normal1.jpg');
figure(1)
h=imshow(img);
hFH=imfreehand();
BW=hFH.createMask();
ons=find(BW==0);
xy = hFH.getPosition;
% Get coordinates of the boundary of the freehand drawn region.
structBoundaries = bwboundaries(BW);
xy=structBoundaries{1}; % Get n by 2 array of x,y coordinates.
x = xy(:, 2); % Columns.
y = xy(:, 1); % Rows.
drawnow; % Force it to draw immediately.
% Will keep only the part of the image that's inside the mask, zero outside mask.
blackMaskedImage = img;
blackMaskedImage(~BW) = 0;
% Crop the image.
leftColumn = min(x);
rightColumn = max(x);
topLine = min(y);
bottomLine = max(y);
width = rightColumn - leftColumn + 1;
height = bottomLine - topLine + 1;
cropImage = imcrop(blackMaskedImage, [leftColumn, topLine, width, height]);
figure(2)
imshow(cropImage)

Réponses (1)

DGM
DGM le 24 Mai 2023
In this line, the image is MxNx3, but the mask is MxNx1.
blackMaskedImage(~BW) = 0;
So the mask is only applied to the first channel.
One basic way to apply the mask to all channels is:
mask = repmat(~BW,[1 1 size(blackMaskedImage,3)]); % expand the mask
blackMaskedImage(mask) = 0; % apply it

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by