Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

stereo_match.py to cpp

Hi there. I'd like to generate a disparity map from a stereo image in C++. The C++ sample is a bit large and hard to strip out what I really want. The Python version was easier to strip down. Here is my stripped down python version:

#!/usr/bin/env python

if __name__ == '__main__':
    print 'loading images...'
    imgL = cv2.pyrDown( cv2.imread('aloeL.jpg') )  # downscale images for faster processing
    imgR = cv2.pyrDown( cv2.imread('aloeR.jpg') )

    # disparity range is tuned for 'aloe' image pair
    window_size = 3
    min_disp = 16
    num_disp = 112-min_disp
    stereo = cv2.StereoSGBM(minDisparity = min_disp,
        numDisparities = num_disp,
        SADWindowSize = window_size,
        uniquenessRatio = 10,
        speckleWindowSize = 100,
        speckleRange = 32,
        disp12MaxDiff = 1,
        P1 = 8*3*window_size**2,
        P2 = 32*3*window_size**2,
        fullDP = False
    )

    print 'computing disparity...'
    disp = stereo.compute(imgL, imgR).astype(np.float32) / 16.0

    cv2.imshow('left', imgL)
    cv2.imshow('disparity', (disp-min_disp)/num_disp)
    cv2.waitKey()
    cv2.destroyAllWindows()

By comparing to the cpp sample, I converted the above python script to cpp. I think I did it right, but am having trouble getting data within range to view the result. I need a second set of eyes on this code. What did I screw up? Here's my cpp code:

void bringWithinRange(void *inptr, void *outptr, int width, int height, int min, int num)
{
    int *iptr = (int *)inptr;
    float *fptr = (float *)outptr;

    for(int i=0; i<width*height; i++)
    {
        float value = (float)iptr[i];
        float newvalue = ((value/16.0f) - min) / num;
        fptr[i] = newvalue;
    }
}

int main(int argc, char *argv[]) 
{
    int window_size = 3;
    int min_disp = 16;
    int num_disp = 112-min_disp;

    StereoSGBM sgbm = StereoSGBM(
         min_disp, // min_disp
         num_disp, // num_disp
         window_size, // SADWindowSize
         8*3*window_size*window_size, // P1
         32*3*window_size*window_size, // P2
         1, // disp12MaxDiff
         10, // uniquenessRatio
         100, // speckleWindowSize
         32, // speckleRange
         false // fullDP
         );

    Mat left = imread("aloeL.jpg", -1);
    Mat right = imread("aloeR.jpg", -1);
    Mat disparity, disparity8, disparity32;

    sgbm(left, right, disparity);
    disparity.convertTo(disparity32, CV_32F);
    bringWithinRange(disparity.ptr(), disparity32.ptr(), disparity.cols, disparity.rows, min_disp, num_disp);

    namedWindow("Disparity", 0);
    imshow("disparity", disparity32);
    waitKey();

    return 0;
}