Exemplo n.º 1
0
def visualize_warp(fname_warp, fname_grid=None, step=3, rm_tmp=True):
    if fname_grid is None:
        from numpy import zeros
        tmp_dir = tmp_create()
        im_warp = Image(fname_warp)
        status, out = sct.run(['fslhd', fname_warp])
        curdir = os.getcwd()
        os.chdir(tmp_dir)
        dim1 = 'dim1           '
        dim2 = 'dim2           '
        dim3 = 'dim3           '
        nx = int(
            out[out.find(dim1):][len(dim1):out[out.find(dim1):].find('\n')])
        ny = int(
            out[out.find(dim2):][len(dim2):out[out.find(dim2):].find('\n')])
        nz = int(
            out[out.find(dim3):][len(dim3):out[out.find(dim3):].find('\n')])
        sq = zeros((step, step))
        sq[step - 1] = 1
        sq[:, step - 1] = 1
        dat = zeros((nx, ny, nz))
        for i in range(0, dat.shape[0], step):
            for j in range(0, dat.shape[1], step):
                for k in range(dat.shape[2]):
                    if dat[i:i + step, j:j + step, k].shape == (step, step):
                        dat[i:i + step, j:j + step, k] = sq
        fname_grid = 'grid_' + str(step) + '.nii.gz'
        im_grid = Image(param=dat)
        grid_hdr = im_warp.hdr
        im_grid.hdr = grid_hdr
        im_grid.setFileName(fname_grid)
        im_grid.save()
        fname_grid_resample = add_suffix(fname_grid, '_resample')
        sct.run([
            'sct_resample', '-i', fname_grid, '-f', '3x3x1', '-x', 'nn', '-o',
            fname_grid_resample
        ])
        fname_grid = tmp_dir + fname_grid_resample
        os.chdir(curdir)
    path_warp, file_warp, ext_warp = extract_fname(fname_warp)
    grid_warped = path_warp + extract_fname(
        fname_grid)[1] + '_' + file_warp + ext_warp
    sct.run([
        'sct_apply_transfo', '-i', fname_grid, '-d', fname_grid, '-w',
        fname_warp, '-o', grid_warped
    ])
    if rm_tmp:
        sct.rmtree(tmp_dir)
Exemplo n.º 2
0
def visualize_warp(fname_warp, fname_grid=None, step=3, rm_tmp=True):
    if fname_grid is None:
        from numpy import zeros
        tmp_dir = tmp_create()
        im_warp = Image(fname_warp)
        status, out = run('fslhd ' + fname_warp)
        from os import chdir
        chdir(tmp_dir)
        dim1 = 'dim1           '
        dim2 = 'dim2           '
        dim3 = 'dim3           '
        nx = int(
            out[out.find(dim1):][len(dim1):out[out.find(dim1):].find('\n')])
        ny = int(
            out[out.find(dim2):][len(dim2):out[out.find(dim2):].find('\n')])
        nz = int(
            out[out.find(dim3):][len(dim3):out[out.find(dim3):].find('\n')])
        sq = zeros((step, step))
        sq[step - 1] = 1
        sq[:, step - 1] = 1
        dat = zeros((nx, ny, nz))
        for i in range(0, dat.shape[0], step):
            for j in range(0, dat.shape[1], step):
                for k in range(dat.shape[2]):
                    if dat[i:i + step, j:j + step, k].shape == (step, step):
                        dat[i:i + step, j:j + step, k] = sq
        fname_grid = 'grid_' + str(step) + '.nii.gz'
        im_grid = Image(param=dat)
        grid_hdr = im_warp.hdr
        im_grid.hdr = grid_hdr
        im_grid.setFileName(fname_grid)
        im_grid.save()
        fname_grid_resample = add_suffix(fname_grid, '_resample')
        run('sct_resample -i ' + fname_grid + ' -f 3x3x1 -x nn -o ' +
            fname_grid_resample)
        fname_grid = tmp_dir + fname_grid_resample
        chdir('..')
    path_warp, file_warp, ext_warp = extract_fname(fname_warp)
    grid_warped = path_warp + extract_fname(
        fname_grid)[1] + '_' + file_warp + ext_warp
    run('sct_apply_transfo -i ' + fname_grid + ' -d ' + fname_grid + ' -w ' +
        fname_warp + ' -o ' + grid_warped)
    if rm_tmp:
        run('rm -rf ' + tmp_dir, error_exit='warning')
