Chang a color in an image to black
Show older comments
Hi everyone, i have this code to change a color in the image that i want to black (by entering the name of color). But i got a problem with orange because when i tried to change the orange, it mix with red color. Can anyone tell me how to fix this?
clc;
originalImage = imread('coloredChips.png'); % Load original ColoredChips.png image
[rows, columns, channels] = size(originalImage); % Get the dimensions of the image
% Check if the iamge is not RGB
if channels~=3
error('the image needs to be RGB')
end
% Display the original image
subplot(2,1,1);
imshow(originalImage);
% These masks select the chips in the image
maskR = originalImage(:,:,1) >= 173 & originalImage(:,:,2) < 68 & (10 < originalImage(:,:,3) & originalImage(:,:,3) < 200);
maskG = originalImage(:,:,1) < 60 & originalImage(:,:,2) > 100 & originalImage(:,:,3) < 150;
maskB = originalImage(:,:,1) < 20 & (30 < originalImage(:,:,2) & originalImage(:,:,2) < 100) & originalImage(:,:,3) > 150;
maskY = originalImage(:,:,1) > 200 & originalImage(:,:,2) > 200 & originalImage(:,:,3) < 160;
maskO = (originalImage(:,:,1) > 120 & originalImage(:,:,1) < 255) & (originalImage(:,:,2) < 55 & originalImage(:,:,3) < 20) | (originalImage(:,:,2) > 50 & originalImage(:,:,2) < 122) & originalImage(:,:,3) < 80;
%Change the color to blackre
black = [0 0 0];
% Create the new image from orginal image
newImage = originalImage;
% Taking input from user
color = input('Enter color to remove: ', 's');
% Change the color according to the input
while true
if (lower(color) == "red")
selectedmask = repmat(maskR,[1 1 3]);
break
elseif (lower(color) == "green")
selectedmask = repmat(maskG,[1 1 3]);
break
elseif (lower(color) == "blue")
selectedmask = repmat(maskB,[1 1 3]);
break
elseif (lower(color) == "yellow")
selectedmask = repmat(maskY,[1 1 3]);
break
elseif (lower(color) == "orange")
selectedmask = repmat(maskMagenta,[1 1 3]);
break
else
disp("Wrong color or Color not found.");
break
end
end
newImage(selectedmask) = 0;
newImage = newImage + uint8(selectedmask.*permute(black,[1 3 2]));
% Display the new image
subplot(2,1,2);
imshow(newImage);

Accepted Answer
More Answers (1)
Walter Roberson
on 21 Jul 2021
elseif (lower(color) == "orange")
selectedmask = repmat(maskMagenta,[1 1 3]);
You do not define maskMagenta in your code, and it seems unlikely that you want to use a magenta mask for orange.
1 Comment
Khoa Tran
on 21 Jul 2021
Categories
Find more on Images in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

