def process_dataset(args, num_tries=3):
    """ pre process and registrate volume"""
    # pylint: disable= unused-argument
    moving_image_id = args[0]
    print(moving_image_id)

    conn = sqlite3.connect(util.DB_PATH)
    conn.text_factory = str
    cursor = conn.execute('''SELECT pid from Images where id = ?''', (moving_image_id,))
    pid = cursor.fetchone()[0]
    cursor = conn.execute('''SELECT id from Images where pid = ? AND diag_pre_post = ?''',
                          (pid, "pre"))
    db_temp = cursor.fetchone()
    pre_image_id = db_temp[0]

    cursor.close()
    conn.close()

    import datetime
    start_time = datetime.datetime.now()
    pre_img = img_data(pre_image_id, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)
    post_img = img_data(moving_image_id, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)

    pre_img = image_registration.pre_process(pre_img, False)
    post_img = image_registration.pre_process(post_img, False)
    img = image_registration.registration(post_img, pre_img.pre_processed_filepath,
                                          image_registration.RIGID)
    print("\n\n\n\n -- Total run time: ")
    print(datetime.datetime.now() - start_time)

    img.fixed_image = pre_image_id

    return img
Exemplo n.º 2
0
def process_dataset(args):
    """ pre process and registrate volume"""
    (moving_image_id, reg_type, save_to_db, be_method, reg_type_be) = args
    util.LOGGER.info(moving_image_id)

    for k in range(3):
        try:
            start_time = datetime.datetime.now()
            img = img_data(moving_image_id, util.DATA_FOLDER,
                           util.TEMP_FOLDER_PATH)
            img = pre_process(img, reg_type=reg_type_be, be_method=be_method)
            util.LOGGER.info("-- Run time preprocess: ")
            util.LOGGER.info(datetime.datetime.now() - start_time)
            img = registration(img, util.TEMPLATE_MASKED_VOLUME, reg_type)
            break
        # pylint: disable= broad-except
        except Exception as exp:
            util.LOGGER.error('Crashed during ' + str(k + 1) + ' of 3 ' +
                              str(exp))
    util.LOGGER.info(" -- Run time: " +
                     str(datetime.datetime.now() - start_time))
    if save_to_db:
        save_transform_to_database([img])
        del img
    else:
        transform_labels_temp([img])
        del img
def post_calculations(moving_dataset_image_ids, result=None):
    """ Transform images and calculate avg"""
    if result is None:
        result = {}

    for _id in moving_dataset_image_ids:
        img = img_data(_id, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)
        img.load_db_transforms()

        img_pre = img_data(img.fixed_image, util.DATA_FOLDER,
                           util.TEMP_FOLDER_PATH)
        img_pre.load_db_transforms()

        reg_vol = util.transform_volume(img.reg_img_filepath,
                                        img_pre.get_transforms())
        vol = util.TEMP_FOLDER_PATH + util.get_basename(
            basename(reg_vol)) + '_BE.nii.gz'

        mult = ants.MultiplyImages()
        mult.inputs.dimension = 3
        mult.inputs.first_input = reg_vol
        mult.inputs.second_input = util.TEMPLATE_MASK
        mult.inputs.output_product_image = vol
        mult.run()

        label = "img"
        if label in result:
            result[label].append(vol)
        else:
            result[label] = [vol]

        for (segmentation, label) in util.find_reg_label_images(_id):
            segmentation = util.transform_volume(segmentation,
                                                 img_pre.get_transforms(),
                                                 label_img=True)
            if label in result:
                result[label].append(segmentation)
            else:
                result[label] = [segmentation]
    return result
Exemplo n.º 4
0
def process_dataset(args, num_tries=3):
    """ pre process and registrate volume"""
    # pylint: disable= unused-argument
    (moving_image_id, _, save_to_db, _) = args
    print(moving_image_id)

    conn = sqlite3.connect(util.DB_PATH)
    conn.text_factory = str
    cursor = conn.execute('''SELECT pid from Images where id = ?''',
                          (moving_image_id, ))
    pid = cursor.fetchone()[0]
    cursor = conn.execute(
        '''SELECT id from Images where pid = ? AND diag_pre_post = ?''',
        (pid, "pre"))
    db_temp = cursor.fetchone()
    pre_image_id = db_temp[0]

    cursor.close()
    conn.close()

    start_time = datetime.datetime.now()
    pre_img = img_data(pre_image_id, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)
    post_img = img_data(moving_image_id, util.DATA_FOLDER,
                        util.TEMP_FOLDER_PATH)
    post_img.fixed_image = pre_image_id

    pre_img = image_registration.pre_process(pre_img, False)
    post_img = image_registration.pre_process(post_img, False)
    img = image_registration.registration(post_img,
                                          pre_img.pre_processed_filepath,
                                          image_registration.RIGID)
    print("\n\n\n\n -- Total run time: ")
    print(datetime.datetime.now() - start_time)
    img.fixed_image = pre_image_id

    if save_to_db:
        image_registration.save_transform_to_database([img])