def visualize_warp(fname_warp, fname_grid=None, step=3, rm_tmp=True):
    if fname_grid is None:
        from numpy import zeros
        tmp_dir = sct.tmp_create()
        im_warp = Image(fname_warp)
        os.chdir(tmp_dir)

        assert len(im_warp.data.shape
                   ) == 5, 'ERROR: Warping field does bot have 5 dimensions...'
        nx, ny, nz, nt, ndimwarp = im_warp.data.shape

        # nx, ny, nz, nt, px, py, pz, pt = im_warp.dim
        # This does not work because dimensions of a warping field are not correctly read : it would be 1,1,1,1,1,1,1,1

        sq = zeros((step, step))
        sq[step - 1] = 1
        sq[:, step - 1] = 1
        dat = zeros((nx, ny, nz))
        for i in range(0, dat.shape[0], step):
            for j in range(0, dat.shape[1], step):
                for k in range(dat.shape[2]):
                    if dat[i:i + step, j:j + step, k].shape == (step, step):
                        dat[i:i + step, j:j + step, k] = sq
        fname_grid = 'grid_' + str(step) + '.nii.gz'
        im_grid = Image(param=dat)
        grid_hdr = im_warp.hdr
        im_grid.hdr = grid_hdr
        im_grid.setFileName(fname_grid)
        im_grid.save()
        fname_grid_resample = sct.add_suffix(fname_grid, '_resample')
        sct.run('sct_resample -i ' + fname_grid + ' -f 3x3x1 -x nn -o ' +
                fname_grid_resample)
        fname_grid = tmp_dir + fname_grid_resample
        os.chdir('..')
    path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp)
    grid_warped = path_warp + 'grid_warped_gm' + ext_warp
    sct.run('sct_apply_transfo -i ' + fname_grid + ' -d ' + fname_grid +
            ' -w ' + fname_warp + ' -o ' + grid_warped)
    if rm_tmp:
        sct.run('rm -rf ' + tmp_dir, error_exit='warning')
    return grid_warped
def visualize_warp(fname_warp, fname_grid=None, step=3, rm_tmp=True):
    if fname_grid is None:
        from numpy import zeros

        tmp_dir = sct.tmp_create()
        im_warp = Image(fname_warp)
        os.chdir(tmp_dir)

        assert len(im_warp.data.shape) == 5, "ERROR: Warping field does bot have 5 dimensions..."
        nx, ny, nz, nt, ndimwarp = im_warp.data.shape

        # nx, ny, nz, nt, px, py, pz, pt = im_warp.dim
        # This does not work because dimensions of a warping field are not correctly read : it would be 1,1,1,1,1,1,1,1

        sq = zeros((step, step))
        sq[step - 1] = 1
        sq[:, step - 1] = 1
        dat = zeros((nx, ny, nz))
        for i in range(0, dat.shape[0], step):
            for j in range(0, dat.shape[1], step):
                for k in range(dat.shape[2]):
                    if dat[i : i + step, j : j + step, k].shape == (step, step):
                        dat[i : i + step, j : j + step, k] = sq
        fname_grid = "grid_" + str(step) + ".nii.gz"
        im_grid = Image(param=dat)
        grid_hdr = im_warp.hdr
        im_grid.hdr = grid_hdr
        im_grid.setFileName(fname_grid)
        im_grid.save()
        fname_grid_resample = sct.add_suffix(fname_grid, "_resample")
        sct.run("sct_resample -i " + fname_grid + " -f 3x3x1 -x nn -o " + fname_grid_resample)
        fname_grid = tmp_dir + fname_grid_resample
        os.chdir("..")
    path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp)
    grid_warped = path_warp + "grid_warped_gm" + ext_warp
    sct.run("sct_apply_transfo -i " + fname_grid + " -d " + fname_grid + " -w " + fname_warp + " -o " + grid_warped)
    if rm_tmp:
        sct.run("rm -rf " + tmp_dir, error_exit="warning")
    return grid_warped
