mask_labeled, mask_num = ni.label(mask_bin)
    curr_mask_dict = ia.get_masks(labeled=mask_labeled,
                                  keyPrefix='caiman_mask_{:03d}'.format(i),
                                  labelLength=5)
    for roi_key, roi_mask in curr_mask_dict.items():
        final_roi_dict.update({roi_key: ia.WeightedROI(roi_mask * mask)})

print('Total number of ROIs:', len(final_roi_dict))

f = plt.figure(figsize=(15, 8))
ax1 = f.add_subplot(121)
ax1.imshow(bg, vmin=0, vmax=0.5, cmap='gray', interpolation='nearest')
colors1 = pt.random_color(masks.shape[0])
for i, mask in enumerate(masks):
    pt.plot_mask_borders(mask, plotAxis=ax1, color=colors1[i])
ax1.set_title('original ROIs')
ax1.set_axis_off()
ax2 = f.add_subplot(122)
ax2.imshow(ia.array_nor(bg),
           vmin=0,
           vmax=0.5,
           cmap='gray',
           interpolation='nearest')
colors2 = pt.random_color(len(final_roi_dict))
i = 0
for roi in final_roi_dict.values():
    pt.plot_mask_borders(roi.get_binary_mask(), plotAxis=ax2, color=colors2[i])
    i = i + 1
ax2.set_title('filtered ROIs')
ax2.set_axis_off()
Ejemplo n.º 2
0
def run():
    isSave = True

    filter_sigma = 2.  # 2. for soma, 1. for bouton
    thr_high = 0.0
    thr_low = 0.1

    bg_fn = "corrected_mean_projections.tif"
    save_folder = 'figures'

    curr_folder = os.path.dirname(os.path.realpath(__file__))
    os.chdir(curr_folder)

    data_f = h5py.File('caiman_segmentation_results.hdf5', 'r')
    masks = data_f['masks'].value
    data_f.close()

    bg = ia.array_nor(np.max(tf.imread(bg_fn), axis=0))

    final_roi_dict = {}

    roi_ind = 0
    for i, mask in enumerate(masks):
        mask_dict = hl.threshold_mask_by_energy(mask,
                                                sigma=filter_sigma,
                                                thr_high=thr_high,
                                                thr_low=thr_low)
        for mask_roi in mask_dict.values():
            final_roi_dict.update({'roi_{:04d}'.format(roi_ind): mask_roi})
            roi_ind += 1

    print('Total number of ROIs:', len(final_roi_dict))

    f = plt.figure(figsize=(15, 8))
    ax1 = f.add_subplot(121)
    ax1.imshow(bg, vmin=0, vmax=0.5, cmap='gray', interpolation='nearest')
    colors1 = pt.random_color(masks.shape[0])
    for i, mask in enumerate(masks):
        pt.plot_mask_borders(mask, plotAxis=ax1, color=colors1[i])
    ax1.set_title('original ROIs')
    ax1.set_axis_off()
    ax2 = f.add_subplot(122)
    ax2.imshow(ia.array_nor(bg),
               vmin=0,
               vmax=0.5,
               cmap='gray',
               interpolation='nearest')
    colors2 = pt.random_color(len(final_roi_dict))
    i = 0
    for roi in final_roi_dict.values():
        pt.plot_mask_borders(roi.get_binary_mask(),
                             plotAxis=ax2,
                             color=colors2[i])
        i = i + 1
    ax2.set_title('filtered ROIs')
    ax2.set_axis_off()
    # plt.show()

    if isSave:

        if not os.path.isdir(save_folder):
            os.makedirs(save_folder)

        f.savefig(os.path.join(save_folder,
                               'caiman_segmentation_filtering.pdf'),
                  dpi=300)

        cell_file = h5py.File('cells.hdf5', 'w')

        i = 0
        for key, value in sorted(final_roi_dict.items()):
            curr_grp = cell_file.create_group('cell{:04d}'.format(i))
            curr_grp.attrs['name'] = key
            value.to_h5_group(curr_grp)
            i += 1

        cell_file.close()
