def keep(in_nii, keep_labels, keep_csv_filename, out_filename): in_label_nii = labels.read_nifti_file(in_nii, 'Label file does not exist') in_label_array = in_label_nii.get_data() if len(keep_csv_filename): csv_keep_labels = labels.read_labels_from_csv(keep_csv_filename) else: csv_keep_labels = [] all_labels = set(labels.get_labels(None, in_label_array)) keep_labels = set( labels.get_labels(keep_labels + csv_keep_labels, in_label_array)) remove_labels = sorted(list(all_labels.symmetric_difference(keep_labels))) out_label_array = in_label_array for ii in remove_labels: mask = in_label_array == ii out_label_array[mask] = 0 nb.save(nb.Nifti1Image(out_label_array, None, in_label_nii.get_header()), out_filename)
def main(): # Parsing Arguments usage = "usage: %prog [options] arg1 arg2" parser = argparse.ArgumentParser(prog='iw_labels_otsu') parser.add_argument("in_labels", help="Filename of input labels") parser.add_argument("in_image", help="Filename of input labels") parser.add_argument("otsu_labels", help="Filename of output NII otsu mask") parser.add_argument("-v", "--verbose", help="Verbose flag", action="store_true", default=False) inArgs = parser.parse_args() in_label_nii = labels.read_nifti_file(inArgs.in_labels, 'Label file does not exist') in_label_array = in_label_nii.get_data() in_image_nii = labels.read_nifti_file(inArgs.in_image, 'Label file does not exist') in_image_array = in_image_nii.get_data() out_array_low = np.zeros(in_label_array.shape) out_array_high = np.zeros(in_label_array.shape) for ii in xrange(1, 4): ii_label_array = in_label_array[:, :, :, ii] ii_image_array = in_image_array[:, :, :, ii] ii_labels = labels.get_labels(None, ii_label_array) for jj in ii_labels: print ii, jj jj_mask = ndimage.binary_dilation(ii_label_array == jj) jj_image = jj_mask * ii_image_array val = filters.threshold_otsu(jj_image) jj_image_high = jj * (jj_image >= val) * jj_mask jj_image_low = jj * (jj_image < val ) * jj_mask out_array_low[:,:,:,ii] += jj_image_low out_array_high[:,:,:,ii] += jj_image_high nb.save(nb.Nifti1Image(out_array_low, in_image_nii.get_affine()), 'low.' + inArgs.otsu_labels) nb.save(nb.Nifti1Image(out_array_high, in_image_nii.get_affine()), 'high.' + inArgs.otsu_labels)
# in_label_nii = labels.read_nifti_file(inArgs.in_nii, 'Label file does not exist') in_label_array = in_label_nii.get_data() if inArgs.out_nii == None: out_filename = inArgs.in_nii else: out_filename = inArgs.out_nii if len(inArgs.csv): csv_remove_labels = labels.read_labels_from_csv(inArgs.csv) else: csv_remove_labels = [] remove_labels = labels.get_labels(inArgs.remove + csv_remove_labels, in_label_array) if inArgs.verbose: print sorted(inArgs.remove + csv_remove_labels) out_label_array = in_label_array for ii in remove_labels: mask = in_label_array == ii out_label_array[mask] = 0 nb.save(nb.Nifti1Image(out_label_array, None, in_label_nii.get_header()), out_filename)
def main(): ## Parsing Arguments # # usage = "usage: %prog [options] arg1 arg2" parser = argparse.ArgumentParser(prog='iw_compare_images') parser.add_argument("in_label_nii_filename", help="Label NIFTI filename ") parser.add_argument("in_label2_nii_filename", help="Label NIFTI filename ") parser.add_argument( "--out", help="Filename of CSV output file containing label stats", default=None) parser.add_argument("--stats", help="Stats to report", type=str, nargs="*", default=('volume', 'com_x', 'com_y', 'com_z', 'com_in', 'bb_dx', 'bb_dy', 'bb_dz', 'bb_dmin', 'bb_volume', 'fill_factor')) parser.add_argument("--labels", help="Label indices to analyze", type=int, nargs="*", default=None) parser.add_argument("--sort", help="Label indices to analyze", type=str, default='label') parser.add_argument("--limits_volume", help="Report labels within these limits", type=int, nargs=2, default=[0, numpy.inf]) parser.add_argument("--limits_fill_factor", help="Report labels within these limits", type=int, nargs=2, default=[0, 1.0]) parser.add_argument("--limits_bb_volume", help="Report labels within these limits", type=int, nargs=2, default=[0, numpy.inf]) parser.add_argument("--limits_background", help="Report background label (i.e label=0)", action="store_true", default=False) parser.add_argument("-d", "--display", help="Display Results", action="store_true", default=False) parser.add_argument("-v", "--verbose", help="Verbose flag", action="store_true", default=False) parser.add_argument("--verbose_nlines", help="Number of lines to display (default=10)", default=10) inArgs = parser.parse_args() label1_nii = labels.read_nifti_file(inArgs.in_label_nii_filename, 'Label file does not exist') label1_array = label1_nii.get_data() label2_nii = labels.read_nifti_file(inArgs.in_label2_nii_filename, 'Label file does not exist') label2_array = label2_nii.get_data() label1_list = labels.get_labels(inArgs.labels, label1_array, inArgs.limits_background) label2_list = labels.get_labels(None, label2_array, inArgs.limits_background) label1_dict = dict(zip(label1_list, range(0, len(label1_list)))) label2_dict = dict(zip(label2_list, range(0, len(label2_list)))) print label1_dict print label2_dict overlap_matrix = numpy.zeros([len(label1_list), len(label2_list)]) for ii in label1_list: mask1 = 1. * (label1_array == ii) ii_label2_list = numpy.unique(mask1 * label2_array) ii_label2_list = ii_label2_list[ii_label2_list > 0] for jj in ii_label2_list: mask2 = 1. * (label2_array == jj) overlap_matrix[label1_dict[ii], label2_dict[jj]] = numpy.sum(mask1 * mask2) print ii, label1_dict[ii], jj, label2_dict[jj], numpy.sum( mask1), numpy.sum(mask2), overlap_matrix[label1_dict[ii], label2_dict[jj]] overlap_matrix.tofile('overlap.csv', sep=',', format='%10.5f')
inArgs = parser.parse_args() if inArgs.debug: print "inArgs.in_nii = " + inArgs.in_nii print print "inArgs.debug = " + str(inArgs.debug) print "inArgs.verbose = " + str(inArgs.verbose) label_nii = labels.read_nifti_file( inArgs.in_nii, 'Label file does not exist' ) label_array = label_nii.get_data() labels = labels.get_labels( inArgs.labels, label_array) df_stats = pd.DataFrame(columns=('label', 'com_x', 'com_y', 'com_z', 'label_volume', 'ellipsoid_volume', 'center_x', 'center_y', 'center_z', 'r1', 'r2', 'r3', 'fa' )) if inArgs.stats is not None: stats_list = inArgs.stats else: stats_list = list(df_stats.columns.values) if inArgs.verbose: jj=0 pd.set_option('expand_frame_repr', False) for ii in labels:
def measure(in_label_nii_filename, labels, background, stats, out_filename, limits_volume_voxels=[0, numpy.inf], limits_bb_volume_voxels=[0, numpy.inf], limits_fill_factor=[0,1], sort='volume', verbose=False, verbose_nlines=20): label_nii = iw_labels.read_nifti_file( in_label_nii_filename, 'iw_label_stats.py: Label file does not exist. ') single_voxel_volume_mm3 = query_voxel_volume_mm3( label_nii ) label_array = label_nii.get_data() label_list = iw_labels.get_labels(labels, label_array, background) df_stats = pd.DataFrame(columns=( 'label', 'volume_voxels', 'volume_mm3', 'com_x', 'com_y', 'com_z', 'com_t', 'com_in', 'bb_dx', 'bb_dy', 'bb_dz', 'bb_dt', 'bb_dmin', 'bb_volume_voxels', 'fill_factor')) stats_list = ['label', ] + list(stats) if verbose: jj = 0 pd.set_option('expand_frame_repr', False) for ii in label_list: # Create logical mask mask = (label_array == ii) ndim = query_ndimensions(mask) # Calculate Volume label_volume_voxels = int(numpy.sum(mask)) label_volume_mm3 = single_voxel_volume_mm3 * label_volume_voxels if check_limits(label_volume_voxels, limits_volume_voxels): bb_dx, bb_dy, bb_dz, bb_dt, bb_dmin, bb_volume_voxels = calculate_bounding_box(mask) if check_limits(bb_volume_voxels, limits_bb_volume_voxels): label_x_com, label_y_com, label_z_com, label_t_com = calculate_center_of_mass(mask) if ndim == 4: label_com_in = mask[label_x_com, label_y_com, label_z_com, label_t_com] else: label_com_in = mask[label_x_com, label_y_com, label_z_com] fill_factor = label_volume_voxels / bb_volume_voxels if check_limits(fill_factor, limits_fill_factor): label_stats = [ii, label_volume_voxels, label_volume_mm3, label_x_com, label_y_com, label_z_com, label_t_com, label_com_in, bb_dx, bb_dy, bb_dz, bb_dt, bb_dmin, bb_volume_voxels, fill_factor] df_stats.loc[len(df_stats)] = label_stats if verbose: if jj == (verbose_nlines - 1): print df_verbose = df_stats.tail(verbose_nlines) df_verbose = df_verbose[stats_list] print df_verbose.to_string( formatters={'volume_voxels': '{:,.0f}'.format, 'volume_mm3': '{:,.3f}'.format, 'com_x': '{:,.0f}'.format, 'com_y': '{:,.0f}'.format, 'com_z': '{:,.0f}'.format, 'com_t': '{:,.0f}'.format, 'com_in': '{:,.0f}'.format, 'bb_dx': '{:,.0f}'.format, 'bb_dy': '{:,.0f}'.format, 'bb_dz': '{:,.0f}'.format, 'bb_dt': '{:,.0f}'.format, 'bb_volume_voxels': '{:,.0f}'.format, 'fill_factor': '{:,.3f}'.format } ) jj = 0 else: jj += 1 df_sorted = df_stats.sort_values([sort], ascending=[1]).reset_index(drop=True) if verbose: print print df_sorted[stats_list] print if not out_filename == None: df_sorted[stats_list].to_csv(out_filename, index=False)
import iwUtilities as util # # Main Function # if __name__ == "__main__": ## Parsing Arguments # # usage = "usage: %prog [options] arg1 arg2" parser = argparse.ArgumentParser(prog='iw_compare_images') parser.add_argument("in_nii", help="Filename of NIFTI input label ") parser.add_argument("--background", help="Include background label (i.e label=0)", action="store_true", default=False) inArgs = parser.parse_args() # in_label_nii = labels.read_nifti_file( inArgs.in_nii, 'Label file does not exist' ) labels = labels.get_labels( None, in_label_nii.get_data() , inArgs.background ) for ii in labels: print ii
def compare_images(label_nii_filename, image1_nii_filename, image2_nii_filename, requested_labels, min_volume, verbose_flag=False): import iw_labels as labels # Load arrays label_nii = labels.read_nifti_file(label_nii_filename, 'Label file does not exist') image1_nii = labels.read_nifti_file(image1_nii_filename, 'Image file does not exist') image2_nii = labels.read_nifti_file(image2_nii_filename, 'Image file does not exist') # System Checks to verify that the Array Size and Dimensions are compatible image1_array = image1_nii.get_data() image2_array = image2_nii.get_data() label_array = label_nii.get_data() labels.image_shape_check(image1_array) labels.image_shape_check(image2_array) if not image1_array.shape == image2_array.shape: sys.exit('Image arrays must have the same shape') if not len(label_array.shape) == 3: sys.exit('Only supports 3D label arrays') if not image1_array.shape[0:len(label_array.shape)] == label_array.shape: sys.exit( 'Image array and label array do not have the same voxel dimensions' ) # Find a set of acceptable labels label_list = labels.get_labels(requested_labels, label_array) # Permute array or expand so desired stats is along first dimension image1_array, nVolumes = labels.permute_image_array(image1_array) image2_array, nVolumes = labels.permute_image_array(image2_array) # Gather stats if inArgs.verbose: jj = 0 pd.set_option('expand_frame_repr', False) df_stats = pd.DataFrame(columns=('label', 'time_index', 'volume', 'boundary_mean1', 'boundary_std1', 'mean1', 'std1', 'boundary_mean2', 'boundary_std2', 'mean2', 'std2', 'scale', 'p_rel_scaled')) for ii, ii_label in enumerate(label_list): mask = label_array == ii_label boundary_mask = binary_dilation(mask, structure=np.ones((3, 3, 3))) boundary_mask -= mask label_volume = np.sum(mask[:]) for time in range(0, nVolumes): # Calculate signal intensity of boundary pixels boundary_image1_mean, boundary_image1_std, boundary_image1_min, boundary_image1_max = labels.individual_image_stats( image1_array[time][boundary_mask]) boundary_image2_mean, boundary_image2_std, boundary_image2_min, boundary_image2_max = labels.individual_image_stats( image2_array[time][boundary_mask]) scale = boundary_image1_mean / boundary_image2_mean # Scale image to match boundary pixels image1_mean, image1_std, image1_min, image1_max = labels.individual_image_stats( image1_array[time][mask]) image2_mean, image2_std, image2_min, image2_max = labels.individual_image_stats( scale * image2_array[time][mask]) # Calculate paired t-test from region of interest across two images t_rel, p_rel_scaled = stats.ttest_rel( image1_array[time][mask], scale * image2_array[time][mask]) # Save stats image_array_stats = [ ii_label, time, label_volume, boundary_image1_mean, boundary_image1_std, image1_mean, image1_std, boundary_image2_mean, boundary_image2_std, image2_mean, image2_std, scale, -np.log(p_rel_scaled) ] df_stats.loc[len(df_stats)] = image_array_stats if inArgs.verbose: if jj == (inArgs.verbose_nlines - 1): print df_verbose = df_stats.tail(inArgs.verbose_nlines) print df_verbose.to_string( formatters={ 'label': '{:,.0f}'.format, 'volume': '{:,.0f}'.format, 'time_index': '{:,.0f}'.format }) jj = 0 else: jj += 1 if inArgs.verbose: print print df_stats print return df_stats