简体   繁体   中英

Data types use in Matlab functions

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. '

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM