How to change specific RGB value to another RGB value in a PNG uint8 image?

%I have the following code:
RGB = imread('image.png');
[r c z] = size(RGB);
for i=1:r
for j=1:c
if (RGB(i,j,1)==50 && RGB(i,j,2)==205 && RGB(i,j,3)==50)
RGB(i,j,1)=255; RGB(i,j,2)=255; RGB(i,j,3)=255;
elseif (RGB(i,j,1)==255 && RGB(i,j,2)==228 && RGB(i,j,3)==181)
RGB(i,j,1)=255; RGB(i,j,2)=255; RGB(i,j,3)=255;
elseif (RGB(i,j,1)==0 && RGB(i,j,2)==0 && RGB(i,j,3)==0) %MATLAB won't run this part
RGB(i,j,1)==255 && RGB(i,j,2)==255 && RGB(i,j,3)==255;
elseif (RGB(i,j,1)==250 && RGB(i,j,2)==250 && RGB(i,j,3)==250) %MATLAB also won't run this part
RGB(i,j,1)==255 && RGB(i,j,2)==255 && RGB(i,j,3)==255;
else
RGB(i,j,1)=0; RGB(i,j,2)=0; RGB(i,j,3)=0;
end
end
end
%So that's my code
My problem now is why MATLAB does not change the RGB values as indicated in the code comments? Also, is there a way to use operators to simplify the code instead of using so much elseifs? I shall be using this for one of my clustering algorithms. Thank you so much in advance for any help.

1 Comment

also, the imshow(RGB) differs if I use the .jpg version of the file. i'm not sure why:
thanks.

Sign in to comment.

 Accepted Answer

You have
elseif (RGB(i,j,1)==0 && RGB(i,j,2)==0 && RGB(i,j,3)==0) %MATLAB won't run this part
RGB(i,j,1)==255 && RGB(i,j,2)==255 && RGB(i,j,3)==255;
You want to do assignments not tests, same kind of structure as you had used already where you had
RGB(i,j,1)=255; RGB(i,j,2)=255; RGB(i,j,3)=255;

3 Comments

Thanks Walter.
I have revised my code to something like this:
RGB = imread('image.png');
[r c z] = size(RGB);
for i=1:r
for j=1:c
if ((RGB(i,j,1)==50 && RGB(i,j,2)==205 && RGB(i,j,3)==50)|(RGB(i,j,1)==255 && RGB(i,j,2)==228 && RGB(i,j,3)==181)|(RGB(i,j,1)==0 && RGB(i,j,2)==0 && RGB(i,j,3)==0)|(RGB(i,j,1)==250 && RGB(i,j,2)==250 && RGB(i,j,3)==250))
RGB(i,j,1)=255; RGB(i,j,2)=255; RGB(i,j,3)=255;
else
RGB(i,j,1)=0; RGB(i,j,2)=0; RGB(i,j,3)=0;
end
end
end
Next thing I'll try to figure out is how to extract the centroids corresponding to each "black square or rectangle" and store them in a horizontal matrix variable.
i still don't get though why the .jpg version of the file doesn't work as nice as the .png. thanks
How did you create the .png and .jpg files ?

Sign in to comment.

More Answers (0)

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!