Esempio n. 1
0
for i in range(1,5):
    tmp_seg[nd.binary_closing(tmp_seg==i,
                              structure=morphology.ball(2))>0] = i

background = (nd.binary_dilation( tmp_seg>0, structure=ball ) == 0).astype('int32')

header = tmp_img.get_header()
header['dim'][3] = 5
proba = irtk.zeros( header, dtype='float32' )

proba[0][tmp_seg==0] = 1.0

for i in range(1,5):
    proba[i][tmp_seg==i] = 1.0

irtk.imwrite( "proba.nii.gz", proba )

print proba.header, proba.shape

tmp_seg = irtk.crf( tmp_img,
                    tmp_seg,
                    proba,
                    l=4.0,
                    sigma=50 )

res = tmp_seg.transform( target=seg, interpolation='nearest' )

print np.unique(res)

irtk.imwrite( args.output, res )
# for i in [1,2]:
#     seg[proba[i] > 0.5] = i

if args.seg is None:
    seg_init = irtk.Image( np.argmax(proba,axis=0).astype('int32'),
                      img.get_header() )
else:
    seg_init = irtk.imread( args.seg, dtype='int32', force_neurological=True )
    seg_init[seg_init>2] = 0
    seg_init[seg_init==2] = 1

irtk.imwrite("seg_debug.nii.gz",seg_init)

seg = irtk.crf( img,
                seg_init,
                proba,
                l=args.l,
                sigma=args.sigma ) # 30,10 # 10,5

print 1, seg.shape, seg_init.shape

print np.unique(seg)

if args.remove_small_objects > 0:
    seg = irtk.Image( morphology.remove_small_objects(seg.view(np.ndarray).astype('bool'),
                                                      min_size=args.remove_small_objects).astype('uint8'),
                      seg.get_header() )

print 2, seg.shape, seg_init.shape
    
