Example #1
0
def main():
	i1, h1 = load(sys.argv[1])
	i2, h2 = load(sys.argv[2])

	# shift image to align origins
	origin_h1 = numpy.sign(h1.get_qform()[0:3,0:3]).dot(header.get_offset(h1))
	origin_h2 = numpy.sign(h2.get_qform()[0:3,0:3]).dot(header.get_offset(h2))
	origin_difference_pixel = (origin_h1 - origin_h2) / numpy.asarray(header.get_pixel_spacing(h1))
	# negative values: shift image 1 by this upon inserting (which is the smae as cutting the output image)
	# positive values: cut image 1 by this at inserting and also cut right side by length of output image plus this value
	o = numpy.zeros(i2.shape, i2.dtype)
	o_slicer = []
	i_slicer = []
	for j, p in enumerate(origin_difference_pixel):
		if p >= 0:
			i_slicer.append(slice(0,      min(i1.shape[j], o.shape[j] - abs(p))))
			o_slicer.append(slice(abs(p), min(i1.shape[j] + abs(p), o.shape[j])))
		else:
			i_slicer.append(slice(abs(p), min(i1.shape[j], o.shape[j] + abs(p))))
			o_slicer.append(slice(0,      min(i1.shape[j] - abs(p), o.shape[j])))

	o[o_slicer] = i1[i_slicer]
	header.set_offset(h1, header.get_offset(h2))
	
	save(o, sys.argv[3], h1)
Example #2
0
def test03(img, hdr, idx, delta):
    # TEST 03: DOES ANY META-INFORMATION GET LOST DURING FORMAT CONVERSION? AND IF YES; WHICH?
    for tr in types_int: # reference type
        print ''
        oformat = tr
        
        # create, save and load reference image
        try:
            name_ref = tmp_folder + '.'.join(['tmp_ref', tr])
            save(img, name_ref, hdr, True)
            img_ref, hdr_ref = load(name_ref)
        except Exception as e:
            print '\tERROR: Could not generate reference image for type {}: {}'.format(otype, e)
            continue
        
        # extract meta-data from reference image
        mdata_ref = {'shape': img_ref.shape,
                     'dtype': img_ref.dtype,
                     'point': img_ref[idx],
                     'spacing': header.get_pixel_spacing(hdr_ref),
                     'offset': header.get_offset(hdr_ref),}        
        
        # print meta-data from reference image
        
        # iterate of test images
        for tt in types_int: # test type
            print '{} => {}'.format(oformat, tt),
            
            # create, save and load test images
            try:
                #print type(img_ref), type(hdr_ref)
                #print type(img_test), type(hdr_test)
                name_test = tmp_folder + '.'.join(['tmp_test', tt])
                save(img_ref, name_test, hdr_ref, True)
                img_test, hdr_test = load(name_test)
                
            except Exception as e:
                print '\tERROR: Could not generate test image. {}'.format(e)
                continue
            
            # extract meta-data from test image
            mdata_test = {'shape': img_test.shape,
                          'dtype': img_test.dtype,
                          'spacing': header.get_pixel_spacing(hdr_test),
                          'offset': header.get_offset(hdr_test),
                          'point': img_test[idx]}                    
            
            # compare reference against meta-image
            error = False
            for k in mdata_ref.keys():
                equal = _compare(mdata_ref[k], mdata_test[k], delta)
                #print '\n\t{} ({}) : {} = {}'.format(equal, k, mdata_ref[k], mdata_test[k]),
                if not equal:
                    error = True
                    print '\n\t{} ({}) : {} = {}'.format(equal, k, mdata_ref[k], mdata_test[k]),
            if not error:
                print '\t{}'.format(True)
            else:
                print '\n'
Example #3
0
 def __diff(self, hdr1, hdr2):
     """
     Returns an error message if the meta-data of the supplied headers differ,
     otherwise False. 
     """
     if not self.__same_seq(header.get_pixel_spacing(hdr1), header.get_pixel_spacing(hdr2)):
         return 'the voxel spacing is not consistent: {} != {}'.format(header.get_pixel_spacing(hdr1), header.get_pixel_spacing(hdr2))
     if not self.__same_seq(header.get_offset(hdr1), header.get_offset(hdr2)):
         return 'the offset is not consistent: {} != {}'.format(header.get_offset(hdr1), header.get_offset(hdr2))
         #return 'the offset is not consistent: {} != {}\n{} / {}\n{} / {}'.format(header.get_offset(hdr1), header.get_offset(hdr2), type(hdr1), type(hdr2), hdr2.NumberOfFrames if "NumberOfFrames" in hdr2 else "NONE", hdr2.ImagePositionPatient if "ImagePositionPatient" in hdr2 else 'NONE')
     else: return False
