Example #1
0
def apply_shifts_to_binary(ops, offsets, reg_file_alt, raw_file_alt):
    ''' apply registration shifts to binary data'''
    nbatch = ops['batch_size']
    Ly = ops['Ly']
    Lx = ops['Lx']
    nbytesread = 2 * Ly * Lx * nbatch
    ix = 0
    meanImg = np.zeros((Ly, Lx))
    k = 0
    t0 = time.time()
    if len(raw_file_alt) > 0:
        reg_file_alt = open(reg_file_alt, 'wb')
        raw_file_alt = open(raw_file_alt, 'rb')
        raw = True
    else:
        reg_file_alt = open(reg_file_alt, 'r+b')
        raw = False
    while True:
        if raw:
            buff = raw_file_alt.read(nbytesread)
        else:
            buff = reg_file_alt.read(nbytesread)

        data = np.frombuffer(buff, dtype=np.int16, offset=0).copy()
        buff = []
        if (data.size == 0) | (ix >= ops['nframes']):
            break
        data = np.reshape(
            data[:int(np.floor(data.shape[0] / Ly / Lx) * Ly * Lx)],
            (-1, Ly, Lx))
        nframes = data.shape[0]
        iframes = ix + np.arange(0, nframes, 1, int)

        # get shifts
        ymax, xmax = offsets[0][iframes].astype(
            np.int32), offsets[1][iframes].astype(np.int32)
        ymax1, xmax1 = [], []
        if ops['nonrigid']:
            ymax1, xmax1 = offsets[3][iframes], offsets[4][iframes]

        # apply shifts
        data = apply_shifts(data, ops, ymax, xmax, ymax1, xmax1)
        data = np.minimum(data, 2**15 - 2)
        meanImg += data.mean(axis=0)
        data = data.astype('int16')
        # write to binary
        if not raw:
            reg_file_alt.seek(-2 * data.size, 1)
        reg_file_alt.write(bytearray(data))

        # write registered tiffs
        if ops['reg_tif_chan2']:
            tiff.write(data, ops, k, False)
        ix += nframes
        k += 1
    if ops['functional_chan'] != ops['align_by_chan']:
        ops['meanImg'] = meanImg / k
    else:
        ops['meanImg_chan2'] = meanImg / k
    print('Registered second channel in %0.2f sec.' % (time.time() - t0))

    reg_file_alt.close()
    if raw:
        raw_file_alt.close()
    return ops
Example #2
0
def register_binary_to_ref(ops, refImg, reg_file_align, raw_file_align):
    """ register binary data to reference image refImg

    Parameters
    ----------
    ops : dictionary

    refImg : int16
        reference image

    reg_file_align : string
        file to (read if raw_file_align empty, and) write registered binary to

    raw_file_align : string
        file to read raw binary from (if not empty)

    Returns
    -------
    ops : dictionary
        sets 'meanImg' or 'meanImg_chan2'
        maskMul, maskOffset, cfRefImg (see register.prepare_masks for details)

    offsets : list
        [ymax, xmax, cmax, yxnr] <- shifts and correlations
    """
    offsets = utils.init_offsets(ops)
    refAndMasks = prepare_refAndMasks(refImg, ops)

    nbatch = ops['batch_size']
    Ly = ops['Ly']
    Lx = ops['Lx']
    nbytesread = 2 * Ly * Lx * nbatch
    if len(raw_file_align) > 0:
        raw = True
    else:
        raw = False
        #raw = 'keep_movie_raw' in ops and ops['keep_movie_raw'] and 'raw_file' in ops and os.path.isfile(ops['raw_file'])
    if raw:
        reg_file_align = open(reg_file_align, 'wb')
        raw_file_align = open(raw_file_align, 'rb')
    else:
        reg_file_align = open(reg_file_align, 'r+b')

    meanImg = np.zeros((Ly, Lx))
    k = 0
    nfr = 0
    t0 = time.time()
    while True:
        if raw:
            buff = raw_file_align.read(nbytesread)
        else:
            buff = reg_file_align.read(nbytesread)
        data = np.frombuffer(buff, dtype=np.int16, offset=0).copy()
        buff = []
        if (data.size == 0) | (nfr >= ops['nframes']):
            break
        data = np.float32(np.reshape(data, (-1, Ly, Lx)))

        dout = compute_motion_and_shift(data, refAndMasks, ops)
        data = np.minimum(dout[0], 2**15 - 2)
        meanImg += data.sum(axis=0)
        data = data.astype('int16')

        # write to reg_file_align
        if not raw:
            reg_file_align.seek(-2 * data.size, 1)
        reg_file_align.write(bytearray(data))

        # compile offsets (dout[1:])
        for n in range(len(dout) - 1):
            if n < 3:
                offsets[n] = np.hstack((offsets[n], dout[n + 1]))
            else:
                # add on nonrigid stats
                for m in range(len(dout[-1])):
                    offsets[n + m] = np.vstack((offsets[n + m], dout[-1][m]))

        # write registered tiffs
        if ops['reg_tif']:
            tiff.write(data, ops, k, True)

        nfr += data.shape[0]
        k += 1
        if k % 5 == 0:
            print('%d/%d frames, %0.2f sec.' %
                  (nfr, ops['nframes'], time.time() - t0))

    print('%d/%d frames, %0.2f sec.' % (nfr, ops['nframes'], time.time() - t0))

    # mean image across all frames
    if ops['nchannels'] == 1 or ops['functional_chan'] == ops['align_by_chan']:
        ops['meanImg'] = meanImg / ops['nframes']
    else:
        ops['meanImg_chan2'] = meanImg / ops['nframes']

    reg_file_align.close()
    if raw:
        raw_file_align.close()
    return ops, offsets