if args.select:
Esempio n. 3
0
def mask_image( file_img, file_mask, ga, r, neigh, output_dir ):
    img = irtk.imread( file_img, dtype='float32' )

    input_mask = irtk.imread( file_mask )
    
    print "predicting..."
    res = irtk.zeros( img.get_header(), dtype='float32' )
    res2 = irtk.zeros( img.get_header(), dtype='float32' )
    res3 = irtk.zeros( img.get_header(), dtype='float32' )
    res4 = irtk.zeros( img.get_header(), dtype='uint8' )
    mask = irtk.ones( input_mask.get_header(), dtype='uint8' )
    mask[input_mask == 2] = 0
    for z in xrange(img.shape[0]):
        print z
        YX = np.transpose( np.nonzero( mask[z] ) )
        if YX.shape[0] == 0:
            continue # this slice does not intersect the box
        patches = extract_patches2D( img[z], r, YX )
        patches = np.reshape( patches, (patches.shape[0],patches.shape[1]*patches.shape[2]) )

        predictions = neigh.predict_proba(patches)[:,1]
        res[z,YX[:,0],YX[:,1]] = predictions

    x_min, y_min, z_min, x_max, y_max, z_max = mask.bbox()

    proba = res[z_min:z_max+1,
                y_min:y_max+1,
                x_min:x_max+1]

    if args.mass:
        BV = get_BV( args.ga )
        box_volume = (z_max-z_min)*img.header['pixelSize'][2]*(y_max-y_min)*img.header['pixelSize'][1]*(x_max-x_min)*img.header['pixelSize'][0]
        ratio = float(BV) / float(box_volume)
        print "ratio", ratio
        q0,q1 = mquantiles( proba.flatten(), prob=[0.5*(1.0-ratio),
                                                   1.0-0.5*ratio] )
        print "threshold", q0,q1
        #threshold = max(0.5,threshold)
    
        # labels = res[z_min:z_max+1,
        #              y_min:y_max+1,
        #              x_min:x_max+1] > threshold
        
    #res = 1 / (np.exp(-(res-threshold)/(res.max()-res.min())))

        res[res<q0] = q0
        res[res>q1] = q1
        res -= res.min()
        res /= res.max()

    labels = res[z_min:z_max+1,
                 y_min:y_max+1,
                 x_min:x_max+1] > 0.5
   
    proba = res[z_min:z_max+1,
                y_min:y_max+1,
                x_min:x_max+1]
    
    cropped_img = img[z_min:z_max+1,
                      y_min:y_max+1,
                      x_min:x_max+1]

    if args.do_3D:
        labels = irtk.crf( cropped_img,
                           labels,
                           proba,
                           l=args.l,
                           sigma=get_noiseXY(cropped_img),
                           sigmaZ=get_noiseZ(cropped_img) )
    # elif args.do_patchZ:
    #     labels = irtk.crf_patchZ( cropped_img,
    #                               labels,
    #                               proba,
    #                               l=10.0 )   
    # else:
    #     for z in xrange(z_min,z_max+1):
    #         labels[z] = irtk.crf( cropped_img[z],
    #                               labels[z],
    #                               proba[z],
    #                               l=1.0 )

    print "MAX LABEL:", labels.max()
    irtk.imwrite(output_dir + "/bare_"+os.path.basename(file_img), labels )
    tmp = irtk.zeros( img.get_header(), dtype='uint8' )
    tmp[z_min:z_max+1,
        y_min:y_max+1,
        x_min:x_max+1] = labels
    ( min_x_bare, min_y_bare, min_z_bare,
      max_x_bare, max_y_bare, max_z_bare ) = tmp.bbox()
    
    if not args.no_cleaning:
        # clean by fitting ellipses enlarged of 10%
        for z in xrange(labels.shape[0]):
            edges = nd.morphological_gradient( labels[z] > 0,size=5 )
            points = np.transpose(edges.nonzero())[:,::-1]
            if len(points) == 0:
                continue
            points = np.array(map(lambda x:[x],points),dtype='int32')
            ellipse = cv2.fitEllipse(points)
            cv2.ellipse( labels[z], (ellipse[0],
                                     (1.1*ellipse[1][0],1.1*ellipse[1][1]),
                                     ellipse[2]) , 1, -1 )

    irtk.imwrite(output_dir + "/seg_"+os.path.basename(file_img), labels )
    irtk.imwrite(output_dir + "/res_"+os.path.basename(file_img), res )

    # re-read the image in case we processed it
    img = irtk.imread( file_img, dtype='float32' )
    cropped_img = img[z_min:z_max+1,
                      y_min:y_max+1,
                      x_min:x_max+1]
    cropped_img[labels==0] = -1
    masked = cropped_img.bbox(crop=True)
    irtk.imwrite(output_dir + "/masked_"+os.path.basename(file_img), masked )

    # re-read the image in case we processed it
    img = irtk.imread( file_img, dtype='float32' )    
    x0 = min_x_bare + (max_x_bare - min_x_bare) / 2
    y0 = min_y_bare + (max_y_bare - min_y_bare) / 2
    ofd = get_OFD(ga)/img.header['pixelSize'][0]

    cropped_img = img[min_z_bare:max_z_bare+1,
                      max(0,int(round(y0-ofd/2))):min(img.shape[1],int(round(y0+ofd/2+1))),
                      max(0,int(round(x0-ofd/2))):min(img.shape[2],int(round(x0+ofd/2+1)))].copy()

    irtk.imwrite(output_dir + "/very_large_"+os.path.basename(file_img),
                 cropped_img )
    
    cropped_proba = res[min_z_bare:max_z_bare+1,
                        max(0,int(round(y0-ofd/2))):min(img.shape[1],int(round(y0+ofd/2+1))),
                        max(0,int(round(x0-ofd/2))):min(img.shape[2],int(round(x0+ofd/2+1)))].copy()

    irtk.imwrite(output_dir + "/proba_"+os.path.basename(file_img),
                 cropped_proba )    
