Change a specific color in an image to black

Viewed 143

I want my program to change a color in the user's input in coloredChips.png to black. How can I do it? I have tried but it failed.

clc;
close all;
clear;
originalImage = imread('coloredChips.png'); % Load original ColoredChips.png image
[rows, columns, numberOfColorBands] = size(originalImage); % Get the dimensions of the image
% Display the original images
subplot(2,1,1);
imshow(originalImage);
% Extract the individual red, green, and blue color channels.
redChannel = originalImage(:, :, 1);
greenChannel = originalImage(:, :, 2);
blueChannel = originalImage(:, :, 3);
black = redChannel == 0 & greenChannel  == 0 & blueChannel  == 0;
color = input("Enter color to remove(RED,GREEN,BLUE): ", 's'); % taking input from user
for row = 1 : rows %iterating over each pizel of image
    for column = 1 : columns
        if color == "RED"
            originalImage(black) = 0; % if input is red we'll make red channel value for this pixel to 0
        elseif color == "GREEN"
            originalImage(black) = 0; % if input is green we'll make red channel value for this pixel to 0
        else
            originalImage(black) = 0; % if input is green we'll make red channel value for this pixel to 0
        end
    end
end
rgb = cat(3, redChannel, greenChannel, blueChannel);
subplot(2,1,2);
imshow(rgb);

As you can see, I input RED but the image is still red, not black:

current result

1 Answers

First issue with your code is, that within your for loop you change the originalImage and not your red, green, blueChannels. Secondly you dont use the iteration agruments, meaning you dont actually set the corresponding pixels, actually within your for-loop you set black pixels to black.

Bellow my example code how I'd solve the problem. Hope this gives you some indication.

orgImg = imread('image.jpg');

% threshold 
t = 0.5;
colThresUp = t * 255;
colThresLow = (1-t) * 255;

% init color mat
rMat = orgImg(:,:,1);
gMat = orgImg(:,:,2);
bMat = orgImg(:,:,3);

% build an index matrix of all pixels that are above the threshold
% resp. below for the other colors

% TODO depending on user selection - example for RED
idxSelCol = orgImg(:,:,1) > colThresUp & ...
    orgImg(:,:,3) < colThresLow & ... 
    orgImg(:,:,2) < colThresLow;

% set all pixels above the threshold to zero i.e. black
rMat(idxSelCol) = 0;
gMat(idxSelCol) = 0;
bMat(idxSelCol) = 0;

% build new image
modImg = cat(3, rMat,gMat,bMat);

% visualize result
subplot(2,1,1)
imshow(orgImg)

subplot(2,1,2)
imshow(modImg)
Related