0
votes

I am new to Matlab. I have this function which I want to calculate the Euclidean distance between two pixels(RGB).

function[distance]=calc_dist(R1, R2, G1, G2, B1, B2)

    if (R1>R2)
        dR=R1-R2;
    else
        dR=R2-R1;
    end

    if (G1>G2)
        dG=G1-G2;
    else
        dG=G2-G1;
    end

    if (B1>B2)
        dB=B1-B2;
    else
        dB=B2-B1;
    end

  sum=uint64(3*dR*dR+4*dG*dG+2*dB*dB);
  disp(sum);
  distance=(sqrt(double(3*dR*dR+4*dG*dG+2*dB*dB));
end

The problem is the displayed value for sum is 255 each time. This must be happening because the variables are of type uint8. How do I change them? I tried to do some sort of casting

sum=uint64(3*dR*dR+4*dG*dG+2*dB*dB); 

but I get this error: 'Undefined function 'uit64' for input arguments of type 'uint8'. How should I display the right value for the sum? Thanks. '

1
Don't even cast, just do the math. I also don't know why each of those terms should be multiplied - you are computing the Euclidean distance, no? - Ben
and for the record matlab has built in dist() which should be able to calculate distances using several metrics - Ben
@Ben With no casting, the output is 255. Each time. - Tanatos Daniel
The function to cast as a 64-bit unsigned integer is uint64; you were just missing the n. Be that as it may, the casting is occurring too late - after you have done the multiplication and not before. You may want to try something like R1=double(R1) etc. for each input variable (tedious) and then set the Euclidean distance as dist = sqrt((R1-R2)^2 + (B1-B2)^2 + (G1-G2)^2). (Not sure where your 2,3 and 4 come in.) - Geoff
@GeoffHayes Tedious, indeed. It gets the job done, though. Thanks. Isn't there any other way? - Tanatos Daniel

1 Answers

1
votes

Consider converting your input of 6 variables to one 2x3 matrix, where the first row is the RGB colours from one pixel, and the second row is the RGB colours from the second pixel:

function[distance]=calc_dist(R1, R2, G1, G2, B1, B2)

rgbPixels = [R1 G1 B1; R2 G2 B2];

% cast as double
rgbPixels = double(rgbPixels);

% compute the difference between the rows
rgbDiffs = diff(rgbPixels);

% compute the Euclidean distance
distance = sqrt(sum(rgbDiffs.^2));

This way, you don't have to change your signature and all casting can be done in one line. Try the above and see what happens!