Esempio n. 1
0
def predict_autocontext( self,
                         img,
                         mask,
                         nb_labels,
                         nb_autocontext,
                         debug=False,
                         return_all=False ):
    proba = np.ones((nb_labels,img.shape[0],img.shape[1],img.shape[2]),dtype='float32')
    proba /= nb_labels

    header = img.get_header()
    header['dim'][3] = nb_labels
    proba = irtk.Image(proba,header,squeeze=False)
    
    all_steps = []

    for k in xrange(nb_autocontext):
        knowledge = self.get_knowledge(img,proba,mask=mask)

        if debug:
            irtk.imwrite("knowledge_"+str(k)+".nii.gz", knowledge)

        forest = integralForest( folder=self.folder(k),
                                 test=self.params['test'],
                                 parallel=self.params['parallel'],
                                 nb_knowledge_layers=knowledge.shape[0] )
        proba = forest.predict_autocontext( img,
                                            knowledge,
                                            mask,
                                            self.params['ksampling'] )
        proba = irtk.Image(proba,header,squeeze=False)
        if return_all:
            all_steps.append( proba.copy() )
        if debug:
            irtk.imwrite("debug_"+str(k)+".nii.gz", proba)
        
        if k < 1:
            for i in xrange(proba.shape[0]):
                if i == 0:
                    proba[i] = 0
                else:
                    proba[i] = self.get_center(proba[i])
            
        if debug:
            print "done autocontext", k
        #     irtk.imwrite("debug_rescaled_"+str(k)+".nii.gz", proba)

    if not return_all:
        return proba
    else:
        return all_steps
Esempio n. 2
0
    def get_knowledge( self, img, proba, mask=None ):
        knowledge = proba[1:].rescale(0,1000).view(np.ndarray)
        if len(knowledge.shape) == 2:
            knowledge = knowledge[np.newaxis,np.newaxis,...]
        if len(knowledge.shape) == 3:
            knowledge = knowledge[np.newaxis,...]

        group_distances = Parallel(n_jobs=self.params['n_jobs'])(delayed(gdt)( img,
                                                                               self.get_center(proba[group_id]),
                                                                               l=float(self.params['lambda_gdt'])*self.params['resample'][0] )
                                                                 for group_id in range(1,proba.shape[0]) )

        for group_id in xrange(1,proba.shape[0]):
            knowledge = np.concatenate((knowledge,
                                        np.reshape(group_distances[group_id-1].rescale(0,1000),
                                                   (1,
                                                    img.shape[0],
                                                    img.shape[1],
                                                    img.shape[2]))),
                                       axis=0)

        header = img.get_header()
        header['dim'][3] = knowledge.shape[0]
        knowledge = irtk.Image(knowledge.copy(order='C').astype('float32'),header,squeeze=False)
        if self.params['ksampling'] != 1.0:
            knowledge = knowledge.resample(img.header['pixelSize'][0]*self.params['ksampling'])

        # irtk.imwrite("debug.nii.gz",knowledge)
        # exit(0)

        return knowledge    
Esempio n. 3
0
def edt( img, mask ):
    if mask.sum() == 0:
        return irtk.zeros(img.get_header())
    voxelSpacing = img.header['pixelSize'][:3][::-1]
    distanceMap = nd.distance_transform_edt( logical_not(mask),
                                             sampling=voxelSpacing)
    distanceMap -= nd.distance_transform_edt( mask,
                                              sampling=voxelSpacing)
    return irtk.Image(distanceMap,img.get_header())
Esempio n. 4
0
 def apply( self, img, target_header=None,
            interpolation='linear', gaussian_parameter=1.0 ):
     """
     Apply.
     """
     if not isinstance( img, irtk.Image ):
         # point transformation
         pt = np.array(img, dtype='float64', copy=True)
         if len(pt.shape) == 1:
             tmp_pt = np.hstack((pt,[1])).astype('float64')
             return np.dot( self.matrix(), tmp_pt )[:3]
         else:
             pt = _irtk.transform_points( self.matrix(), pt )
             return pt  
             # tmp_pt = np.hstack((pt,[[1]]*pt.shape[0])).astype('float64')
             # return np.transpose( np.dot( self.matrix(),
             #                              np.transpose(tmp_pt) ) )[:,:3]
     
     # if target_header is None:
     #     target_header = img.get_header()
     if target_header is None:
         (x_min, y_min, z_min, x_max, y_max, z_max ) = img.bbox(world=True)
         corners = [[x_min, y_min, z_min],
                    [x_max, y_min, z_min],
                    [x_min, y_max, z_min],
                    [x_min, y_min, z_max],
                    [x_max, y_max, z_min],
                    [x_min, y_max, z_max],
                    [x_max, y_min, z_max],
                    [x_max, y_max, z_max]]
         corners = self.apply( corners )
         x_min, y_min, z_min = corners.min(axis=0)
         x_max, y_max, z_max = corners.max(axis=0)
         res = img.header['pixelSize'][0]
         pixelSize = [res, res, res, 1]
         origin = [ x_min + (x_max+1 - x_min)/2,
                    y_min + (y_max+1 - y_min)/2,
                    z_min + (z_max+1 - z_min)/2,
                    img.header['origin'][3] ]
         dim = [ (x_max+1 - x_min)/res,
                 (y_max+1 - y_min)/res,
                 (z_max+1 - z_min)/res,
                 1 ]
         target_header = irtk.new_header( pixelSize=pixelSize, origin=origin, dim=dim)
     if isinstance( target_header, irtk.Image ):
         target_header = target_header.get_header()
     data = img.get_data('float32','cython')
     new_data = _irtk.transform_rigid( self.tx, self.ty, self.tz,
                                       self.rx, self.ry, self.rz,
                                       data,
                                       img.get_header(),
                                       target_header,
                                       interpolation,
                                       gaussian_parameter )
     return irtk.Image( new_data, target_header )