Exemplo n.º 5
0
def visualize_warp(fname_warp, fname_grid=None, step=3, rm_tmp=True):
    if fname_grid is None:
        from numpy import zeros
        tmp_dir = sct.tmp_create()
        im_warp = Image(fname_warp)
        curdir = os.getcwd()
        os.chdir(tmp_dir)

        assert len(im_warp.data.shape) == 5, 'ERROR: Warping field does bot have 5 dimensions...'
        nx, ny, nz, nt, ndimwarp = im_warp.data.shape

        # nx, ny, nz, nt, px, py, pz, pt = im_warp.dim
        # This does not work because dimensions of a warping field are not correctly read : it would be 1,1,1,1,1,1,1,1

        sq = zeros((step, step))
        sq[step - 1] = 1
        sq[:, step - 1] = 1
        dat = zeros((nx, ny, nz))
        for i in range(0, dat.shape[0], step):
            for j in range(0, dat.shape[1], step):
                for k in range(dat.shape[2]):
                    if dat[i:i + step, j:j + step, k].shape == (step, step):
                        dat[i:i + step, j:j + step, k] = sq
        fname_grid = 'grid_' + str(step) + '.nii.gz'
        im_grid = Image(param=dat)
        grid_hdr = im_warp.hdr
        im_grid.hdr = grid_hdr
        im_grid.setFileName(fname_grid)
        im_grid.save()
        fname_grid_resample = sct.add_suffix(fname_grid, '_resample')
        sct.run(['sct_resample', '-i', fname_grid, '-f', '3x3x1', '-x', 'nn', '-o', fname_grid_resample])
        fname_grid = os.path.join(tmp_dir, fname_grid_resample)
        os.chdir(curdir)
    path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp)
    grid_warped = os.path.join(path_warp, 'grid_warped_gm' + ext_warp)
    sct.run(['sct_apply_transfo', '-i', fname_grid, '-d', fname_grid, '-w', fname_warp, '-o', grid_warped])
    if rm_tmp:
        sct.rmtree(tmp_dir)
    return grid_warped
Exemplo n.º 6
0
def visualize_warp(fname_warp, fname_grid=None, step=3, rm_tmp=True):
    if fname_grid is None:
        from numpy import zeros
        tmp_dir = tmp_create()
        im_warp = Image(fname_warp)
        status, out = run('fslhd '+fname_warp)
        from os import chdir
        chdir(tmp_dir)
        dim1 = 'dim1           '
        dim2 = 'dim2           '
        dim3 = 'dim3           '
        nx = int(out[out.find(dim1):][len(dim1):out[out.find(dim1):].find('\n')])
        ny = int(out[out.find(dim2):][len(dim2):out[out.find(dim2):].find('\n')])
        nz = int(out[out.find(dim3):][len(dim3):out[out.find(dim3):].find('\n')])
        sq = zeros((step, step))
        sq[step-1] = 1
        sq[:, step-1] = 1
        dat = zeros((nx, ny, nz))
        for i in range(0, dat.shape[0], step):
            for j in range(0, dat.shape[1], step):
                for k in range(dat.shape[2]):
                    if dat[i:i+step, j:j+step, k].shape == (step, step):
                        dat[i:i+step, j:j+step, k] = sq
        fname_grid = 'grid_'+str(step)+'.nii.gz'
        im_grid = Image(param=dat)
        grid_hdr = im_warp.hdr
        im_grid.hdr = grid_hdr
        im_grid.setFileName(fname_grid)
        im_grid.save()
        fname_grid_resample = add_suffix(fname_grid, '_resample')
        run('sct_resample -i '+fname_grid+' -f 3x3x1 -x nn -o '+fname_grid_resample)
        fname_grid = tmp_dir+fname_grid_resample
        chdir('..')
    path_warp, file_warp, ext_warp = extract_fname(fname_warp)
    grid_warped = path_warp+extract_fname(fname_grid)[1]+'_'+file_warp+ext_warp
    run('sct_apply_transfo -i '+fname_grid+' -d '+fname_grid+' -w '+fname_warp+' -o '+grid_warped)
    if rm_tmp:
        run('rm -rf '+tmp_dir, error_exit='warning')
