def testOutput(self): it_in = minc.input_iterator_real(self.fname) it_out = minc.output_iterator_real(self.tmp, reference_file=self.fname) for i in it_in: it_out.value(i) it_out.next() # compare now del it_out del it_in _ref = minc.Image(self.fname).data _out = minc.Image(self.tmp).data self.assertTrue(np.allclose(_ref, _out))
def testMincType(self): for minctype in ('byte', 'short', 'int', 'float', 'double'): check_call_out([ 'mincreshape', '-' + minctype, '-clobber', self.fname, self.tmp ]) self.img = minc.Image(self.fname) self.assertAlmostEqual(np.median(self.img.data), 12.6001232)
def setUp(self): self.fname = os.path.join(DATA_PATH, ANAT_FILE) self.img = minc.Image(self.fname) self.fname_nan = os.path.join(DATA_PATH, ANAT_FILE) self.tmp = create_tmp_filename(prefix='mni_icbm152_', suffix='.mnc', remove=False)
def setUp(self): self.fname = os.path.join(DATA_PATH, ANAT_FILE_T2) self.fmask = os.path.join(DATA_PATH, MASK_FILE) self.masked_data = ma.masked_array(minc.Image(self.fname).data, mask=minc.Mask(self.fmask).data) self.tmp = create_tmp_filename(prefix='mni_icbm152_t2_', suffix='.mnc', remove=True)
def testHistory(self): img = minc.Image(self.fname) history = [ 'Thu Jul 30 14:23:47 2009>>> mincaverage -short mni_icbm152_t1_tal_nlin_sym_09c_.mnc mni_icbm152_t1_tal_nlin_sym_09c_flip_.mnc final/mni_icbm152_t1_tal_nlin_sym_09c.mnc', 'Thu Apr 1 15:39:40 2010>>> mincconvert ./mni_icbm152_t1_tal_nlin_sym_09c.mnc ./mni_icbm152_t1_tal_nlin_sym_09c.mnc.minc1', 'Mon Aug 13 12:55:20 2018>>> mincresample -nearest -like test/data/atlas_csf.mnc /data/vfonov/models/icbm152_model_09c/mni_icbm152_t1_tal_nlin_sym_09c.mnc test/data/mri_t1.mnc' ] self.assertEqual(img.history, history)
def _run_interface(self, runtime): if not isdefined(self.inputs.out_file): fname = os.path.splitext(os.path.basename(self.inputs.in_file))[0] dname = os.getcwd() #os.path.dirname(self.inputs.nativeT1) self.inputs.out_file = dname + os.sep + fname + self._suffix try: os.remove(self.inputs.out_file) except OSError: pass class InfoOptions: def __init__(self, command, variable, attribute, type_): self.command = command self.variable = variable self.attribute = attribute self.type_ = type_ temp_out_file = os.getcwd() + os.sep + "temp.json" try: img = pyezminc.Image(self.inputs.in_file, metadata_only=True) hd = img.get_MINC_header() for key in hd.keys(): self._params[key] = {} for subkey in hd[key].keys(): self._params[key][subkey] = {} data_in = hd[key][subkey] var = str(key) attr = str(subkey) #Populate dictionary with some useful image parameters (e.g., world coordinate start values of dimensions) self._params[key][subkey] = data_in update_minchd_json(temp_out_file, data_in, var, attr) except RuntimeError: print("Warning: Could not read header file from", self.inputs.in_file) header = json.load(open(temp_out_file, "r+")) minc_input = True if not isdefined(self.inputs.json_header): print("Error: could not find json file", self.inputs.json_header) exit(1) json_header = json.load(open(self.inputs.json_header, "r+")) header.update(json_header) minc_input = False header = set_frame_duration(header, minc_input) header = set_isotope_halflife(header, self.inputs.halflife, 'halflife') fp = open(self.inputs.out_file, "w+") fp.seek(0) json.dump(header, fp, sort_keys=True, indent=4) fp.close() self._params = header return runtime
def setUp(self): self.fname = os.path.join(DATA_PATH, 'mni_icbm152_t1_tal_nlin_sym_09c.mnc') self.img = minc.Image(self.fname) self.fname_nan = os.path.join(DATA_PATH, 'mni_icbm152_t1_tal_nlin_sym_09c.mnc') self.tmp = create_tmp_filename(prefix='mni_icbm152_', suffix='.mnc', remove=False)
def setUp(self): self.fname = os.path.join(DATA_PATH, 'mni_icbm152_t2_tal_nlin_sym_09c.mnc') self.fmask = os.path.join(DATA_PATH, 'mni_icbm152_t1_tal_nlin_sym_09c_mask.mnc') self.masked_data = ma.masked_array(minc.Image(self.fname).data, mask=minc.Mask(self.fmask).data) self.tmp = create_tmp_filename(prefix='mni_icbm152_t2_', suffix='.mnc', remove=True)
def mnc2nii(input_fn): '''For a MINC input file, returns a nibabel nifti image. This image can then be saved as a nifti file.''' img_mnc = pyezminc.Image(fname=input_fn) #Create empty instance of a Nibabel image img_nii = nib.Nifti1Image(img_mnc.data, np.eye(4)) for space, row in zip(['xspace', 'yspace', 'zspace'], ['srow_x', 'srow_y', 'srow_z']): img_nii.header[row] = img_mnc.header[space][ 'direction_cosines'] + img_mnc.header[space]['start'] affine = [ img_nii.header['srow_x'], img_nii.header['srow_y'], img_nii.header['srow_z'], [0, 0, 0, 1] ] #Return data structure, data, header, affine return (img_nii) #, img_mnc.data, img_nii.header, affine )
def load_from_csv(self, fname): with open(fname, 'rb') as f: ll = list(csv.reader(f)) _data = [] _target = [] self.ids = [] self.thumbnails = [] for j, i in enumerate(ll): _img = minc.Image(i[0]) _data.append(np.ravel(_img.data)) _target.append(j) self.ids.append(i[1]) self.thumbnails.append( np.flipud( np.clip( scipy.ndimage.interpolation.zoom( _img.data[_img.data.shape[0] / 2, :, :], 0.4), 0, 120))) self.data = np.vstack(tuple(_data)) self.target = np.ravel(_target) # ravel?
return options if __name__ == "__main__": history = minc.format_history(sys.argv) options = parse_options() #print(repr(options)) # load prior and input image if (options.prior is not None or options.load is not None) and options.image is not None: if options.debug: print("Loading images...") images = [minc.Image(i).data for i in options.image] if options.coord: # add features dependant on coordinates c = np.mgrid[0:images[0].shape[0], 0:images[0].shape[1], 0:images[0].shape[2]] # use with center at 0 and 1.0 at the edge, could have used preprocessing images.append( (c[0] - images[0].shape[0] / 2.0) / (images[0].shape[0] / 2.0)) images.append( (c[1] - images[0].shape[1] / 2.0) / (images[0].shape[1] / 2.0)) images.append( (c[2] - images[0].shape[2] / 2.0) / (images[0].shape[1] / 2.0)) mask = None
def testLoadNan(self): with self.assertRaises(Exception): img = minc.Image(self.fname_nan)
def testLoadNan(self): with self.assertRaises(Exception): img = minc.Image(os.path.join(DATA_PATH, NAN_FILE))
def testHistory(self): img = minc.Image(self.fname) history = [ 'Thu Jul 30 14:23:47 2009>>> mincaverage -short mni_icbm152_t1_tal_nlin_sym_09c_.mnc mni_icbm152_t1_tal_nlin_sym_09c_flip_.mnc final/mni_icbm152_t1_tal_nlin_sym_09c.mnc' ] self.assertEqual(img.history, history)
def testLoad(self): img = minc.Image() img.load(self.fname) self.assertTrue(isinstance(img.data, np.ndarray))
return options if __name__ == "__main__": history = minc.format_history(sys.argv) options = parse_options() #print(repr(options)) patch_size = options.neighbours # load prior and input image if (options.prior is not None or options.load is not None) and options.image is not None: if options.debug: print("Loading images...") # convert to float as we go images = [minc.Image(i).data.astype(np.float32) for i in options.image] input_images = len(images) if options.neighbours is not None: for i in range(input_images): for x in range(-patch_size, patch_size + 1): for y in range(-patch_size, patch_size + 1): for z in range(-patch_size, patch_size + 1): if not (x == 0 and y == 0 and z == 0): # skip the central voxel images.append( np.roll(np.roll(np.roll(images[i], shift=x, axis=0), shift=y, axis=1), shift=z,
def _run_interface(self, runtime): if not isdefined(self.inputs.out_file): fname = os.path.splitext(os.path.basename(self.inputs.in_file))[0] dname = os.getcwd() #os.path.dirname(self.inputs.nativeT1) self.inputs.out_file = dname + os.sep + fname + self._suffix try: os.remove(self.inputs.out_file) except OSError: pass #pettot1_4d_header_fixed = pe.Node(interface=FixHeaderCommand(), name="pettot1_4d_header_fixed") #pettot1_4d_header_fixed.inputs.time_only=True #pettot1_4d_header_fixed.inputs.in_file = fixIrregular.inputs.out_file #pettot1_4d_header_fixed.inputs.header = self.inputs.header class InfoOptions: def __init__(self, command, variable, attribute, type_): self.command = command self.variable = variable self.attribute = attribute self.type_ = type_ #options = [ InfoOptions('-dimnames','time','dimnames','string'), # InfoOptions('-varvalue time','time','frames-time','integer'), # InfoOptions('-varvalue time-width','time','frames-length','integer') ] temp_out_file = os.getcwd() + os.sep + "temp.json" #for opt in options: # run_mincinfo=InfoCommand() # run_mincinfo.inputs.in_file = self.inputs.in_file # run_mincinfo.inputs.out_file = temp_out_file # run_mincinfo.inputs.opt_string = opt.command # run_mincinfo.inputs.json_var = opt.variable # run_mincinfo.inputs.json_attr = opt.attribute # run_mincinfo.inputs.json_type = opt.type_ # run_mincinfo.inputs.error = 'unknown' # print run_mincinfo.cmdline # if self.inputs.run: # run_mincinfo.run() img = pyezminc.Image(self.inputs.in_file, metadata_only=True) hd = img.get_MINC_header() for key in hd.keys(): self._params[key] = {} for subkey in hd[key].keys(): self._params[key][subkey] = {} data_in = hd[key][subkey] var = str(key) attr = str(subkey) #Populate dictionary with some useful image parameters (e.g., world coordinate start values of dimensions) self._params[key][subkey] = data_in update_minchd_json(temp_out_file, data_in, var, attr) header = json.load(open(temp_out_file, "r")) #fp.close() minc_input = True if not isdefined(self.inputs.json_header): print("Error: could not find json file", self.inputs.json_header) exit(1) print("\n\nMINC INPUT =", minc_input, self.inputs.json_header) json_header = json.load(open(self.inputs.json_header, "r+")) header.update(json_header) minc_input = False header = set_frame_duration(header, minc_input) header = set_isotope_halflife(header, self.inputs.halflife, 'halflife') fp = open(self.inputs.out_file, "w+") fp.seek(0) json.dump(header, fp, sort_keys=True, indent=4) fp.close() self._params = header return runtime
})) plt.register_cmap(cmap=colors.LinearSegmentedColormap( 'blue', { 'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'alpha': ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0)) })) if __name__ == "__main__": options = parse_options() register_custom_maps() _img = minc.Image(options.input) _idata = _img.data data_shape = _img.data.shape _ovl = None _odata = None omin = 0 omax = 1 if options.overlay is not None: _ovl = minc.Image(options.overlay) if _ovl.data.shape != data_shape: print("Overlay shape does not match image!\nOvl={} Image={}", repr(_ovl.data.shape), repr(data_shape)) exit(1) if options.orange is None:
return options if __name__ == "__main__": history = minc.format_history(sys.argv) options = parse_options() # load prior and input image if (options.prior is not None or options.load is not None) and options.image is not None: if options.debug: print("Loading images...") # convert to float as we go #images= [ minc.Image(i).data.astype(np.float32) for i in options.image ] image = minc.Image(options.image).data.astype(np.float32) if options.debug: print("Done") clf = None if options.load is not None: #TODO: load classifications pass else: prior = minc.Label(options.prior) labels = list(np.unique(prior.data)) counts = list(np.bincount(np.ravel(prior.data))) if 0 in labels:
help='Provide random state if needed') options = parser.parse_args() return options if __name__ == "__main__": history = minc.format_history(sys.argv) options = parse_options() if options.image is not None: if options.debug: print("Loading images...") images = [minc.Image(i).data for i in options.image] if options.patch > 0: input_images = len(images) for i in range(input_images): for x in range(-options.patch, options.patch + 1): for y in range(-options.patch, options.patch + 1): for z in range(-options.patch, options.patch + 1): if not (x == 0 and y == 0 and z == 0): images.append( np.roll(np.roll(np.roll(images[i], shift=x, axis=0), shift=y, axis=1),
return options if __name__ == "__main__": history = minc.format_history(sys.argv) options = parse_options() # load prior and input image if (options.prior is not None or options.load is not None) and options.image is not None: if options.debug: print("Loading images...") # convert to float as we go #images= [ minc.Image(i).data.astype(np.float32) for i in options.image ] image = minc.Image(options.image).data.astype(np.float32) nvoxels = image.shape[0] * image.shape[1] * image.shape[2] if options.debug: print("Done") clf = None if options.load is not None: #TODO: load classifications pass else: prior = minc.Label(options.prior) labels = list(np.unique(prior.data)) counts = list(np.bincount(np.ravel(prior.data)))
training_output=[] training_err=[] #go over training samples clf=None #scaler=preprocessing.StandardScaler().fit(X) for (i,inp) in enumerate(train): mask =minc.Label( inp[-3] ).data ground=minc.Label( inp[-2] ).data auto =minc.Label( inp[-1] ).data # normalize input features to zero mean and unit std if options.normalize: images=[ preprocessing.scale(minc.Image(k).data) for k in inp[0:-3] ] else: images=[ minc.Image(k).data for k in inp[0:-3] ] # store training data training_images.append( prepare_features( options, images, None, auto, mask ) ) # perform direct learning right now training_output.append( ground[mask>0] ) # dump first dataset for debugging if i == 0 and options.dump: print "Dumping feature images..." for (j,k) in enumerate( training_images[-1] ): test=np.zeros_like( images[0] ) test[ mask>0 ]=k
#ret=coeff[0] ret=vals*coeff[1]+coeff[0] for i in range(2,coeff.get_shape()[0]): ret=ret+tf.pow(vals,i)*coeff[i] return ret if __name__ == "__main__": history=minc.format_history(sys.argv) options = parse_options() # load prior and input image if options.debug: print("Loading images...") # convert to float as we go ref_image=minc.Image(options.reference).data.astype(np.float32) image=minc.Image(options.image).data.astype(np.float32) if options.debug: print("Done") mm=(image>0) if options.mask is not None: mask = minc.Label(options.mask) mm = np.logical_and(image>0 , mask.data>0 ) rmm=(ref_image>0) if options.refmask is not None: refmask = minc.Label(options.refmask) rmm = np.logical_and(ref_image>0 , refmask.data>0 ) #print ref_image[rmm]
n_i = -1 for i in train_library: if n_i == -1: n_i = len(i) - 1 elif n_i != (len(i) - 1): raise "Inconsistent number of images:{}".format(repr(i)) if n_i == -1: raise "No input images!" if options.debug: print("Loading {} images ...".format(n_i * len(train_library))) images = [[ minc.Image(os.path.join(prefix, j[i])).data for i in range(n_i) ] for j in train_library] segs = [ minc.Label(os.path.join(prefix, j[n_i])).data for j in train_library ] priors = [] # TODO: check shape of all images for consistency _shape = images[0][0].shape if options.coord: # add features dependant on coordinates c = np.mgrid[0:_shape[0], 0:_shape[1], 0:_shape[2]] # use with center at 0 and 1.0 at the edge, could have used preprocessing priors.append((c[0] - _shape[0] / 2.0) / (_shape[0] / 2.0))