def run():

    curr_folder = os.path.dirname(os.path.realpath(__file__))
    os.chdir(curr_folder)

    print('getting total mask ...')
    cell_f = h5py.File('cells_refined.hdf5', 'r')
    h, w = cell_f['cell0000']['roi'].attrs['dimension']
    total_mask = np.zeros((h, w), dtype=np.uint8)
    for cell_n, cell_grp in cell_f.items():
        curr_roi = ia.WeightedROI.from_h5_group(cell_grp['roi'])
        curr_mask = curr_roi.get_binary_mask()
        total_mask = np.logical_or(total_mask, curr_mask)
    cell_f.close()
    total_mask = ni.binary_dilation(total_mask, iterations=1)
    # plt.imshow(total_mask)
    # plt.title('total_mask')
    # plt.show()

    nwb_folder = os.path.dirname(curr_folder)
    nwb_fn = [f for f in os.listdir(nwb_folder) if f[-4:] == '.nwb'][0]
    nwb_path = os.path.join(nwb_folder, nwb_fn)

    plane_n = os.path.split(curr_folder)[1]
    dset_path = 'processing/motion_correction/MotionCorrection/{}/corrected/data'.format(
        plane_n)

    print('downsampling movie ...')
    print('\tnwb_path: {}'.format(nwb_path))
    print('\tdset_path: {}'.format(dset_path))

    nwb_f = h5py.File(nwb_path, 'r')
    dset = nwb_f[dset_path]
    print('\ttotal shape: {}'.format(dset.shape))
    nwb_f.close()

    mov_d = downsample_mov(nwb_path=nwb_path,
                           dset_path=dset_path,
                           dr=downsample_r)
    v_min = np.amin(mov_d)
    v_max = np.amax(mov_d)
    print('\tshape of downsampled movie: {}'.format(mov_d.shape))

    print('\n\tgenerating avi ...')

    if cv2.__version__[0:3] == '3.1' or cv2.__version__[0] == '4':
        codex = 'XVID'
        fourcc = cv2.VideoWriter_fourcc(*codex)
        out = cv2.VideoWriter('marked_mov.avi',
                              fourcc,
                              30, (frame_size * 100, frame_size * 100),
                              isColor=True)
    elif cv2.__version__[0:6] == '2.4.11':
        out = cv2.VideoWriter('marked_mov.avi',
                              -1,
                              30, (frame_size * 100, frame_size * 100),
                              isColor=True)
    elif cv2.__version__[0:3] == '2.4':
        codex = 'XVID'
        fourcc = cv2.cv.CV_FOURCC(*codex)
        out = cv2.VideoWriter('marked_mov.avi',
                              fourcc,
                              30, (frame_size * 100, frame_size * 100),
                              isColor=True)
    else:
        raise EnvironmentError(
            'Do not understand opencv cv2 version: {}.'.format(
                cv2.__version__))

    f = plt.figure(figsize=(frame_size, frame_size))
    for frame_i, frame in enumerate(mov_d):
        print('\tframe: {} / {}'.format(frame_i, mov_d.shape[0]))
        f.clear()
        ax = f.add_subplot(111)
        ax.imshow(frame,
                  vmin=v_min,
                  vmax=v_max * 0.5,
                  cmap='gray',
                  interpolation='nearest')
        pt.plot_mask_borders(total_mask,
                             plotAxis=ax,
                             color='#ff0000',
                             zoom=1,
                             borderWidth=1)
        ax.set_aspect('equal')
        # plt.show()

        buffer_ = io.BytesIO()
        pt.save_figure_without_borders(f, buffer_, dpi=100)
        buffer_.seek(0)
        image = PIL.Image.open(buffer_)
        curr_frame = np.asarray(image)
        r, g, b, a = np.rollaxis(curr_frame, axis=-1)
        curr_frame = (np.dstack((b, g, r)))
        # print(r.dtype)
        # print(curr_frame.shape)

        out.write(curr_frame)

    out.release()
    cv2.destroyAllWindows()
    print('\t.avi movie generated.')