def resample():
    # extract resampling factor
    sct.printv('\nParse resampling factor...', param.verbose)
    factor_split = param.factor.split('x')
    factor = [float(factor_split[i]) for i in range(len(factor_split))]
    # check if it has three values
    if not len(factor) == 3:
        sct.printv('\nERROR: factor should have three dimensions. E.g., 2x2x1.\n', 1, 'error')
    else:
        fx, fy, fz = [float(factor_split[i]) for i in range(len(factor_split))]

    # Extract path/file/extension
    path_data, file_data, ext_data = sct.extract_fname(param.fname_data)
    path_out, file_out, ext_out = path_data, file_data, ext_data
    if param.fname_out != '':
        file_out = sct.extract_fname(param.fname_out)[1]
    else:
        file_out.append(param.file_suffix)

    input_im = Image(param.fname_data)

    # Get dimensions of data
    sct.printv('\nGet dimensions of data...', param.verbose)
    nx, ny, nz, nt, px, py, pz, pt = input_im.dim
    sct.printv('  ' + str(nx) + ' x ' + str(ny) + ' x ' + str(nz)+ ' x ' + str(nt), param.verbose)
    dim = 4  # by default, will be adjusted later
    if nt == 1:
        dim = 3
    if nz == 1:
        dim = 2
        #TODO : adapt for 2D too or change description
        sct.run('ERROR (sct_resample): Dimension of input data is different from 3 or 4. Exit program', param.verbose, 'error')

    # Calculate new dimensions
    sct.printv('\nCalculate new dimensions...', param.verbose)
    nx_new = int(round(nx*fx))
    ny_new = int(round(ny*fy))
    nz_new = int(round(nz*fz))
    px_new = px/fx
    py_new = py/fy
    pz_new = pz/fz
    sct.printv('  ' + str(nx_new) + ' x ' + str(ny_new) + ' x ' + str(nz_new)+ ' x ' + str(nt), param.verbose)


    zooms = input_im.hdr.get_zooms()[:3]
    affine = input_im.hdr.get_base_affine()
    new_zooms = (px_new, py_new, pz_new)

    if type(param.interpolation) == int:
        order = param.interpolation
    elif type(param.interpolation) == str and param.interpolation in param.x_to_order.keys():
        order = param.x_to_order[param.interpolation]
    else:
        order = 1
        sct.printv('WARNING: wrong input for the interpolation. Using default value = trilinear', param.verbose, 'warning')

    new_data, new_affine = dp_iso.reslice(input_im.data, affine, zooms, new_zooms, mode=param.mode, order=order)

    new_im = Image(param=new_data)
    new_im.absolutepath = path_out+file_out+ext_out
    new_im.path = path_out
    new_im.file_name = file_out
    new_im.ext = ext_out

    zooms_to_set = list(new_zooms)
    if dim == 4:
        zooms_to_set.append(nt)

    new_im.hdr = input_im.hdr
    new_im.hdr.set_zooms(zooms_to_set)
    new_im.save()

    # to view results
    sct.printv('\nDone! To view results, type:', param.verbose)
    sct.printv('fslview '+param.fname_out+' &', param.verbose, 'info')
    print
def resample():
    # extract resampling factor
    sct.printv('\nParse resampling factor...', param.verbose)
    factor_split = param.factor.split('x')
    factor = [float(factor_split[i]) for i in range(len(factor_split))]
    # check if it has three values
    if not len(factor) == 3:
        sct.printv(
            '\nERROR: factor should have three dimensions. E.g., 2x2x1.\n', 1,
            'error')
    else:
        fx, fy, fz = [float(factor_split[i]) for i in range(len(factor_split))]

    # Extract path/file/extension
    path_data, file_data, ext_data = sct.extract_fname(param.fname_data)
    path_out, file_out, ext_out = path_data, file_data, ext_data
    if param.fname_out != '':
        file_out = sct.extract_fname(param.fname_out)[1]
    else:
        file_out.append(param.file_suffix)

    input_im = Image(param.fname_data)

    # Get dimensions of data
    sct.printv('\nGet dimensions of data...', param.verbose)
    nx, ny, nz, nt, px, py, pz, pt = input_im.dim
    sct.printv(
        '  ' + str(nx) + ' x ' + str(ny) + ' x ' + str(nz) + ' x ' + str(nt),
        param.verbose)
    dim = 4  # by default, will be adjusted later
    if nt == 1:
        dim = 3
    if nz == 1:
        dim = 2
        #TODO : adapt for 2D too or change description
        sct.run(
            'ERROR (sct_resample): Dimension of input data is different from 3 or 4. Exit program',
            param.verbose, 'error')

    # Calculate new dimensions
    sct.printv('\nCalculate new dimensions...', param.verbose)
    nx_new = int(round(nx * fx))
    ny_new = int(round(ny * fy))
    nz_new = int(round(nz * fz))
    px_new = px / fx
    py_new = py / fy
    pz_new = pz / fz
    sct.printv(
        '  ' + str(nx_new) + ' x ' + str(ny_new) + ' x ' + str(nz_new) +
        ' x ' + str(nt), param.verbose)

    zooms = input_im.hdr.get_zooms()[:3]
    affine = input_im.hdr.get_base_affine()
    new_zooms = (px_new, py_new, pz_new)

    if type(param.interpolation) == int:
        order = param.interpolation
    elif type(param.interpolation
              ) == str and param.interpolation in param.x_to_order.keys():
        order = param.x_to_order[param.interpolation]
    else:
        order = 1
        sct.printv(
            'WARNING: wrong input for the interpolation. Using default value = trilinear',
            param.verbose, 'warning')

    new_data, new_affine = dp_iso.reslice(input_im.data,
                                          affine,
                                          zooms,
                                          new_zooms,
                                          mode=param.mode,
                                          order=order)

    new_im = Image(param=new_data)
    new_im.absolutepath = path_out + file_out + ext_out
    new_im.path = path_out
    new_im.file_name = file_out
    new_im.ext = ext_out

    zooms_to_set = list(new_zooms)
    if dim == 4:
        zooms_to_set.append(nt)

    new_im.hdr = input_im.hdr
    new_im.hdr.set_zooms(zooms_to_set)
    new_im.save()

    # to view results
    sct.printv('\nDone! To view results, type:', param.verbose)
    sct.printv('fslview ' + param.fname_out + ' &', param.verbose, 'info')
    print
