Ejemplo n.º 1
0
def simulate_2d_gaussian_psf(sizes, steps, starts, centre, width, depth_dependent_width):
    """simulate the image of point source at location centre in
    translated along dimension l and having a gaussian profile in x
    with a minimum width specified by width and an optional l (or
    depth dependence)

    sizes :  (Nx, Nl)   dimensions of simulated image
    steps :  (sx, sl)   voxel size in x and l dimensions
    starts : (cx, cl)   centre of 0,0 voxel
    width  :  width in x of gaussian
    depth_dependent_width : additional width term which is proportional to l-cl and combines in quadrature with base width
    """

    # alloc array
    img = py_minc.ArrayVolume((1, sizes[0], sizes[1]), dimension_names = ('zspace', 'xspace', 'lspace'), 
                        nc_data_type = py_minc.NC_SHORT, typecode = float_)
    img.set_starts((0, starts[0], starts[1]))
    img.set_separations((1, steps[0], steps[1]))
                  
    # iterate over voxels
    for j in range(sizes[1]):
        l = starts[1] + j*steps[1]
        dl = l - centre[1] # coordinate relative to focal plane

        combined_width_sq = width**2 + (dl*depth_dependent_width)**2
        c = 1.0/sqrt(2*pi*combined_width_sq)

        for i in range(sizes[0]):
            x = starts[0] + i*steps[0]
            dx = x - centre[0]   # coordinate relative to centre
            
            img.array[0,i,j] = c*exp(-.5*dx**2/combined_width_sq) # evaluate gaussian
    
    return img
Ejemplo n.º 2
0
def simulate_point_sinogram(sizes, steps, starts, psf, position):
    """simulate the sinogram generated by a point at specified position that is degrade by the specified psf

    sizes  :  (Nx, Nphi)   dimensions of image
    steps  :  (sx, sphi)   voxel size in x and l dimensions
    starts :  (cx, cphi)   centre of 0,0 voxel
    psf    :  ArrayVolume specifying psf
    position :  position or point object 

    Note centre of rotation is assumed to be at x = 0, y = 0
    """

    # alloc array
    sino = py_minc.ArrayVolume((1, sizes[0], sizes[1]), dimension_names = ('zspace', 'xspace', 'phispace'), 
                        nc_data_type = py_minc.NC_SHORT, typecode = float_)
    sino.set_starts((0, starts[0], starts[1]))
    sino.set_separations((1, steps[0], steps[1]))
    
    # convert point location to polar coordinates
    r = sqrt(position[0]**2+position[1]**2)
    theta = arctan2(position[0], position[1])
    
    psf_starts = psf.get_starts()
    psf_steps = psf.get_separations()
    psf_sizes = psf.get_sizes()
    x_values = psf_starts[1] + arange(psf_sizes[1])*psf_steps[1]
    l_values = psf_starts[2] + arange(psf_sizes[2])*psf_steps[2]
    interp_psf = bilinear_interp(x_values, l_values, psf.array[0])
    
    # iterate over angles
    for j in range(sizes[1]):
        phi = starts[1] + j*steps[1]
        dphi = phi - theta # relative rotation of point
        offset = r*sin(dphi)  # compute position of rotated point in detector coord (x,l)
        l = r*cos(dphi)
        
        # iterate over detector elements
        for i in range(sizes[0]):
            x = starts[0] + i*steps[0]
            dx = offset - x   # coordinate relative to centre
            sino.array[0,i,j] = interp_psf(dx, l)
    
    return sino
def additional_seeding(mnc_bin_file, tag_file, all_tags):
    print "****************** additional seeding : ", tag_file

    #create distance_transform (binary input only)
    cmnd = ("mincmorph -clobber -short -successive F %s %s > %s/tmp.log" %
            (mnc_bin_file, mnc_bin_file[:-4] + "_dt.mnc",
             os.path.dirname(os.path.abspath(mnc_bin_file))))
    print cmnd
    os.system(cmnd)
    #p= subprocess.Popen(cmnd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
    #stdout, stderr = p.communicate()
    ##p.wait()

    volume_dt = py_minc.ArrayVolume(
        mnc_bin_file[:-4] + "_dt.mnc"
    )  # without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image

    size = volume_dt.get_sizes()

    tags = py_minc.VolumeTags(1)

    for z in range(size[0]):
        for y in range(size[1]):
            for x in range(size[2]):
                dt_value = volume_dt.array[z, y, x]

                if dt_value >= 0.5:
                    dt_value_world_location = volume_dt.convert_voxel_to_world(
                        np.array([z, y, x]))  #return world in [x,y,z]
                    if not list(dt_value_world_location) in all_tags:
                        tags.append(dt_value_world_location, 1, 1, 1, 1)

    if tags.number() > 0:
        tags.output(tag_file)
        print "****************** additional seeding : ", tag_file, " DONE! ", tags.number(
        ), " seeds created!\n"
        return True
    else:
        print "****************** No additional seed can be added!\n"
        return False
