Exemple #1
0
def clust(elect_coords, n_clusts, iters, init_clusts):
    
   # Load resultant coordinates from Hough circles transform
   #coords = scipy.io.loadmat(elect_coords);
   #dat = coords.get('elect_coords');
   dat = elect_coords;

   # Configure Kmeans
   cluster = sklearn.cluster.KMeans();
   cluster.n_clusters= n_clusts;
   cluster.init = 'k-means++';
   cluster.max_iter = iters;
   cluster.verbose = 0;
   cluster.n_init = init_clusts;
   cluster.fit(dat);

   # Grab vector for plotting each dimension
   x = list(cluster.cluster_centers_[:,0]);
   y = list(cluster.cluster_centers_[:,1]);
   z = list(cluster.cluster_centers_[:,2]);
   c = list(cluster.labels_);

   scipy.io.savemat('k_labels.mat', {'labels':cluster.labels_})
   scipy.io.savemat('k_coords.mat', {'coords':cluster.cluster_centers_})

   # plot the results of kmeans
   cmap = colors.Colormap('hot');
   norm  = colors.Normalize(vmin=1, vmax=10);
   s = 64;
   fig = plt.figure();
   ax = fig.add_subplot(111,projection='3d');
   Axes3D.scatter3D(ax,x,y,z,s=s);
   plt.show(fig);
   
   return cluster.cluster_centers_,cluster.labels_;
Exemple #2
0
def elecDetect(CT_dir, T1_dir, img, thresh, frac, num_gridStrips, n_elects):

    #navigate to dir with CT img
    os.chdir(T1_dir)

    # Extract and apply CT brain mask
    mask_CTBrain(CT_dir, T1_dir, frac)
    masked_img = 'masked_' + img

    # run CT_electhresh
    print "::: Thresholding CT at %f stdv :::" % (thresh)
    electhresh(masked_img, thresh)

    # run im_filt to gaussian smooth thresholded image
    fname = "thresh_" + masked_img
    print "::: Applying guassian smooth of 2.5mm to thresh-CT :::"
    img_filt(fname)

    # run hough transform to detect electrodes
    new_fname = "smoothed_" + fname
    print "::: Applying 2d Hough Transform to localize electrode clusts :::"
    elect_coords = CT_hough(CT_dir, new_fname)

    # set up x,y,z coords to view hough results
    x = elect_coords[:, 0]
    x = x.tolist()
    y = elect_coords[:, 1]
    y = y.tolist()
    z = elect_coords[:, 2]
    z = z.tolist()

    # plot the hough results
    s = 64
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter3D(ax, x, y, z, s=s)
    plt.show(fig)

    # run K means to find grid and strip clusters
    n_clusts = num_gridStrips
    # number of cluster to find = number of electrodes
    iters = 1000
    init_clusts = n_clusts
    print "::: Performing K-means cluster to find %d grid-strip and noise clusters :::" % (
        n_clusts)
    [clust_coords, clust_labels] = clust(elect_coords, n_clusts, iters,
                                         init_clusts)

    # run K means to find electrode center coordinates
    n_clusts = n_elects
    # number of cluster to find = number of electrodes
    iters = 1000
    init_clusts = n_clusts
    print "::: Performing K-means cluster to find %d electrode centers :::" % (
        n_clusts)
    [center_coords, labels] = clust(elect_coords, n_clusts, iters, init_clusts)

    print "::: Finished :::"

    return elect_coords, clust_coords, clust_labels
Exemple #3
0
    def onpick(event):

        # get event indices and x y z coord for click
        ind = event.ind[0];
        x_e, y_e, z_e = event.artist._offsets3d;
        print x_e[ind], y_e[ind], z_e[ind];
        seg_coord = [x_e[ind], y_e[ind], z_e[ind]];
        seg_elecs.append(seg_coord);

        # refresh plot with red dots picked and blue dots clean
        #fig.clf();
        seg_arr = np.array(seg_elecs);
        x_f = seg_arr[:,0];
        y_f = seg_arr[:,1];
        z_f = seg_arr[:,2];
        plt.cla();
        Axes3D.scatter3D(ax,x_f,y_f,z_f,s=150,c='r', picker=5);

        # get array of only clean elecs to re-plot as blue dots
        clean_list = list(coords);
        clean_list = [list(i) for i in clean_list];
        for coordin in clean_list:
                if list(coordin) in seg_elecs:
                    clean_list.pop(clean_list.index(coordin));
        clean_coordis = np.array(clean_list);
        x_c = clean_coordis[:,0];
        y_c = clean_coordis[:,1];
        z_c = clean_coordis[:,2];
        Axes3D.scatter3D(ax,x_c, y_c, z_c, s=150,c='b', picker=5);
        time.sleep(0.5);
        plt.draw();
