The algorithm is too slow

Hello, i am 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 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 disparityImage(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 Like

It seems get is slower than pixels[]

https://processing.org/reference/pixels.html

Also dist is slow and there are faster ways like pythagoras but without the squarerroot (doesn‘t matter since you only need the relative distance)

3 Likes

get() is much slower than pixels[] – AND red() green() blue() is much slower than bit-shifting.

Explanations for how to optimize your code performance by bypassing these calls are in the reference pages for each function.

https://processing.org/reference/get_.html
https://processing.org/reference/red_.html
https://processing.org/reference/green_.html
https://processing.org/reference/blue_.html

3 Likes