-1

I intended to choose one point of the image and compare other points' RGB values with this point's, and then change the similar points' colors, but I failed. Following is my code:

function exchangecolor()
I1=imread('F:\28.jpg');   
I2=imread('F:\29.jpg'); 
[m1,n1,x1]=(size(I1));
[m2,n2,x2]=size(I2);  //[399,400,3]=size(I1)=size(I2)
r1=I1(200,200,1);  
r2=I2(200,200,1);

g1=I1(200,200,2);
g2=I2(200,200,2);

b1=I1(200,200,3);
b2=I2(200,200,3);

for i=1:m1
    for j=1:n1
        if abs(I1(i,j,1)-r1)<=10
            if abs(I1(i,j,2)-g1)<=10
                if abs(I1(i,j,3)-b1)<=10
                    I1(i,j,1)=r2;
                    I1(i,j,2)=g2;
                    I1(i,j,3)=b2;
                end
            end
        end
    end
  end
imwrite(I1,'F:\89.jpg','jpg');
Shai
  • 111,146
  • 38
  • 238
  • 371
Smile
  • 25
  • 1
  • 5
  • 1
    In what way did you fail? – Oliver Charlesworth Nov 13 '14 at 13:41
  • 1
    Example images, if you have rights to post them, would help a lot too. Simple logic is only going to work on very easy images. – Neil Slater Nov 13 '14 at 13:43
  • @Oliver I failed because the 'similar' points I got from the comparison are incorrect. In other words, I failed to find the similar points. – Smile Nov 14 '14 at 11:07
  • @Neil Sorry, I don't have the right. The images I choosed are similar except the clothes' colors. – Smile Nov 14 '14 at 11:13
  • @Smile you might find [this thread](http://stackoverflow.com/questions/4063965/how-can-i-convert-an-rgb-image-to-grayscale-but-keep-one-color) relevant to your problem. – Shai Nov 14 '14 at 12:31

1 Answers1

0

I'm not sure about the correctness of your code, but nested loops and if clauses is not the Matlab-ish way of doing stuff.

Have you considered this approach:

rgb1 = I1(200,200,:);
rgb2 = I2(200,200,:);
sel = all( abs( bsxfun(@minus, I1, rgb1) ) <= 10, 3 );%//need care when subtracting `uint` type!
% replace
for ci=1:3
    tmp = I1(:,:,ci);
    tmp(sel) = rgb2(ci);
    I1(:,:,ci) = tmp;
end

The only thing I can think of that might be problematic here is that I1 is probably of type uint8 and for some reason Matlab is having hard time subtracting rgb1 from I1. Try casting I1 to double and see if it helps.


PS,
It is best not to use i and j as variable names in Matlab.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Thank you for your help and advice. I'm a beginner. I will pay more attention to my variable names next time. – Smile Nov 14 '14 at 11:17
  • But the code you offer doesn't work very well. I think my logic isn't practical. – Smile Nov 14 '14 at 11:26