Exemple #4
0
    def onpick(event):

        # get event indices and x y z coord for click
        ind = event.ind[0];
        x_e, y_e, z_e = event.artist._offsets3d;
        print x_e[ind], y_e[ind], z_e[ind];
        seg_coord = [x_e[ind], y_e[ind], z_e[ind]];
        seg_elecs.append(seg_coord);

        # refresh plot with red dots picked and blue dots clean
        #fig.clf();
        seg_arr = np.array(seg_elecs);
        x_f = seg_arr[:,0];
        y_f = seg_arr[:,1];
        z_f = seg_arr[:,2];
        plt.cla();
        Axes3D.scatter3D(ax,x_f,y_f,z_f,s=150,c='r', picker=5);

        # get array of only clean elecs to re-plot as blue dots
        clean_list = list(coords);
        clean_list = [list(i) for i in clean_list];
        for coordin in clean_list:
                if list(coordin) in seg_elecs:
                    clean_list.pop(clean_list.index(coordin));
        clean_coordis = np.array(clean_list);
        x_c = clean_coordis[:,0];
        y_c = clean_coordis[:,1];
        z_c = clean_coordis[:,2];
        Axes3D.scatter3D(ax,x_c, y_c, z_c, s=150,c='b', picker=5);
        time.sleep(0.5);
        plt.draw();
Exemple #5
0
def clust(elect_coords, n_clusts, iters, init_clusts):

    # Load resultant coordinates from Hough circles transform
    #coords = scipy.io.loadmat(elect_coords);
    #dat = coords.get('elect_coords');
    dat = elect_coords

    # Configure Kmeans
    cluster = sklearn.cluster.KMeans()
    cluster.n_clusters = n_clusts
    cluster.init = 'k-means++'
    cluster.max_iter = iters
    cluster.verbose = 0
    cluster.n_init = init_clusts
    cluster.fit(dat)

    # Grab vector for plotting each dimension
    x = list(cluster.cluster_centers_[:, 0])
    y = list(cluster.cluster_centers_[:, 1])
    z = list(cluster.cluster_centers_[:, 2])
    c = list(cluster.labels_)

    scipy.io.savemat('k_labels.mat', {'labels': cluster.labels_})
    scipy.io.savemat('k_coords.mat', {'coords': cluster.cluster_centers_})

    # plot the results of kmeans
    cmap = colors.Colormap('hot')
    norm = colors.Normalize(vmin=1, vmax=10)
    s = 64
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter3D(ax, x, y, z, s=s)
    plt.show(fig)

    return cluster.cluster_centers_, cluster.labels_