def main():
    args = getArguments(getParser())

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
    
    # load input image
    data_input, header_input = load(args.input)
    
    logger.debug('Original shape = {}.'.format(data_input.shape))
    
    # check if supplied dimension parameters is inside the images dimensions
    if args.dimension1 >= data_input.ndim or args.dimension1 < 0:
        raise ArgumentError('The first swap-dimension {} exceeds the number of input volume dimensions {}.'.format(args.dimension1, data_input.ndim))
    elif args.dimension2 >= data_input.ndim or args.dimension2 < 0:
        raise ArgumentError('The second swap-dimension {} exceeds the number of input volume dimensions {}.'.format(args.dimension2, data_input.ndim))
    
    # swap axes
    data_output = scipy.swapaxes(data_input, args.dimension1, args.dimension2)
    # swap pixel spacing and offset
    ps = list(header.get_pixel_spacing(header_input))
    ps[args.dimension1], ps[args.dimension2] = ps[args.dimension2], ps[args.dimension1]
    header.set_pixel_spacing(header_input, ps)
    os = list(header.get_offset(header_input))
    os[args.dimension1], os[args.dimension2] = os[args.dimension2], os[args.dimension1]
    header.set_offset(header_input, os)
    
    logger.debug('Resulting shape = {}.'.format(data_output.shape))
    
    # save resulting volume
    save(data_output, args.output, header_input, args.force)
    
    logger.info("Successfully terminated.")    
 def __diff(self, hdr1, hdr2):
     """
     Returns an error message if the meta-data of the supplied headers differ,
     otherwise False. 
     """
     if not self.__same_seq(header.get_pixel_spacing(hdr1),
                            header.get_pixel_spacing(hdr2)):
         return 'the voxel spacing is not consistent: {} != {}'.format(
             header.get_pixel_spacing(hdr1), header.get_pixel_spacing(hdr2))
     if not self.__same_seq(header.get_offset(hdr1),
                            header.get_offset(hdr2)):
         return 'the offset is not consistent: {} != {}'.format(
             header.get_offset(hdr1), header.get_offset(hdr2))
         #return 'the offset is not consistent: {} != {}\n{} / {}\n{} / {}'.format(header.get_offset(hdr1), header.get_offset(hdr2), type(hdr1), type(hdr2), hdr2.NumberOfFrames if "NumberOfFrames" in hdr2 else "NONE", hdr2.ImagePositionPatient if "ImagePositionPatient" in hdr2 else 'NONE')
     else:
         return False
Example #6
0
def main():
	i, h = load(sys.argv[1])

	print 'Image:\t{}'.format(sys.argv[1])
	print 'Shape:\t{}'.format(i.shape)
	print 'Spacing:{}'.format(header.get_pixel_spacing(h))
	print 'Offset:\t{}'.format(header.get_offset(h))

	if 0 == h.get_header()['qform_code']:
		method = 'ANALYZE 7.5 (old)'
	if h.get_header()['qform_code'] > 0:
		method = 'Normal (qform)'
	if h.get_header()['sform_code'] > 0:
		method = 'Special space (sform)'

	print
	print 'Orientation and location in space:'
	print 'Type:\t\t{}'.format(method)
	print 'qform_code:\t{}'.format(h.get_header()['qform_code'])
	print 'sform_code:\t{}'.format(h.get_header()['sform_code'])

	print
	print 'qform == sform?\t{} (max diff={})'.format(numpy.all(h.get_qform() == h.get_sform()), numpy.max(numpy.abs(h.get_qform() - h.get_sform())))
	print 'affine = qform?\t{} (max diff={})'.format(numpy.all(h.get_affine() == h.get_qform()), numpy.max(numpy.abs(h.get_affine() - h.get_qform())))
	print 'affine = sform?\t{} (max diff={})'.format(numpy.all(h.get_affine() == h.get_sform()), numpy.max(numpy.abs(h.get_affine() - h.get_sform())))

	print
	print 'qform:'
	print h.get_qform()
	print 'sform:'
	print h.get_sform()
	print 'affine:'
	print h.get_affine()