Esempio n. 5
0
def background_distance(img,metric='geodesic',includeEDT=True):
    background = get_background(img)

    if metric == "euclidean":
        distanceMap = edt( img, background )
    elif metric == "geodesic":
        distanceMap = gdt( img, background, includeEDT )
    else:
        raise ValueError("Unknown metric: "+ metric)
    
    return irtk.Image(distanceMap,img.get_header())
Esempio n. 6
0
def gdt( img, mask, includeEDT=True, l=1.0 ):
    if mask.sum() == 0:
        return irtk.zeros(img.get_header())
    voxelSpacing = img.header['pixelSize'][:3][::-1]
    grad =  irtk.Image( nd.gaussian_gradient_magnitude(img, 0.5),
                        img.get_header() )
    #irtk.imwrite("gradBefore.nii.gz",grad)
    grad = l*grad.saturate().rescale(0.0,1.0).as3D()
    #irtk.imwrite("gradAfter.nii.gz",grad)
    # distanceMap = geodesic_distance_transform( mask,
    #                                            grad,
    #                                            numIterations=3,
    #                                            spacing=voxelSpacing,
    #                                            includeEDT=includeEDT )
    # distanceMap -= geodesic_distance_transform( logical_not(mask),
    #                                             grad,
    #                                             numIterations=3,
    #                                             spacing=voxelSpacing,
    #                                             includeEDT=includeEDT )
    # return irtk.Image(distanceMap,img.get_header())

    # distanceMaps = Parallel(n_jobs=-1)(delayed(_geodesic_distance_transform)( m,
    #                                                                          grad,
    #                                                                          numIterations=3,
    #                                                                          spacing=voxelSpacing,
    #                                                                          includeEDT=includeEDT )
    #                                                              for m in [mask,
    #                                                                        logical_not(mask)]
    #                                                                          )
    # res = irtk.Image(distanceMaps[0]-distanceMaps[1],img.get_header())

    res = irtk.Image( _geodesic_distance_transform( mask,
                                                    grad,
                                                    numIterations=3,
                                                    spacing=voxelSpacing,
                                                    includeEDT=includeEDT ),
                      img.get_header() ).as3D()

    return res
Esempio n. 7
0
#!/usr/bin/python

import irtk
import sys
import scipy.ndimage as nd

input_file = sys.argv[1]
output_file = sys.argv[2]

img = irtk.imread(input_file, dtype='float32')

img = irtk.Image(nd.median_filter(img.get_data(), 5), img.get_header())
irtk.imwrite(output_file, img)
Esempio n. 8
0
    
    return labels == best_label
    
def background_distance(img,metric='geodesic',includeEDT=True):
    background = get_background(img)

    if metric == "euclidean":
        distanceMap = edt( img, background )
    elif metric == "geodesic":
        distanceMap = gdt( img, background, includeEDT )
    else:
        raise ValueError("Unknown metric: "+ metric)
    
    return irtk.Image(distanceMap,img.get_header())


if __name__ == "__main__":

    img = irtk.imread( sys.argv[1], dtype="float64" )
    #filtered = nd.minimum_filter(img,5)
    filtered = nd.gaussian_gradient_magnitude(img,0.5)
    img = irtk.Image(filtered,img.get_header())
    irtk.imwrite("test2.nii.gz",img)
    exit(0)
    
    img = world_align(img,pixelSize=[2,2,2,1])

    irtk.imwrite("distanceEDT.nii.gz",background_distance(img,metric="euclidean"))

    irtk.imwrite( "distanceGDT.nii.gz", background_distance(img,metric="geodesic"))