Ejemplo n.º 4
0
def newmincfile(dims,ord=(py_minc.MIzspace,py_minc.MIyspace,py_minc.MIxspace), \
    ncdt=py_minc.NC_FLOAT,tc=float32):
    a = py_minc.ArrayVolume(dims, ord, nc_data_type=ncdt, typecode=tc)
    return a
Ejemplo n.º 5
0
def openmincfile(filename, dn=py_minc.FILE_ORDER_DIMENSION_NAMES, tc=int16):
    a = py_minc.ArrayVolume(filename, dim_names=dn, typecode=tc)
    return a
        raise SystemExit, \
            "The --clobber option is needed to overwrite an existing file."


    try:
        g, attributes = graph_analysis.input_graph(graph_file, ["history", "vertex_offsets"])  	# open graph data and copy contents to memory
        print ("Successfully read in the %s\n" %graph_file)	
        sys.stdout.flush()
    except:
        print("Error reading in the %s \n" %graph_file)
        sys.stdout.flush()



    #### mri_distance feature:
    mri_atlas = py_minc.ArrayVolume(mr_atlas_file, nc_data_type=py_minc.NC_BYTE)# without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image	
    sizes = mri_atlas.get_sizes()
    mri_labels =[]
    for z_vox in range(sizes[0]):
        for y_vox in range(sizes[1]):
            for x_vox in range(sizes[2]):
                if mri_atlas.array[z_vox,y_vox,x_vox]>0 and mri_atlas.array[z_vox,y_vox,x_vox] not in mri_labels:
                    mri_labels.append(mri_atlas.array[z_vox,y_vox,x_vox])
    mri_labels=map(lambda x:int(round(x)), mri_labels)
    
    
    for l in mri_labels:
        #print "mri_label",l
        sys.stdout.flush()
        mri_atlas = py_minc.ArrayVolume(mr_atlas_file[:-4]+"_%d_dt.mnc" %l, nc_data_type=py_minc.NC_BYTE)# without this always voxels[z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image	
        for e in g.edge_list():
Ejemplo n.º 7
0
    def buildPipeline(self):
        #def create_subvolumes (minc_file,subvol_nums, overlap=10):
        """v0min v0max v1min v1max v2min v2max",
        only process a subvolume specified by the bounds in voxel coordinates: v0min <= v0 < v0max, v1min <= v1 < v1max, v2min <= v2 < v2max"   
        create subvolumes 6 parameters to be passed to each parallel process of vesselTracking."""
        v0min = []  #x
        v0max = []  #x
        v1min = []  #y
        v1max = []  #y
        v2min = []  #z
        v2max = []  #z
        #img = pymincf.volumeFromFile(self.minc_file)
        #sizes = img.getSizes()      # z_vox(sizes[0]), y_vox(sizes[1]),x_vox(sizes[2])
        #self.spacing = img.getSeparations()# z_vox(sizes[0]), y_vox(sizes[1]),x_vox(sizes[2])
        #origin = img.getStarts()# z_vox(sizes[0]), y_vox(sizes[1]),x_vox(sizes[2])
        img = py_minc.ArrayVolume(
            self.minc_file
        )  # without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
        sizes = img.get_sizes(
        )  # z_vox(sizes[0]), y_vox(sizes[1]),x_vox(sizes[2])
        self.spacing = img.get_separations(
        )  # z_vox(sizes[0]), y_vox(sizes[1]),x_vox(sizes[2])
        origin = img.get_starts(
        )  # z_vox(sizes[0]), y_vox(sizes[1]),x_vox(sizes[2])

        if self.subvol_nums > 27:
            self.subvol_nums = 27
        if self.subvol_nums < 1:
            self.subvol_nums = 1

        if self.subvol_nums == 1:
            self.input_subvols.append(self.minc_file)
        else:
            [xdiv, ydiv, zdiv] = self.make_subvol_indx()
            #### crop the mincfile into each subvolume
            subv = 0
            for i in range(xdiv):
                for j in range(ydiv):
                    for k in range(zdiv):
                        subvol_minc_file = self.minc_file[:-4] + "_crop" + str(
                            subv) + ".mnc"
                        v0min = max(0, int(i * sizes[2] / xdiv) - self.overlap)
                        v0max = min(
                            sizes[2],
                            int((i + 1) * sizes[2] / xdiv) + self.overlap)
                        v1min = max(0, int(j * sizes[1] / ydiv) - self.overlap)
                        v1max = min(
                            sizes[1],
                            int((j + 1) * sizes[1] / ydiv) + self.overlap)
                        v2min = max(0, int(k * sizes[0] / zdiv) - self.overlap)
                        v2max = min(
                            sizes[0],
                            int((k + 1) * sizes[0] / zdiv) + self.overlap)

                        self.nel = [
                            v0max - v0min, v1max - v1min, v2max - v2min
                        ]  #x,y,z
                        self.strts = [
                            origin[2] + (v0min * self.spacing[2]),
                            origin[1] + (v1min * self.spacing[1]),
                            origin[0] + (v2min * self.spacing[0])
                        ]  #x,y,z
                        """Resample minc_file into space of subvol_minc_file
                        Here, we add stages of the pipeline that is defined in the main file (subvolume_vessel_tracking)"""
                        if self.clobber or not file_exists(subvol_minc_file):
                            self.mincResampler(subvol_minc_file)
                        self.input_subvols.append(subvol_minc_file)
                        #resample = ma.mincresample(self.minc_file, subvol_minc_file, likeFile=self.minc_file, argArray=["-clobber", "-step %f %f %f" %(self.spacing[2],self.spacing[1],self.spacing[0]),"-nelements %d %d %d" %(self.nel[0],self.nel[1],self.nel[2]),"-start %f %f %f" %(self.strts[0],self.strts[1], self.strts[2])])
                        #self.p.addStage(resample)
                        #print self.p.cmd
                        #self.input_subvols.append(resample.outputFiles[0])
                        subv += 1