Esempio n. 4
0
def mask_image(file_img, file_mask, ga, r, neigh, output_dir):
    img = irtk.imread(file_img, dtype='float32')

    input_mask = irtk.imread(file_mask)

    print "predicting..."
    res = irtk.zeros(img.get_header(), dtype='float32')
    res2 = irtk.zeros(img.get_header(), dtype='float32')
    res3 = irtk.zeros(img.get_header(), dtype='float32')
    res4 = irtk.zeros(img.get_header(), dtype='uint8')
    mask = irtk.ones(input_mask.get_header(), dtype='uint8')
    mask[input_mask == 2] = 0
    for z in xrange(img.shape[0]):
        print z
        YX = np.transpose(np.nonzero(mask[z]))
        if YX.shape[0] == 0:
            continue  # this slice does not intersect the box
        patches = extract_patches2D(img[z], r, YX)
        patches = np.reshape(
            patches, (patches.shape[0], patches.shape[1] * patches.shape[2]))

        predictions = neigh.predict_proba(patches)[:, 1]
        res[z, YX[:, 0], YX[:, 1]] = predictions

    x_min, y_min, z_min, x_max, y_max, z_max = mask.bbox()

    proba = res[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]

    if args.mass:
        BV = get_BV(args.ga)
        box_volume = (z_max - z_min) * img.header['pixelSize'][2] * (
            y_max - y_min) * img.header['pixelSize'][1] * (
                x_max - x_min) * img.header['pixelSize'][0]
        ratio = float(BV) / float(box_volume)
        print "ratio", ratio
        q0, q1 = mquantiles(proba.flatten(),
                            prob=[0.5 * (1.0 - ratio), 1.0 - 0.5 * ratio])
        print "threshold", q0, q1
        #threshold = max(0.5,threshold)

        # labels = res[z_min:z_max+1,
        #              y_min:y_max+1,
        #              x_min:x_max+1] > threshold

        #res = 1 / (np.exp(-(res-threshold)/(res.max()-res.min())))

        res[res < q0] = q0
        res[res > q1] = q1
        res -= res.min()
        res /= res.max()

    labels = res[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1] > 0.5

    proba = res[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]

    cropped_img = img[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]

    if args.do_3D:
        labels = irtk.crf(cropped_img,
                          labels,
                          proba,
                          l=args.l,
                          sigma=get_noiseXY(cropped_img),
                          sigmaZ=get_noiseZ(cropped_img))
    # elif args.do_patchZ:
    #     labels = irtk.crf_patchZ( cropped_img,
    #                               labels,
    #                               proba,
    #                               l=10.0 )
    # else:
    #     for z in xrange(z_min,z_max+1):
    #         labels[z] = irtk.crf( cropped_img[z],
    #                               labels[z],
    #                               proba[z],
    #                               l=1.0 )

    print "MAX LABEL:", labels.max()
    irtk.imwrite(output_dir + "/bare_" + os.path.basename(file_img), labels)
    tmp = irtk.zeros(img.get_header(), dtype='uint8')
    tmp[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1] = labels
    (min_x_bare, min_y_bare, min_z_bare, max_x_bare, max_y_bare,
     max_z_bare) = tmp.bbox()

    if not args.no_cleaning:
        # clean by fitting ellipses enlarged of 10%
        for z in xrange(labels.shape[0]):
            edges = nd.morphological_gradient(labels[z] > 0, size=5)
            points = np.transpose(edges.nonzero())[:, ::-1]
            if len(points) == 0:
                continue
            points = np.array(map(lambda x: [x], points), dtype='int32')
            ellipse = cv2.fitEllipse(points)
            cv2.ellipse(
                labels[z],
                (ellipse[0],
                 (1.1 * ellipse[1][0], 1.1 * ellipse[1][1]), ellipse[2]), 1,
                -1)

    irtk.imwrite(output_dir + "/seg_" + os.path.basename(file_img), labels)
    irtk.imwrite(output_dir + "/res_" + os.path.basename(file_img), res)

    # re-read the image in case we processed it
    img = irtk.imread(file_img, dtype='float32')
    cropped_img = img[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]
    cropped_img[labels == 0] = -1
    masked = cropped_img.bbox(crop=True)
    irtk.imwrite(output_dir + "/masked_" + os.path.basename(file_img), masked)

    # re-read the image in case we processed it
    img = irtk.imread(file_img, dtype='float32')
    x0 = min_x_bare + (max_x_bare - min_x_bare) / 2
    y0 = min_y_bare + (max_y_bare - min_y_bare) / 2
    ofd = get_OFD(ga) / img.header['pixelSize'][0]

    cropped_img = img[min_z_bare:max_z_bare + 1,
                      max(0, int(round(y0 - ofd / 2))
                          ):min(img.shape[1], int(round(y0 + ofd / 2 + 1))),
                      max(0, int(round(x0 - ofd / 2))
                          ):min(img.shape[2], int(round(x0 + ofd / 2 +
                                                        1)))].copy()

    irtk.imwrite(output_dir + "/very_large_" + os.path.basename(file_img),
                 cropped_img)

    cropped_proba = res[min_z_bare:max_z_bare + 1,
                        max(0, int(round(y0 - ofd / 2))
                            ):min(img.shape[1], int(round(y0 + ofd / 2 + 1))),
                        max(0, int(round(x0 - ofd / 2))
                            ):min(img.shape[2], int(round(x0 + ofd / 2 +
                                                          1)))].copy()

    irtk.imwrite(output_dir + "/proba_" + os.path.basename(file_img),
                 cropped_proba)