def run():
    data_file_name = 'cells_refined.hdf5'
    background_file_name = "corrected_mean_projections.tif"
    save_folder = 'figures'

    overlap_threshold = 0.9
    surround_limit = [1, 8]

    curr_folder = os.path.dirname(os.path.realpath(__file__))
    os.chdir(curr_folder)

    if not os.path.isdir(save_folder):
        os.makedirs(save_folder)

    print('reading cells file ...')
    data_f = h5py.File(data_file_name, 'r')

    cell_ns = data_f.keys()
    cell_ns.sort()

    binary_mask_array = []
    weight_mask_array = []

    for cell_n in cell_ns:
        curr_roi = ia.ROI.from_h5_group(data_f[cell_n]['roi'])
        binary_mask_array.append(curr_roi.get_binary_mask())
        weight_mask_array.append(curr_roi.get_weighted_mask())

    data_f.close()
    binary_mask_array = np.array(binary_mask_array)
    weight_mask_array = np.array(weight_mask_array)
    print('starting mask_array shape:', weight_mask_array.shape)

    print('getting total mask ...')
    total_mask = np.zeros((binary_mask_array.shape[1], binary_mask_array.shape[2]), dtype=np.uint8)
    for curr_mask in binary_mask_array:
        total_mask = np.logical_or(total_mask, curr_mask)
    total_mask = np.logical_not(total_mask)

    plt.imshow(total_mask, interpolation='nearest')
    plt.title('total_mask')
    # plt.show()

    print('getting and surround masks ...')
    binary_surround_array = []
    for binary_center in binary_mask_array:
        curr_surround = np.logical_xor(ni.binary_dilation(binary_center, iterations=surround_limit[1]),
                                       ni.binary_dilation(binary_center, iterations=surround_limit[0]))
        curr_surround = np.logical_and(curr_surround, total_mask).astype(np.uint8)
        binary_surround_array.append(curr_surround)
        # plt.imshow(curr_surround)
        # plt.show()
    binary_surround_array = np.array(binary_surround_array)

    print("saving rois ...")
    center_areas = []
    surround_areas = []
    for mask_ind in range(binary_mask_array.shape[0]):
        center_areas.append(np.sum(binary_mask_array[mask_ind].flat))
        surround_areas.append(np.sum(binary_surround_array[mask_ind].flat))
    roi_f = h5py.File('rois_and_traces.hdf5')
    roi_f['masks_center'] = weight_mask_array
    roi_f['masks_surround'] = binary_surround_array

    roi_f.close()
    print('minimum surround area:', min(surround_areas), 'pixels.')

    f = plt.figure(figsize=(10, 10))
    ax_center = f.add_subplot(211)
    ax_center.hist(center_areas, bins=30)
    ax_center.set_title('roi center area distribution')
    ax_surround = f.add_subplot(212)
    ax_surround.hist(surround_areas, bins=30)
    ax_surround.set_title('roi surround area distribution')
    # plt.show()

    print('plotting ...')
    colors = pt.random_color(weight_mask_array.shape[0])
    bg = ia.array_nor(np.max(tf.imread(background_file_name), axis=0))

    f_c_bg = plt.figure(figsize=(10, 10))
    ax_c_bg = f_c_bg.add_subplot(111)
    ax_c_bg.imshow(bg, cmap='gray', vmin=0, vmax=0.5, interpolation='nearest')
    f_c_nbg = plt.figure(figsize=(10, 10))
    ax_c_nbg = f_c_nbg.add_subplot(111)
    ax_c_nbg.imshow(np.zeros(bg.shape,dtype=np.uint8),vmin=0,vmax=1,cmap='gray',interpolation='nearest')
    f_s_nbg = plt.figure(figsize=(10, 10))
    ax_s_nbg = f_s_nbg.add_subplot(111)
    ax_s_nbg.imshow(np.zeros(bg.shape,dtype=np.uint8),vmin=0,vmax=1,cmap='gray',interpolation='nearest')

    i = 0
    for mask_ind in range(binary_mask_array.shape[0]):
        pt.plot_mask_borders(binary_mask_array[mask_ind], plotAxis=ax_c_bg, color=colors[i], borderWidth=1)
        pt.plot_mask_borders(binary_mask_array[mask_ind], plotAxis=ax_c_nbg, color=colors[i], borderWidth=1)
        pt.plot_mask_borders(binary_surround_array[mask_ind], plotAxis=ax_s_nbg, color=colors[i], borderWidth=1)
        i += 1

    # plt.show()

    print('saving figures ...')
    pt.save_figure_without_borders(f_c_bg, os.path.join(save_folder, '2P_ROIs_with_background.png'), dpi=300)
    pt.save_figure_without_borders(f_c_nbg, os.path.join(save_folder, '2P_ROIs_without_background.png'), dpi=300)
    pt.save_figure_without_borders(f_s_nbg, os.path.join(save_folder, '2P_ROI_surrounds_background.png'), dpi=300)
    f.savefig(os.path.join(save_folder, 'roi_area_distribution.pdf'), dpi=300)