4

i'm using processing and i'm trying to calculate disparity from 2 rectified images and for that i need to take every pixel from left image and seach in one line from right image and find the similar pixel ,the dimension of the images is 640x480 .

I need to run disparityImage(PImage imgL, PImage imgR) in function draw() and is too slow ,the function is execute in 1-2 seconds ,but if i comment these lines of code “minD=d;rightX=xr;” from the if block the function is execute in 3-5 miliseconds. I don’t understand which is the problem with my code,i tried too many hours to find out but i couldn’t.

void depthImage(PImage imgL, PImage imgR) { 
    for (int x=0; x<imgL.width; x=x+1) {
      for (int y=0; y<imgL.height; y=y+1) {    
        color imgleft=imgL.get(x,y);
        float r1=red(imgleft);
        float g1=green(imgleft);
        float b1=blue(imgleft);

        float minD=Integer.MAX_VALUE;
        int rightX=0;

        for (int xr=0; xr<imgR.width; xr++) {    
          color imgright=imgR.get(x,y);
          float r2=red(imgright);
          float g2=green(imgright);
          float b2=blue(imgright);

          float d=dist(r1, g1, b1, r2, g2, b2);

          if (d<minD) {
            minD=d;
            rightX=xr;
          }
        }
      }
    }
  }

1 Answers1

4

dist() calculates the Euclidean distance between 2 points. For the computation the sqrt() function is required. sqrt() is a very time consuming operation.

dist(x1, y1, z1, x2, y2, z2)

can be expressed as

sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1))

I recommend to compute and compare the square of the Euclidean distance instead. That avoids the expensive sqrt operation. e.g.:

void depthImage(PImage imgL, PImage imgR) {
    for (int x=0; x<imgL.width; x=x+1) {
        for (int y=0; y<imgL.height; y=y+1) {

            color imgleft = imgL.get(x,y);
            float r1=red(imgleft);
            float g1=green(imgleft);
            float b1=blue(imgleft);

            float minD_square = Integer.MAX_VALUE;
            int rightX=0;

            for (int xr=0; xr<imgR.width; xr++) {

                color imgright=imgR.get(x,y);
                float dr = red(imgright)   - r1;
                float dg = green(imgright) - g1;
                float db = blue(imgright)  - b1;

                float d_square = dr*dr + dg*dg + db*db;

                if (d_square < minD_square) {
                    minD_square = d_square;
                    rightX = xr;
                }
            }
        }
    }
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174