Exemple #6
0
def elecDetect(CT_dir, T1_dir, img, thresh, frac, num_gridStrips, n_elects):

    # navigate to dir with CT img
    os.chdir(T1_dir)

    # Extract and apply CT brain mask
    mask_CTBrain(CT_dir, T1_dir, frac)
    masked_img = "masked_" + img

    # run CT_electhresh
    print "::: Thresholding CT at %f stdv :::" % (thresh)
    electhresh(masked_img, thresh)

    # run im_filt to gaussian smooth thresholded image
    fname = "thresh_" + masked_img
    print "::: Applying guassian smooth of 2.5mm to thresh-CT :::"
    img_filt(fname)

    # run hough transform to detect electrodes
    new_fname = "smoothed_" + fname
    print "::: Applying 2d Hough Transform to localize electrode clusts :::"
    elect_coords = CT_hough(CT_dir, new_fname)

    # set up x,y,z coords to view hough results
    x = elect_coords[:, 0]
    x = x.tolist()
    y = elect_coords[:, 1]
    y = y.tolist()
    z = elect_coords[:, 2]
    z = z.tolist()

    # plot the hough results
    s = 64
    fig = plt.figure()
    ax = fig.add_subplot(111, projection="3d")
    Axes3D.scatter3D(ax, x, y, z, s=s)
    plt.show(fig)

    # run K means to find grid and strip clusters
    n_clusts = num_gridStrips
    # number of cluster to find = number of electrodes
    iters = 1000
    init_clusts = n_clusts
    print "::: Performing K-means cluster to find %d grid-strip and noise clusters :::" % (n_clusts)
    [clust_coords, clust_labels] = clust(elect_coords, n_clusts, iters, init_clusts)

    # run K means to find electrode center coordinates
    n_clusts = n_elects
    # number of cluster to find = number of electrodes
    iters = 1000
    init_clusts = n_clusts
    print "::: Performing K-means cluster to find %d electrode centers :::" % (n_clusts)
    [center_coords, labels] = clust(elect_coords, n_clusts, iters, init_clusts)

    print "::: Finished :::"

    return elect_coords, clust_coords, clust_labels
    def plot(self, ax: Axes3D, obj: Object, zorder: int = 1) -> Axes3D:
        assert obj.points is not None

        ax.scatter3D(obj.points[:, 0],
                     obj.points[:, 1],
                     obj.points[:, 2],
                     c=obj.points[:, 2],
                     cmap=obj.cmap,
                     edgecolors=obj.edgecolors,
                     linewidths=obj.linewidths,
                     s=obj.markersize)

        return ax
Exemple #8
0
def quick_plot_3D(
        ct_data,
        ax: Axes3D = None,
        step_size: int = 50,
        is_long: bool = False,
        is_norm: bool = False,
        base_color: Tuple = (0, 0, 0),
        alpha_max: float = 1.0,
):
    """ Plots subsampled CT/MRI data
  
  Arguments:
      ct_data {Nibabel object data} -- Data from a nibabel object using the .get_fdata() method
        to shorten compute time, send the voxel_to_4D output and set the is_long variable to True.
  
  Keyword Arguments:
      step_size {int} -- sample step size 
        For example this function defaults to 1 point in 50 (default: {50})
      is_long {bool} -- set if precomputed 4D vector array using voxels_to_4D, shortens computation
      is_norm {bool} -- set if data is already normalized from 0 to 1 (default: False)
      base_color {Tuple} -- three value'd tuple of RGB values 
      alpha_max {float} -- value between 0 and 1 for transparancy
  """
    if not is_long:
        long_data = rd.voxels_to_4D(ct_data, is_norm)
    else:
        long_data = ct_data

    if is_norm:
        vals = long_data[::step_size, 3]
    else:
        vals = fct.min_max_normalize(long_data[::step_size, 3])

    if ax is None:
        fig = plt.figure(figsize=(16, 16))
        ax = fig.add_subplot(111, projection='3d')

    colors = [(base_color[0], base_color[1], base_color[2], n * alpha_max)
              for n in vals]
    ax.scatter3D(long_data[::step_size, 0],
                 long_data[::step_size, 1],
                 long_data[::step_size, 2],
                 c=colors)
    return ax
Exemple #9
0
# repeat for center img data
img_data = scipy.io.loadmat('elec_centers.mat')
img_data = img_data.get('center_img')
new_fname = 'CT_elecCenters.nii'
N = nib.Nifti1Image(img_data, affine, hdr)
N.to_filename(new_fname)

# get img dims
z_len = img_data[0, 0, :].shape
x_len = img_data[:, 0, 0].shape
y_len = img_data[0, :, 0].shape

# get coords of voxels containing center data
coords = np.nonzero(img_data)
x = coords[0]
y = coords[1]
z = coords[2]

# concatonate xyz vectors into 3 x n matrix
stackem = (x, y, z)
coords = np.vstack(stackem)
coords = np.transpose(coords)
scipy.io.savemat('3dcv_coords.mat', {'coords': coords})