Esempio n. 9
0
def get_noiseZ(img):
    img = img.astype('float32')
    new_img = np.zeros(img.shape, dtype='float32')
    for x in xrange(img.shape[2]):
        new_img[:, :, x] = nd.gaussian_filter(img[:, :, x], 2, mode='reflect')
    noise = img - new_img
    #print "Noise Z:", noise.std(), img.std()
    return noise.std()


output_filename = sys.argv[3]

img = irtk.imread(sys.argv[1], dtype='float64').saturate()
mask = irtk.imread(sys.argv[2], dtype='int16')
mask = irtk.Image(mask, img.get_header())

# crop
x_min, y_min, z_min, x_max, y_max, z_max = mask.bbox()
mask = mask[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]
tmp_img = img[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]

downsampled_img = tmp_img.resample(2)
mask = mask.transform(target=downsampled_img, interpolation='nearest')

seg = irtk.graphcut(downsampled_img,
                    mask,
                    sigma=get_noiseXY(downsampled_img),
                    sigmaZ=get_noiseZ(downsampled_img))

irtk.imwrite(sys.argv[3], seg.transform(target=img, interpolation='nearest'))
Esempio n. 10
0
    # exit(0)

forest.grow(100)

# print "writing"
# forest.write("test_forest")
# print "done"
# print "reading"
# forest = integralForest(folder="test_forest")
# print "done"

img = cv2.imread("378.png", 0).astype("float32")
img = img[np.newaxis, ...].copy()
res = forest.predict_hard(img)
res = np.squeeze(res)  #.copy()
irtk.imshow(irtk.Image(img), seg=res, filename="overlay_seg.png")

res /= res.max()
res *= 255
cv2.imwrite("res_hard.png", res.astype('uint8'))

res = forest.predict_soft(img)
res = np.squeeze(res)
#res /= res.max()

res *= 255
irtk.imshow(irtk.Image(img),
            overlay=res.astype('uint8'),
            colors='jet',
            filename="overlay.png")
Esempio n. 11
0
def preprocess_training_data(patient_id,
                             img_folder,
                             seg_folder,
                             resample,
                             offline=False,
                             online=True):
    if offline or online:
        if (offline and os.path.exists("offline_preprocessing/" + patient_id +
                                       "_img.nii.gz")
                and os.path.exists("offline_preprocessing/" + patient_id +
                                   "_seg.nii.gz")):
            return
        img = irtk.imread(img_folder + "/" + patient_id + ".nii.gz",
                          dtype='float32')
        seg = irtk.imread(seg_folder + "/" + patient_id + "_seg.nii.gz",
                          dtype="uint8")

        wall = nd.binary_dilation(
            seg,
            morphology.ball(int(12.5 * 0.001 / seg.header['pixelSize'][0])))
        wall = wall.astype('int')
        points = np.transpose(np.nonzero(wall))[::4]
        center, S, V = fit_ellipsoidPCA(points)
        if V[0, 0] < 0:
            V *= -1

        points = np.transpose(np.nonzero(wall))
        projections = np.dot(points - center, V[0])

        # valves
        index = projections > (projections.max() -
                               40.0 * 0.001 / seg.header['pixelSize'][0])

        #print "VALVE size:",np.sum(index), projections.max(), 40.0*0.001/seg.header['pixelSize'][0]

        wall[points[index, 0], points[index, 1], points[index, 2]] = 2

        #print "VALVE1", wall.max()

        wall = irtk.Image(wall, seg.get_header())

        img = img.resample(pixelSize=resample,
                           interpolation='linear').rescale(0, 1000)
        seg = seg.transform(target=img,
                            interpolation="nearest").astype('uint8')
        wall = wall.transform(target=img,
                              interpolation="nearest").astype('uint8')

        wall[seg > 0] = 0
        seg[wall == 1] = 2
        seg[wall == 2] = 3

        #print "VALVE2", seg.max()

        #irtk.imwrite("debug/"+patient_id+"_border.nii.gz",seg)

        seg[img == 0] = 255

        if offline:
            irtk.imwrite("offline_preprocessing/" + patient_id + "_img.nii.gz",
                         img)
            irtk.imwrite("offline_preprocessing/" + patient_id + "_seg.nii.gz",
                         seg)
            return

    if not online:
        img = irtk.imread("offline_preprocessing/" + patient_id +
                          "_img.nii.gz")
        seg = irtk.imread("offline_preprocessing/" + patient_id +
                          "_seg.nii.gz")

    mask = irtk.ones(img.get_header(), dtype='uint8')
    mask[img == 0] = 0

    return {
        'patient_id': patient_id,
        'img': img,
        'seg': seg,
        'extra_layers': np.array([], dtype='float32'),
        'metadata': None,
        'mask': mask
    }