def main():
    args = getArguments(getParser())

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)

    # load input image
    data_input, header_input = load(args.input)

    logger.debug('Original shape = {}.'.format(data_input.shape))

    # check if supplied dimension parameters is inside the images dimensions
    if args.dimension1 >= data_input.ndim or args.dimension1 < 0:
        raise ArgumentError(
            'The first swap-dimension {} exceeds the number of input volume dimensions {}.'
            .format(args.dimension1, data_input.ndim))
    elif args.dimension2 >= data_input.ndim or args.dimension2 < 0:
        raise ArgumentError(
            'The second swap-dimension {} exceeds the number of input volume dimensions {}.'
            .format(args.dimension2, data_input.ndim))

    # swap axes
    data_output = scipy.swapaxes(data_input, args.dimension1, args.dimension2)
    # swap pixel spacing and offset
    ps = list(header.get_pixel_spacing(header_input))
    ps[args.dimension1], ps[args.dimension2] = ps[args.dimension2], ps[
        args.dimension1]
    header.set_pixel_spacing(header_input, ps)
    os = list(header.get_offset(header_input))
    os[args.dimension1], os[args.dimension2] = os[args.dimension2], os[
        args.dimension1]
    header.set_offset(header_input, os)

    logger.debug('Resulting shape = {}.'.format(data_output.shape))

    # save resulting volume
    save(data_output, args.output, header_input, args.force)

    logger.info("Successfully terminated.")
Example #8
0
def main(interest_list, train_only, proportion, save_name):
    if train_only == False:
        train_indicator = [False, True]
    else:
        train_indicator = [True]

    for indicator in train_indicator:
        isTrain = indicator

        if isTrain == True:
            datadir_to_load = '../input/submission/pred_result/train/'
            data_name = 'train'
            datadir_to_save = '../input/submission/pred_result_ensemble/train/'
        else:
            datadir_to_load = '../input/submission/pred_result/test/'
            data_name = 'test'
            datadir_to_save = '../input/submission/pred_result_ensemble/test/'

        if os.path.isdir(datadir_to_load) is not True:
            raise
        if os.path.isdir(datadir_to_save) is not True:
            os.makedirs(datadir_to_save)

        file_list = []
        interest_model_list = list(interest_list)
        for model_num in interest_model_list:
            file_list = file_list + glob(
                os.path.join(datadir_to_load,
                             '*model_{}*.nii'.format(model_num)))
        file_dict = dict()
        for file in file_list:
            name = str.split(file, '.')[-2]
            if name in file_dict.keys():
                file_dict[name].append(file)
            else:
                file_dict[name] = []
                file_dict[name].append(file)

        record = []
        for name in file_dict.keys():
            N = len(file_dict[name])
            img_list = []
            #NEED CHANGE !!!
            if isTrain == True:
                file_path = glob(
                    '../input/train_data/*/*/*{}*'.format(name))[0]
            else:
                file_path = glob('../input/test_data/*/*/*{}*'.format(name))[0]
            mtt, mtt_header = load(file_path)
            adc_path = glob('/'.join(str.split(file_path, '/')[:4]) +
                            '/*/*ADC*.nii')[0]
            _, adc_header = load(adc_path)
            # print('name: {}, number of images: {}'.format(name, N))

            for j in xrange(N):
                img, img_header = load(file_dict[name][j])
                if header.get_pixel_spacing(
                        adc_header) != header.get_pixel_spacing(img_header):
                    print("ERROR!!!!")
                if header.get_offset(adc_header) != header.get_offset(
                        img_header):
                    print("ERROR!!!!")
                if mtt.shape != img.shape:
                    print("ERROR!!!!")
                img_list.append(img)

            arr = np.sum(np.array(img_list), axis=0)
            arr = np.array(arr > N * proportion, dtype=np.uint16)
            arr_name = datadir_to_save + 'VSD.yong_{}_{}.'.format(
                save_name, data_name) + name + '.nii'
            # print('proportion of GT: {}, dimension: {}'.format(np.mean(arr), arr.shape))
            save(arr, arr_name, adc_header)

            if isTrain == True:
                gt_path = glob('../input/train_data/{}/*/*OT*'.format(
                    str.split(file_path, '/')[-3]))[0]
                gt, gt_header = load(gt_path)
                f1 = 2.0 * np.sum(gt * arr) / (np.sum(gt) + np.sum(arr))
                record.append(f1)

        if isTrain == True:
            record = np.array(record)
            print(record)
            print(np.mean(record))
            print(np.std(record))
Example #9
0
          numpy.bool)

delta = 0.0001 # maximum difference between meta data allowed (since rounding errors occure)

# load original input image
img, hdr = load(input_image)

# random index
idx = tuple([random.randint(0, img.shape[i] - 1) for i in range(len(img.shape))])

# extract information from original image
otype = input_image.split('.')[-1]
mdata = {'shape': img.shape,
         'dtype': img.dtype,
         'spacing': header.get_pixel_spacing(hdr),
         'offset': header.get_offset(hdr),
         'point': img[idx]}

print "ORIGINAL"
print "Type: {}".format(otype)
print "MData: {}".format(mdata)

def test01(img):
    # TEST 01: WHAT DATATYPES CAN THE FORMATS SAVE?
    for dt in dtypes:
        print '\n:::{}:::'.format(dt).upper()
        for t in types_int:
            print t.upper(), '\t->',
             
            try:
                img1 = img.astype(dt)