# plot the cv center results
s = 202
fig = plt.figure(facecolor="white")
ax = fig.add_subplot(111, projection='3d')
Axes3D.scatter3D(ax, x, y, z, s=s)
plt.show(fig)
Exemple #10
0
def seg_3D(CT_dir,fname, out_fname):

    # load in 3D output
    coords = scipy.io.loadmat(CT_dir + '/' + fname).get('elecmatrix');
    x = coords[:,0];
    y = coords[:,1];
    z = coords[:,2];

    # plot dirty elec results
    s = 150;
    fig = plt.figure(facecolor="white");
    ax = fig.add_subplot(111,projection='3d');
    

    # create point and click function for selecting false alarm points
    seg_elecs = [];
    def onpick(event):

        # get event indices and x y z coord for click
        ind = event.ind[0];
        x_e, y_e, z_e = event.artist._offsets3d;
        print x_e[ind], y_e[ind], z_e[ind];
        seg_coord = [x_e[ind], y_e[ind], z_e[ind]];
        seg_elecs.append(seg_coord);

        # refresh plot with red dots picked and blue dots clean
        #fig.clf();
        seg_arr = np.array(seg_elecs);
        x_f = seg_arr[:,0];
        y_f = seg_arr[:,1];
        z_f = seg_arr[:,2];
        plt.cla();
        Axes3D.scatter3D(ax,x_f,y_f,z_f,s=150,c='r', picker=5);

        # get array of only clean elecs to re-plot as blue dots
        clean_list = list(coords);
        clean_list = [list(i) for i in clean_list];
        for coordin in clean_list:
                if list(coordin) in seg_elecs:
                    clean_list.pop(clean_list.index(coordin));
        clean_coordis = np.array(clean_list);
        x_c = clean_coordis[:,0];
        y_c = clean_coordis[:,1];
        z_c = clean_coordis[:,2];
        Axes3D.scatter3D(ax,x_c, y_c, z_c, s=150,c='b', picker=5);
        time.sleep(0.5);
        plt.draw();
    
    Axes3D.scatter3D(ax,x,y,z,s=s, picker=5);
    #title_font = {'fontname':'serif', 'size':'24', 'color':'black', 'weight':'bold',                            
    #'verticalalignment':'bottom'};                                                                        
    plt.title('3D Output Coordinates: ');
    fig.canvas.mpl_connect('pick_event', onpick);
    plt.ion();
    plt.show(fig);

    # wait for user to press enter to continue
    while True:
        
        fig.canvas.mpl_connect('pick_event', onpick);
        plt.draw();
        i = raw_input("Enter text or Enter to quit: ");
        if i == '':
            
            # remove all false coords from elec centers list
            fig.clf();
            coords_list = list(coords);
            coords_list = [list(i) for i in coords_list];
            for coordi in coords_list:
                if list(coordi) in seg_elecs:
                    coords_list.pop(coords_list.index(coordi));
            clean_coords = np.array(seg_elecs)

            # plot result
            X = clean_coords[:,0];
            Y = clean_coords[:,1];
            Z = clean_coords[:,2];


            s = 150;
            fig = plt.figure(facecolor="white");
            ax = fig.add_subplot(111,projection='3d');
            Axes3D.scatter3D(ax,X,Y,Z,s=s);
            plt.show(fig);
            
            # save the cleaned elecs file
            new_fname = CT_dir + '/' + out_fname;            
            scipy.io.savemat(new_fname, {'elecmatrix':clean_coords});
            
            return clean_coords;
            break;