Ejemplo n.º 8
0
    if not options.clobber and os.path.exists(output_file):
        raise SystemExit, \
            "The --clobber option is needed to overwrite an existing file."

    # reads in the graph to be labeled
    try:
        g, attributes = graph_analysis.input_graph(
            input_file, ["history", "vertex_offsets"])
        print("Succefully read in the %s\n" % input_file)
    except:
        print("Error reading in the %s\n" % input_file)

    # read in the labeled CT : used to make labling training dataset
    #labeled_ct=py_minc.ArrayVolume(labeled_CT_file,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES) #which is in [x,y,z]
    labeled_ct = py_minc.ArrayVolume(
        labeled_CT_file
    )  # without this always [z,y,x], with this :dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
    #

    g = edge_labeling(g, labeled_ct)
    #history = history + '\n>>> %s: %s' % (time.ctime(time.time()), "edge_labeling")		##argv = ['code.py', 'input.db', 'output']
    history = '\n>>> %s: %s' % (time.ctime(time.time()), string.join(argv)
                                )  ##argv = ['code.py', 'input.db', 'output']
    if attributes.has_key("history"):
        history = attributes["history"] + "\n" + history
        del attributes['history']
    graph_analysis.output_graph(output_file, g, history, attributes)
    print("Succefully wrote the %s\n" % output_file)

    g = label_propagate(g, 0)
    #history = history + '\n>>> %s: %s' % (time.ctime(time.time()), "edge_labeling")		##argv = ['code.py', 'input.db', 'output']
Ejemplo n.º 9
0
from scipy import *
import py_minc
from scipy.optimize import leastsq


def gaussian(parameters, y, x):

    a, b, c, d, e, f = parameters
    asdf = e * exp(-((x - a) / b)**2) * exp(-((x - c) / d)**2) - f
    err = y - asdf
    return err


filen = 'exp7/sl0.mnc'
a = py_minc.ArrayVolume(filen, typecode=int16)
views, null, dets = a.get_sizes()
im1 = squeeze(a.array)[700:800, 100:200]

filen = 'exp7/sl399.mnc'
a = py_minc.ArrayVolume(filen, typecode=int16)
views, null, dets = a.get_sizes()
im2 = squeeze(a.array)[700:800, 100:200]

dlist = ravel(im1).tolist()
mx = max(ravel(im1))
flr = mean(ravel(im1))
ind = dlist.index(mx)

indx = ind / 100
indy = mod(ind, 100)
Ejemplo n.º 10
0
from scipy import *
import py_minc


fls = [ "exp2/slice448.mnc", "exp3/slice293.mnc", "exp4/slice286.mnc", "exp5/slice299.mnc",
		"exp6/slice1077.mnc",  "exp7/slice746.mnc",  "exp8/slice752.mnc", "exp9/slice793.mnc" ]

psf_ffts = zeros((8,400,1036),Complex64)
sgs = zeros((8,400,1036),float32)

i = 0

for fl in fls:
	print "Analyzing", fl
	a = py_minc.ArrayVolume(fl,typecode=float32)
	b = squeeze(a.array)
	sgs[i,:,:] = b
	for j in range(400):
		psf_ffts[i,j,:] = fftshift(fft(fftshift(b[j,:])))
	i = i + 1

inv = 1

def showwhere(im,fact=1.0):
	if(inv):
		imshow(-where(im>fact*max(ravel(im)),fact*max(ravel(im)),im))
	else:
		imshow(where(im>fact*max(ravel(im)),fact*max(ravel(im)),im))

