Change specific color in an image to another one

234 views (last 30 days)
Hello,
I am trying to change colors in an image into another color. I have generated some code myself but something seems to be wrong. What I am trying to achieve on the attached file is to change every purple data point into a green data point, or whatever color I would prefer. Currently, the code that I have written is able to change purple to green but the edges of the marked points are still in purple, I believe this has something to do with the intensity at the edges being different or something...
[I,m] = imread('iteration31.png');
%image = imshow(I,'Colormap',m);
rgbImage = ind2rgb(I,m);
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
purplePixels = redChannel == 1 & greenChannel == 0 & blueChannel == 1;
% MAKE THEM GREEN
redChannel(purplePixels) = 0;
greenChannel(purplePixels) = 1;
blueChannel(purplePixels) = 0;
rgbImage = cat(3, redChannel, greenChannel, blueChannel);
imshow(rgbImage);

Accepted Answer

Matthew Eicholtz
Matthew Eicholtz on 5 May 2017
This is a tough problem. Since you are using a raster image, objects that look purple are actually many small variations of purple. One thing you could try to do is compute which colors are purple-ish, and then modify those colors in the colormap.
Here is an example that may yield slightly better results than what you were experiencing, but still not perfect:
% Read image
[I,m] = imread('iteration31.png');
% Find purple-ish colors
mask1 = abs(m(:,3)-m(:,1))<0.8;
mask2 = abs(m(:,3)-m(:,2))>0.3;
mask3 = abs(m(:,2)-m(:,1))>0.3;
mask = mask1 & mask2 & mask3;
% Convert purple-ish colors to green-ish colors
m(mask,:) = 1-m(mask,:);
% Create and show newly colored image
rgb = ind2rgb(I,m);
imshow(rgb);

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by