def buildStack(token, channel, res):

  with closing (ocpcaproj.OCPCAProjectsDB()) as projdb:
    proj = projdb.loadToken(token)
  
  with closing (ocpcadb.OCPCADB(proj)) as db:

    ch = proj.getChannelObj(channel)
    high_res = proj.datasetcfg.scalinglevels
    for cur_res in range(res, high_res+1):

      # Get the source database sizes
      [[ximagesz, yimagesz, zimagesz], timerange] = proj.datasetcfg.imageSize(cur_res)
      [xcubedim, ycubedim, zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[cur_res]
      [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[cur_res]

      biggercubedim = [xcubedim*2,ycubedim*2,zcubedim]

      # Set the limits for iteration on the number of cubes in each dimension
      xlimit = (ximagesz-1) / xcubedim + 1
      ylimit = (yimagesz-1) / ycubedim + 1
      zlimit = (zimagesz-1) / zcubedim + 1

      for z in range(zlimit):
        for y in range(ylimit):
          for x in range(xlimit):

            # cutout the data at the -1 resolution
            olddata = db.cutout(ch, [ x*2*xcubedim, y*2*ycubedim, z*zcubedim], biggercubedim, cur_res-1 ).data
            # target array for the new data (z,y,x) order
            newdata = np.zeros([zcubedim,ycubedim,xcubedim], dtype=np.uint16)

            for sl in range(zcubedim):

              # Convert each slice to an image
              slimage = Image.frombuffer ( 'I;16', (xcubedim*2,ycubedim*2), olddata[sl,:,:].flatten(), 'raw', 'I;16', 0, 1 )

              # Resize the image
              newimage = slimage.resize ( [xcubedim,ycubedim] )
              
              # Put to a new cube
              newdata[sl,:,:] = np.asarray ( newimage )

            zidx = ocplib.XYZMorton ( [x,y,z] )
            cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType())
            cube.zeros()

            cube.data = newdata
            print "Inserting Cube {} at res {}".format(zidx, cur_res)
            db.putCube(ch, zidx, cur_res, cube, update=True)
Build the hierarchy of images
dataset/ETHPy150Open neurodata/ndstore/scripts/imgstack16.py/buildStack