def showmag(num, fact=1.0):
Ejemplo n.º 11
0
				#print "in R2"

	return mask
				

###################################
### MAIN STARTS HERE ##############
###################################

slope = 0.6
max_intercept = 0.3*slope
viewmax = 1/pi/2.
detmax = 0.4
file = "exp3/slice293.mnc"

a = py_minc.ArrayVolume(file)
sg = squeeze(a.array)
sg_fft = fftshift(fft2(fftshift(sg)))

views, dets = shape(sg_fft)

newsg_fft = zeros((views*3,dets),Complex64)
newsg_fft[0:views,:] = sg_fft
newsg_fft[views:views*2,:] = sg_fft
newsg_fft[views*2:views*3,:] = sg_fft

viewsgfft = where(abs(newsg_fft)>7000,7000,abs(newsg_fft))

newviews,newdets = shape(newsg_fft)

mask = zeros(shape(newsg_fft),Int8)
def seeding(mnc_bin_file, tag_file, connectivity, all_tags):
    print "****************** seeding : ", tag_file

    #create distance_transform (binary input only)
    cmnd = ("mincmorph -clobber -short -successive F %s %s > %s/tmp.log" %
            (mnc_bin_file, mnc_bin_file[:-4] + "_dt.mnc",
             os.path.dirname(os.path.abspath(mnc_bin_file))))
    print cmnd
    os.system(cmnd)
    #p= subprocess.Popen(cmnd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
    #stdout, stderr = p.communicate()
    ##p.wait()

    #create group file
    cmnd = ("mincmorph -clobber -short -group -%s %s %s > %s/tmp.log" %
            (connectivity, mnc_bin_file, mnc_bin_file[:-4] + "_group.mnc",
             os.path.dirname(os.path.abspath(mnc_bin_file))))
    print cmnd
    os.system(cmnd)
    #p= subprocess.Popen(cmnd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
    #stdout, stderr = p.communicate()
    ##p.wait()

    dt_img = py_minc.ArrayVolume(
        mnc_bin_file[:-4] + "_dt.mnc"
    )  # without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
    group_img = py_minc.ArrayVolume(
        mnc_bin_file[:-4] + "_group.mnc"
    )  # without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image

    sizes = dt_img.get_sizes()
    #print "\n\nsize of ", group_filename," is ",sizes, "\n\n"

    component_maximum = {}
    for z_vox in range(sizes[0]):
        for y_vox in range(sizes[1]):
            for x_vox in range(sizes[2]):
                g_value = int(round(group_img.array[z_vox, y_vox, x_vox]))
                if g_value > 0:
                    dt_value = int(round(dt_img.array[z_vox, y_vox, x_vox]))
                    if g_value not in component_maximum.keys():
                        component_maximum[g_value] = [
                            dt_value, z_vox, y_vox, x_vox
                        ]
                    else:
                        if dt_value > component_maximum[g_value][0]:
                            component_maximum[g_value] = [
                                dt_value, z_vox, y_vox, x_vox
                            ]

    #descending sort tag components based on value (dt_value)
    sorted_component_maximum = sorted(
        component_maximum.iteritems(),
        key=operator.itemgetter(1),
        reverse=True)  #result is not dict, list of tuples=(key,val)
    tags = py_minc.VolumeTags(1)

    for i in range(len(sorted_component_maximum)):
        voxel_location = np.array([
            sorted_component_maximum[i][1][1],
            sorted_component_maximum[i][1][2],
            sorted_component_maximum[i][1][3]
        ])
        world_location = dt_img.convert_voxel_to_world(voxel_location)
        if not list(world_location) in all_tags:
            tags.append(world_location, 0.05, 1, 1, 1)
            all_tags.append(list(world_location))

    if tags.number() > 0:
        tags.output(tag_file)
        print "****************** seeding : ", tag_file, " DONE! ", tags.number(
        ), " seeds created!\n"
        return True, all_tags
    else:
        print "****************** No seed can be added!\n"
        return False, all_tags
Ejemplo n.º 13
0
subpix_stepsize = 0.1

## THESE ARE ONLY TEMPORARY TEST VARIABLES, DON'T USE THESE IF REALLY RUNNING SCRIPT

views = 400
dets = 1036
slices = 1360
reconsize = 1036

from scipy import *

ff = zeros((views,dets),float32)

from tomography import projections
pj = projections.Projections()
pj.read("/tmp/mytest.pj")
dat = pj.get_data()
g1 = shape(dat)[1]
g2 = dets

left = (g1 - g2)/2  ## Note: These will always be even
right = (g1 + g2)/2 ## as it is either odd-odd or even-even

ff = dat[:,left:right]

import py_minc

a = py_minc.ArrayVolume("exp7/slice746.mnc")

ff = squeeze(a.array).astype(float32)