def __init__(self, scalarName, volume): """ """ super(FyMapAction, self).__init__(scalarName) # load volume self._image = io.readImage(volume) self._imageHeader = self._image.header self._imageDimensions = self._image.shape[:3] self._imageSpacing = self._imageHeader.get_zooms()[:3]
def run(self, masterFile, inputFiles, outputDirectory, spacing, dimensions, likefreesurfer, nii): ''' Performs the equalization ''' # sanity checks outputDirectory = os.path.normpath(outputDirectory) # prepare the output directory if os.path.exists(outputDirectory): c.error('The output directory already exists!') c.error('Aborting..') sys.exit(2) # create the output directory os.mkdir(outputDirectory) # MASTER masterFile = os.path.normpath(masterFile) # read the master master = io.readImage(masterFile) c.info('MASTER IMAGE: ' + str(masterFile)) # INPUTS for i in range(len(inputFiles)): inputFiles[i] = os.path.normpath(inputFiles[i]) c.info('INPUT IMAGE ' + str(i + 1) + ': ' + str(inputFiles[i])) # print more info c.info('OUTPUT DIRECTORY: ' + str(outputDirectory)) if likefreesurfer: spacing = '1,1,1' dimensions = '256,256,256' if spacing != 'no': c.info('SET SPACINGS: ' + str(spacing)) if dimensions != 'no': c.info('SET DIMENSIONS: ' + str(dimensions)) # re-sample master to obtain an isotropic dataset master = self.aniso2iso(master, spacing, dimensions) masterFileBasename = os.path.split(masterFile)[1] masterFileBasenameWithoutExt = os.path.splitext(masterFileBasename)[0] if not nii: masterOutputFileName = os.path.join(outputDirectory, masterFileBasename) else: masterOutputFileName = os.path.join( outputDirectory, masterFileBasenameWithoutExt) + '.nii' io.saveImage(masterOutputFileName, master) # equalize all images to the master for i in range(len(inputFiles)): currentInputFile = inputFiles[i] c.info('Equalizing ' + str(currentInputFile) + ' to ' + str(masterFile) + "...") # load the image currentImage = io.readImage(currentInputFile) currentImageHeader = currentImage.header c.info(' old spacing: ' + str(currentImageHeader.get_zooms())) c.info(' old dimensions: ' + str(currentImage.shape[:3])) # now resample resampledImage = resampler.resample_img2img(currentImage, master) # .. and save it currentInputFileBasename = os.path.split(currentInputFile)[1] currentInputFileBasenameWithoutExt = os.path.splitext( currentInputFileBasename)[0] if not nii: outputFileName = os.path.join(outputDirectory, currentInputFileBasename) else: outputFileName = os.path.join( outputDirectory, currentInputFileBasenameWithoutExt) savedImage = io.saveImage(outputFileName, resampledImage) #c.info( ' new spacing: ' + str( savedImageHeader.get_zooms() ) ) c.info(' new dimensions: ' + str(savedImage.shape[:3])) c.info('All done!')
import sys import numpy # ENTRYPOINT if __name__ == "__main__": track = sys.argv[1] trackId = int(sys.argv[2]) volume = sys.argv[3] s = io.loadTrk(track) tracks = s[0] origHeader = s[1] image = io.readImage(volume) imageHeader = image.header imageDimensions = image.shape[:3] imageSpacing = imageHeader.get_zooms() singleTrack = tracks[trackId] coords = singleTrack[0] valueSum = 0 length = 0 _last = None for _current in coords: if _last != None: # we have the previous point
def validateMapping( volumefile, trkfile, radius=0, map_intermediate=True ): ''' Check if a trk file has correctly mapped scalar values from a volume file. If radius is > 0 take it into account by looking for the most common value in a sphere around the original point. This only happens on start and end points so. If map_intermediate is active, also the points between end points are validated but never using the radius. Returns TRUE if everything is fine, FALSE if there were errors. ''' # load the mapped trk file s = io.loadTrk( trkfile ) volume = io.readImage( volumefile ) imageHeader = volume.header image_size = volume.shape[:3] # grab the tracks tracks = s[0] # pad the image with zeros image = ap.pad( volume, radius, 'constant', constant_values=( 0 ) ) # any errors? any_errors = False # incorporate spacing spacing = imageHeader.get_zooms()[:3] # .. and loop through them for t in tracks: points = t[0] # the points of this fiber track scalars = t[1] # the mapped scalars for index, p in enumerate( points ): current_point = [ int( a / b ) for a, b in zip( [p[0], p[1], p[2]], spacing )] #print 'ORIG', volume[current_point[0], current_point[1], current_point[2]] is_first_point = ( index == 0 ) is_last_point = ( index == len( points ) - 1 ) # if this is if not map_intermediate and not is_first_point and not is_last_point: real_scalar = 0.0 else: # here we check for the neighborhood if radius > 0 if radius > 0 and ( is_first_point or is_last_point ): # neighborhood search! r = radius a, b, c = current_point # crop the image according to the neighborhood look-up # since we zero-padded the image, we don't need boundary checks here min_x = a - r max_x = a + r + 1 min_y = b - r max_y = b + r + 1 min_z = c - r max_z = c + r + 1 cropped_image = numpy.asarray( image[min_x + r:max_x + r, min_y + r:max_y + r, min_z + r:max_z + r] ) # create a sphere mask x, y, z = numpy.ogrid[0:2 * r + 1, 0:2 * r + 1, 0:2 * r + 1] mask = ( x - r ) ** 2 + ( y - r ) ** 2 + ( z - r ) ** 2 <= r * r # 3d sphere mask # apply the mask masked_container = cropped_image[mask] # throw away all zeros (0) masked_container = masked_container[numpy.nonzero( masked_container )] # find the most frequent label in the masked container from collections import Counter # by default, we use the original one mostFrequentLabel = volume[a, b, c] if len( masked_container ) != 0: counter = Counter( masked_container ) all_labels = counter.most_common() best_match_label = counter.most_common( 1 ) original_pos = [i for i, v in enumerate( all_labels ) if v[0] == mostFrequentLabel] if not original_pos or all_labels[original_pos[0]][1] != best_match_label[0][1]: # the original label appears less often as the new best_match_label # in this case, we use the new best matched label mostFrequentLabel = best_match_label[0][0] # we don't need an else here since the original label is already set real_scalar = mostFrequentLabel else: # simple mapping without radius incorporation and make sure we are inside the volume real_scalar = volume[min( current_point[0], image_size[0] - 1 ), min( current_point[1], image_size[1] - 1 ) , min( current_point[2], image_size[2] - 1 )] if type( scalars ) is types.NoneType: mapped_scalar = -1 else: mapped_scalar = scalars[index][0] # now check if the mapped scalar from the trk file matches the real scalar compare = ( mapped_scalar == real_scalar ) if compare: compare = Colors.GREEN + 'OK' else: compare = Colors.RED + 'WRONG!!!' any_errors = True print Colors.PURPLE + 'Probing ' + Colors.CYAN + str( current_point ) + Colors.PURPLE + ' for scalar.. SHOULD BE: ' + Colors.CYAN + str( real_scalar ) + Colors.PURPLE + ' WAS: ' + Colors.CYAN + str( mapped_scalar ) + Colors.PURPLE + ' ... ' + str( compare ) + Colors._CLEAR # return TRUE if everything went fine and FALSE if there were errors return not any_errors
# ENTRYPOINT if __name__ == "__main__": track = sys.argv[1] trackId = int( sys.argv[2] ) volume = sys.argv[3] s = io.loadTrk( track ) tracks = s[0] origHeader = s[1] image = io.readImage( volume ) imageHeader = image.header imageDimensions = image.shape[:3] imageSpacing = imageHeader.get_zooms() singleTrack = tracks[trackId] coords = singleTrack[0] valueSum = 0 length = 0 _last = None for _current in coords: if _last != None: # we have the previous point