Esempio n. 12
0
def predict_autocontext(self,
                        img,
                        mask,
                        extra_layers,
                        metadata,
                        nb_labels,
                        ga,
                        nb_autocontext,
                        debug=False,
                        return_all=False):
    proba = np.ones((nb_labels, img.shape[0], img.shape[1], img.shape[2]),
                    dtype='float32')
    proba /= nb_labels

    header = img.get_header()
    header['dim'][3] = nb_labels
    proba = irtk.Image(proba, header)

    all_steps = []

    for k in xrange(nb_autocontext):
        metadata = self.get_center_axis(proba, k)
        knowledge = self.get_knowledge(img, proba, extra_layers, mask=mask)

        if debug:
            irtk.imwrite("knowledge_" + str(k) + ".nii.gz", knowledge)

        forest = integralForest(folder=self.folder(k),
                                test=self.params['test'],
                                parallel=self.params['parallel'],
                                nb_knowledge_layers=knowledge.shape[0])
        proba = forest.predict_autocontext(img, knowledge, mask,
                                           self.params['ksampling'], metadata)
        proba = irtk.Image(proba, header)
        if return_all:
            all_steps.append(proba.copy())
        if debug:
            irtk.imwrite("debug_" + str(k) + ".nii.gz", proba)

        if k < 1:
            for i in xrange(proba.shape[0]):
                if i == 0:
                    proba[i] = 0
                else:
                    proba[i] = self.groups[i - 1].get_center(proba[i])

        #     # volume constraint
        #     # set not ventricule to 0
        #     tmp_proba = proba[1]
        #     for i in xrange(proba.shape[0]):
        #         if i == 1:
        #             continue
        #         proba[i] = 0

        #     # rescale ventricule
        #     target_volume = 182950.0*0.001**3
        #     #target_volume = 151807.0*0.001**3

        #     if k == 0:
        #         target_volume *= 0.5
        #     # elif k == 1:
        #     #     target_volume *= 0.25
        #     # elif k == 2:
        #     #     target_volume *= 0.5

        #     box_volume = float(proba.shape[1])*proba.header['pixelSize'][2]*float(proba.shape[2])*proba.header['pixelSize'][1]*float(proba.shape[3])*proba.header['pixelSize'][0]

        #     ratio = float(target_volume) / float(box_volume)

        #     #print "ratio", ratio
        #     q0 = mquantiles( tmp_proba.flatten(), prob=[1.0-ratio] )
        #     tmp_proba[proba[1]<q0] = q0
        #     tmp_proba -= tmp_proba.min()
        #     tmp_proba /= tmp_proba.max()

        #     lcc = irtk.largest_connected_component(tmp_proba,fill_holes=False)
        #     tmp_proba[lcc==0] = 0

        #     proba[1] = tmp_proba

        if debug:
            print "done autocontext", k
        #     irtk.imwrite("debug_rescaled_"+str(k)+".nii.gz", proba)

    if not return_all:
        return proba
    else:
        return all_steps
Esempio n. 13
0
#!/usr/bin/python

import irtk
import cv2

mask = irtk.imread("mask.nii", dtype='uint8')
irtk.imwrite("mask.png", mask)

img = irtk.Image(cv2.imread("lena.png", 0))

irtk.imshow(img,
            mask,
            filename="initialisation.png",
            colors={
                1: (255, 0, 0),
                2: (0, 255, 0)
            },
            opacity=1.0)

mask2 = irtk.imread("mask2.nii", dtype='uint8')
irtk.imwrite("mask2.png", mask2)
irtk.imshow(img,
            mask2,
            filename="initialisation2.png",
            colors={
                1: (255, 0, 0),
                2: (0, 255, 0)
            },
            opacity=1.0)
Esempio n. 14
0
#!/usr/bin/python

import sys

import numpy as np
import irtk

# img1 = irtk.imread("reconstruction/t2.nii", dtype='float32')
# img2 = irtk.imread("reconstruction/t2seg.nii", dtype='float32')
# irtk.imwrite( "reconstruction/segfixed.nii", img2.transform(target=img1) )

shape = map(int, sys.argv[1:4])
z = int(sys.argv[4])
y = int(sys.argv[5])
x = int(sys.argv[6])

target = irtk.imread(sys.argv[7])

img = irtk.imread(sys.argv[8], dtype='float32')

new_data = np.zeros(shape, dtype='int32')
new_data[z:z + img.shape[0], y:y + img.shape[1], x:x + img.shape[2]] = img

new_img = irtk.Image(new_data, target.get_header())
irtk.imwrite(sys.argv[9], new_img)