def save_to_db(image_ids, ny_image_ids):
    print("----here")
    data_transforms = []
    for (img_id, ny_img_id) in zip(image_ids, ny_image_ids):
        print(img_id)
        _img = img_data(img_id, db_path, util.TEMP_FOLDER_PATH)
        _img.load_db_transforms()
        print(_img.transform)
        if _img.transform is None:
            continue
        _img.processed_filepath = image_registration.move_vol(_img.img_filepath, _img.get_transforms())
        _img.image_id = ny_img_id
        data_transforms.append(_img)

    image_registration.save_transform_to_database(data_transforms)
Exemplo n.º 6
0
def save_to_db(image_ids, ny_image_ids):
    print("----here")
    data_transforms = []
    for (img_id, ny_img_id) in zip(image_ids, ny_image_ids):
        print(img_id)
        _img = img_data(img_id, db_path, util.TEMP_FOLDER_PATH)
        _img.load_db_transforms()
        print(_img.transform)
        if _img.transform is None:
            continue
        _img.processed_filepath = image_registration.move_vol(
            _img.img_filepath, _img.get_transforms())
        _img.image_id = ny_img_id
        data_transforms.append(_img)

    image_registration.save_transform_to_database(data_transforms)
def move_vol(moving, transform, label_img=False):
    """ Move data with transform """
    if label_img:
        # resample volume to 1 mm slices
        target_affine_3x3 = np.eye(3) * 1
        img_3d_affine = resample_img(moving, target_affine=target_affine_3x3,
                                     interpolation='nearest')
        resampled_file = util.TEMP_FOLDER_PATH + util.get_basename(moving) + '_resample.nii.gz'
        # pylint: disable= no-member
        img_3d_affine.to_filename(resampled_file)

    else:
        img = img_data(-1, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)
        img.set_img_filepath(moving)
        resampled_file = pre_process(img, False).pre_processed_filepath

    result = util.transform_volume(moving, transform, label_img)
    util.generate_image(result, util.TEMPLATE_VOLUME)
    return result
Exemplo n.º 8
0
def move_vol(moving, transform, label_img=False, slice_size=1, ref_img=None):
    """ Move data with transform """
    if label_img:
        # resample volume to 1 mm slices
        target_affine_3x3 = np.eye(3) * slice_size
        img_3d_affine = resample_img(moving,
                                     target_affine=target_affine_3x3,
                                     interpolation='nearest')
        resampled_file = util.TEMP_FOLDER_PATH + util.get_basename(
            moving) + '_resample.nii.gz'
        # pylint: disable= no-member
        img_3d_affine.to_filename(resampled_file)
        del img_3d_affine
    else:
        img = img_data(-1, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)
        img.set_img_filepath(moving)
        resampled_file = pre_process(img, False).pre_processed_filepath

    result = util.transform_volume(resampled_file,
                                   transform,
                                   label_img,
                                   ref_img=ref_img)
    util.generate_image(result, util.TEMPLATE_VOLUME)
    return result
def process_dataset(args):
    """ pre process and registrate volume"""
    (moving_image_id, reg_type, save_to_db) = args
    print(moving_image_id)

    start_time = datetime.datetime.now()
    img = img_data(moving_image_id, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)
    img = pre_process(img)

    print("\n\n\n\n -- Run time preprocess: ")
    print(datetime.datetime.now() - start_time)

    for k in range(3):
        try:
            img = registration(img, util.TEMPLATE_MASKED_VOLUME, reg_type)
            break
        # pylint: disable= broad-except
        except Exception as exp:
            print('Crashed during' + str(k+1) + ' of 3 \n' + str(exp))
    print("\n\n\n\n -- Run time: ")
    print(datetime.datetime.now() - start_time)
    if save_to_db:
        save_transform_to_database([img])
    return img
Exemplo n.º 10
0
    conn = sqlite3.connect(util.DB_PATH)
    cursor = conn.cursor()

    modified_patients = [
        subfolder_name
        for subfolder_name in os.listdir(new_segmentations_folder) if
        os.path.isdir(os.path.join(new_segmentations_folder, subfolder_name))
    ]

    for pid in modified_patients:
        #print('PATIENT ' + pid)
        cursor.execute("SELECT id FROM Images WHERE pid = ?", (int(pid), ))
        image_id = cursor.fetchone()[0]
        print(image_id)
        img = img_data(image_id, util.DATA_FOLDER, util.TEMP_FOLDER_PATH)
        img.load_db_transforms()
        #cursor.execute("SELECT  filepath, filepath_reg FROM Labels WHERE image_id IN "
        #               "(SELECT id FROM Images WHERE pid = ?)", (int(pid),))
        #(label_path, label_reg_path) = cursor.fetchone()
        #cursor.execute("SELECT  transform FROM Images WHERE pid = ?", (int(pid),))
        #transform = cursor.fetchone()[0]
        new_segmentation_path = glob.glob(new_segmentations_folder + str(pid) +
                                          '/*label.nii')[0]
        #print(new_segmentation_path)

        #temp = util.compress_vol(move_vol(new_segmentation_path, img.get_transforms(), True))
        #shutil.copy(temp, img.reg_label_filepath)
        shutil.copy(new_segmentation_path, img.label_filepath)

    #path = '/Volumes/Neuro/Segmentations/oppdaterte_filer/**/*label.nii'
Exemplo n.º 11
0
def main():
    Data = img_data.img_data('train')
    images, labels = Data.get()
    print("images {} labels {}".format(np.shape(images), np.shape(labels)))