'''
Simple example of stereo image matching and point cloud generation.
#!/usr/bin/env python
'''
Simple example of stereo image matching and point cloud generation.
Resulting .ply file cam be easily viewed using MeshLab ( http://meshlab.sourceforge.net/ )
'''
import numpy as np import cv2
ply_header = '''ply format ascii 1.0 element vertex %(vert_num)d property float x property float y property float z property uchar red property uchar green property uchar blue end_header '''
def write_ply(fn, verts, colors): verts = verts.reshape(-1, 3) colors = colors.reshape(-1, 3) verts = np.hstack([verts, colors]) with open(fn, 'w') as f: f.write(ply_header % dict(vert_num=len(verts))) np.savetxt(f, verts, '%f %f %f %d %d %d')
cap1 = cv2.VideoCapture(1) cap2 = cv2.VideoCapture(2)
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)
while( cap1.isOpened()) : #& cap2.isOpened() -----for second camera if __name__ == '__main__': #print 'loading images...' #imgL = cv2.pyrDown( cv2.imread('../gpu/aloeL.jpg') ) # downscale images for faster processing #imgR = cv2.pyrDown( cv2.imread('../gpu/aloeR.jpg') ) ret,L=cap1.read() ret,R=cap2.read() imgL = cv2.pyrDown(L,(320,240)) imgR = cv2.pyrDown(R,(320,240)) # disparity range is tuned for 'aloe' image pair
#print 'computing disparity...' disp = stereo.compute(imgL, imgR).astype(np.float32) / 16.0
print 'generating 3d point cloud...', h, w = imgL.shape[:2] f = 0.8*w # guess for focal length