Exemple #11
0
def seg_Hough3D(CT_dir,fname, out_fname):

    # load in 3D hough output
    coords = scipy.io.loadmat(CT_dir + '/' + fname).get('elecmatrix');
    x = coords[:,0];
    y = coords[:,1];
    z = coords[:,2];

    # plot dirty elec results
    s = 150;
    fig = plt.figure(facecolor="white");
    ax = fig.add_subplot(111,projection='3d');
    

    # create point and click function for selecting false alarm points
    seg_elecs = [];
    def onpick(event):

        # get event indices and x y z coord for click
        ind = event.ind[0];
        x_e, y_e, z_e = event.artist._offsets3d;
        print x_e[ind], y_e[ind], z_e[ind];
        seg_coord = [x_e[ind], y_e[ind], z_e[ind]];
        seg_elecs.append(seg_coord);

        # refresh plot with red dots picked and blue dots clean
        #fig.clf();
        seg_arr = np.array(seg_elecs);
        x_f = seg_arr[:,0];
        y_f = seg_arr[:,1];
        z_f = seg_arr[:,2];
        plt.cla();
        Axes3D.scatter3D(ax,x_f,y_f,z_f,s=150,c='r', picker=5);

        # get array of only clean elecs to re-plot as blue dots
        clean_list = list(coords);
        clean_list = [list(i) for i in clean_list];
        for coordin in clean_list:
                if list(coordin) in seg_elecs:
                    clean_list.pop(clean_list.index(coordin));
        clean_coordis = np.array(clean_list);
        x_c = clean_coordis[:,0];
        y_c = clean_coordis[:,1];
        z_c = clean_coordis[:,2];
        Axes3D.scatter3D(ax,x_c, y_c, z_c, s=150,c='b', picker=5);
        time.sleep(0.5);
        plt.draw();
    
    Axes3D.scatter3D(ax,x,y,z,s=s, picker=5);
    #title_font = {'fontname':'serif', 'size':'24', 'color':'black', 'weight':'bold',                            
    #'verticalalignment':'bottom'};                                                                        
    plt.title('Hough 3D Output Coordinates: ');
    fig.canvas.mpl_connect('pick_event', onpick);
    plt.ion();
    plt.show(fig);

    # wait for user to press enter to continue
    while True:
        
        fig.canvas.mpl_connect('pick_event', onpick);
        plt.draw();
        i = raw_input("Enter text or Enter to quit: ");
        if i == '':
            
            # remove all false coords from elec centers list
            fig.clf();
            coords_list = list(coords);
            coords_list = [list(i) for i in coords_list];
            for coordi in coords_list:
                if list(coordi) in seg_elecs:
                    coords_list.pop(coords_list.index(coordi));
            clean_coords = np.array(seg_elecs)

            # plot result
            X = clean_coords[:,0];
            Y = clean_coords[:,1];
            Z = clean_coords[:,2];


            s = 150;
            fig = plt.figure(facecolor="white");
            ax = fig.add_subplot(111,projection='3d');
            Axes3D.scatter3D(ax,X,Y,Z,s=s);
            plt.show(fig);
            
            # save the cleaned elecs file
            new_fname = CT_dir + '/' + out_fname;            
            scipy.io.savemat(new_fname, {'elecmatrix':clean_coords});
            
            return clean_coords;
            break;
# get img dims
z_len = img_data[0,0,:].shape;
x_len = img_data[:,0,0].shape;
y_len = img_data[0,:,0].shape;

# get coords of voxels containing center data
coords = np.nonzero(img_data);
x = coords[0];
y = coords[1];
z = coords[2];

# concatonate xyz vectors into 3 x n matrix
stackem = (x,y,z);
coords = np.vstack(stackem);
coords = np.transpose(coords);
scipy.io.savemat('3dHough_coords.mat', {'coords':coords});


# plot the hough center results
s = 202
fig = plt.figure(facecolor="white");
ax = fig.add_subplot(111,projection='3d');
Axes3D.scatter3D(ax,x,y,z,s=s);
plt.show(fig);





Exemple #13
0
    de1 = math.sqrt(de / len(x))
    return de1


print('Percentage Error: ', percent_error())

# surface data
fig = plt.figure()
# Red is the spline and Blue is the smooth_path.csv
ax = fig.add_subplot(111, projection='3d')
Axes3D.plot(ax, xs=x, ys=y, zs=z, color='red')
Axes3D.plot(ax, xs=x_axis, ys=y_axis, zs=z_axis, color='blue')
# Purple is the control points
Axes3D.scatter3D(ax,
                 xs=control_vector_x,
                 ys=control_vector_y,
                 zs=control_vector_z,
                 s=0.25,
                 color='purple')
plt.show()

# s contains all the radius data
# tube radius is varied by a factor 0.1 * radius for a cleaner 3D output
s = radius_data / 2

user_using = True
while user_using == True:
    # User input for vessel representation
    print()
    print('Vessel representations:')
    print('[1]: Given Smooth Path')
    print('[2]: B-Spline Values')