计算处理中的视差

4
我正在使用Processing编程语言,尝试从两张校准过的图像计算视差(disparity),为此需要从左侧图片中获取每个像素,并在右侧图像中搜索一行找到与之相似的像素。这两张图片的尺寸都是640x480。
我希望在draw()函数中执行disparityImage(PImage imgL, PImage imgR),但这个函数运行起来太慢了,需要1-2秒才能执行完毕。但如果我注释掉if代码块里的“minD=d; rightX=xr;”那几行代码,该函数只需要3-5毫秒就能执行完毕。我不明白问题出在哪里,已经试了很多小时也没有结果。
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个回答

4

dist()计算两点之间的欧几里得距离。计算过程需要使用sqrt()函数,该函数非常耗时。

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

可以表示为
sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1))

我建议计算并比较欧几里得距离的平方。这避免了昂贵的sqrt操作。例如:

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;
                }
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接