Exemplo n.º 9
0
def resample():
    # extract resampling factor
    sct.printv('\nParse resampling factor...', param.verbose)
    new_size_split = param.new_size.split('x')
    new_size = [float(new_size_split[i]) for i in range(len(new_size_split))]
    # check if it has three values
    if not len(new_size) == 3:
        sct.printv('\nERROR: new size should have three dimensions. E.g., 2x2x1.\n', 1, 'error')
    else:
        ns_x, ns_y, ns_z = new_size

    # Extract path/file/extension
    path_data, file_data, ext_data = sct.extract_fname(param.fname_data)
    path_out, file_out, ext_out = '', file_data, ext_data
    if param.fname_out != '':
        path_out, file_out, ext_out = sct.extract_fname(param.fname_out)
    else:
        file_out += param.file_suffix
    param.fname_out = path_out+file_out+ext_out

    input_im = Image(param.fname_data)

    # Get dimensions of data
    sct.printv('\nGet dimensions of data...', param.verbose)
    nx, ny, nz, nt, px, py, pz, pt = input_im.dim
    sct.printv('  ' + str(px) + ' x ' + str(py) + ' x ' + str(pz)+ ' x ' + str(pt)+'mm', param.verbose)
    dim = 4  # by default, will be adjusted later
    if nt == 1:
        dim = 3
    if nz == 1:
        dim = 2
        sct.run('ERROR (sct_resample): Dimension of input data is different from 3 or 4. Exit program', param.verbose, 'error')

    # Calculate new dimensions
    sct.printv('\nCalculate new dimensions...', param.verbose)
    if param.new_size_type == 'factor':
        px_new = px/ns_x
        py_new = py/ns_y
        pz_new = pz/ns_z
    elif param.new_size_type == 'vox':
        px_new = px*nx/ns_x
        py_new = py*ny/ns_y
        pz_new = pz*nz/ns_z
    else:
        px_new = ns_x
        py_new = ns_y
        pz_new = ns_z

    sct.printv('  ' + str(px_new) + ' x ' + str(py_new) + ' x ' + str(pz_new)+ ' x ' + str(pt)+'mm', param.verbose)

    zooms = (px, py, pz)  # input_im.hdr.get_zooms()[:3]
    affine = input_im.hdr.get_qform()  # get_base_affine()
    new_zooms = (px_new, py_new, pz_new)

    if type(param.interpolation) == int:
        order = param.interpolation
    elif type(param.interpolation) == str and param.interpolation in param.x_to_order.keys():
        order = param.x_to_order[param.interpolation]
    else:
        order = 1
        sct.printv('WARNING: wrong input for the interpolation. Using default value = linear', param.verbose, 'warning')

    new_data, new_affine = dp_iso.reslice(input_im.data, affine, zooms, new_zooms, mode=param.mode, order=order)

    new_im = Image(param=new_data)
    new_im.absolutepath = param.fname_out
    new_im.path = path_out
    new_im.file_name = file_out
    new_im.ext = ext_out

    zooms_to_set = list(new_zooms)
    if dim == 4:
        zooms_to_set.append(nt)

    new_im.hdr = input_im.hdr
    new_im.hdr.set_zooms(zooms_to_set)

    # Set the new sform and qform:
    new_im.hdr.set_sform(new_affine)
    new_im.hdr.set_qform(new_affine)

    new_im.save()

    # to view results
    sct.printv('\nDone! To view results, type:', param.verbose)
    sct.printv('fslview '+param.fname_out+' &', param.verbose, 'info')