def fill_buf(buf, i, img, shape):
    '''fill the ith grid of the buffer matrix with the values from the img
    buf : buffer matrix
    i : serial of the image in the 2D grid
    img : image data
    shape : ( height width depth ) of image'''

    # grid height is a multiple of individual image height
    m = buf.shape[0]/shape[0]

    sx = (i%m)*shape[1]
    sy = (i//m)*shape[0]
    sx = int(sx)
    sy = int(sy)
    buf[sy:sy+shape[0], sx:sx+shape[1], :] = img