def delete_spurious_trajectories(self, subject='particles', plot=True, export=True): """ :param subject: :return: """ ### Deletion of spurious trajectories under 'minpoints' points ### if subject == 'particles': editable_list = self.particle_trajectory_list elif subject == 'algae': editable_list = self.algae_trajectory_list else: raise Exception('The argument subject of the current method ' '(delete_spurious_trajectories) must be either particles or algae') editable_list.set_all_trajectories_dataframe( tp.filter_stubs( editable_list.all_trajectories_dataframe, self.minpoints ) ) editable_list.update_item_list() if plot: tp.plot_traj(editable_list.all_trajectories_dataframe, label=True) plt.show() if export: editable_list.all_trajectories_dataframe.to_csv(self.path + '\\t_' + subject + '.csv', index=None, header=True) return editable_list
def filter_trajectories(self, path, subject='particles', lag=20, plot=True, export=True, inplace=False): """ :param lag: :return: """ if inplace == False: sequence = self.__copy__() elif inplace == True: sequence = self for part in sequence.item_list: sequence.trajectory_dict[part].derivative_filter(lag=lag) if plot: tp.plot_traj(sequence.all_trajectories_dataframe, label=False) plt.show() if export: sequence.all_trajectories_dataframe.to_csv( path + '\\t_' + subject + '_filtered.csv', index=None, header=True) return sequence
def generate_trajectories(self, subject='particles', plot=True, export=True, invert=True, memory=50): """ :param subject: :param plot: :param export: :param invert: :param memory: :return: """ fv = tp.batch(self.image_sequence, self.particlesize, minmass=self.particleminmass, invert=invert) t = tp.link_df(fv, 5, memory=memory) if subject == 'particles': self.particle_trajectory_list = TrajectorySequence(t) elif subject == 'algae': self.algae_trajectory_list = TrajectorySequence(t) else: raise Exception('The argument subject of the current method ' '(generate_trajectories) must be either particles or algae') if plot: tp.plot_traj(t, label=True) plt.show() if export: t.to_csv(self.path + '\\t_' + subject + '.csv', index=None, header=True) if subject == 'particles': return self.particle_trajectory_list if subject == 'algae': return self.algae_trajectory_list
def traj_plot(data_frame): """ The function that graphs trajectory information. Parameters: data_frame (DataFrame): The DataFrame of trajectory information generated by Trackpy. """ plt.figure() tp.plot_traj(data_frame) plt.show()
def tracking(video): print "running tracking" pimsFrames = pims.Video(video, as_grey=True) cells = [] track = [] for frame in pimsFrames[:]: f = tp.locate(frame, 301, invert=False, minmass=2000) t = tp.link_df(f, 5) #remember cells after they left frame tp.annotate(f, frame) cells += f track += t print t.head() tp.plot_traj(t) return t.head()
def tracking(video): print "running tracking" pimsFrames = pims.Video(video, as_grey = True) cells = [] track = [] for frame in pimsFrames[:]: f = tp.locate(frame, 301, invert=False, minmass = 2000) t = tp.link_df(f, 5) #remember cells after they left frame tp.annotate(f, frame) cells += f track += t print t.head() tp.plot_traj(t) return t.head()
def trshow(tr, first_style='bo', last_style='gs', style='b.'): frames = list(tr.groupby('frame')) nframes = len(frames) for i, (fnum, pts) in enumerate(frames): if i == 0: sty = first_style elif i == nframes - 1: sty = last_style else: sty = style print(pts.x, pts.y) tpy.plot_traj(tr, colorby='frame', ax=gca()) axis('equal') xlabel('x') ylabel('y')
def delete_algae_from_particles_trajectories(self, quantile=0.9, plot=True, export=True): self.particle_trajectory_list.set_all_trajectories_dataframe(tp.filtering.bust_clusters( self.particle_trajectory_list.all_trajectories_dataframe, quantile=quantile, threshold=None)) self.particle_trajectory_list.update_item_list() if plot: tp.plot_traj(self.particle_trajectory_list.all_trajectories_dataframe, label=True) plt.show() if export: self.particle_trajectory_list.all_trajectories_dataframe.to_csv( self.path + '\\t_particles.csv', index=None, header=True ) return self.particle_trajectory_list
def image_trajectories(dtraj, img_gfp=None, img_bright=None, label=True, fig=None, ax=None): import trackpy as tp fig = plt.figure(figsize=[20, 20]) if fig is None else fig ax = plt.subplot(111) if ax is None else ax ax = image_background(img_region=img_bright, img=img_gfp, ax=ax) ax = tp.plot_traj(dtraj, label=False, ax=ax, lw=2, plot_style={'color': 'lime'}) dtrajagg = dtraj.groupby('particle').agg( {c: np.median for c in ['x', 'y']}).reset_index() # dtrajagg.columns=coltuples2str(dtrajagg.columns) # print(dtrajagg.iloc[0,:]) if label: dtrajagg.reset_index().apply(lambda x: ax.text( x['x'], x['y'], int(x['particle']), color='magenta'), axis=1) ax.grid(False) return ax
def make_video(vid_path, features_df, export_path, clip_frames=None, fps=30): plt.ion() imgs = glob.glob(vid_path) # frames = pims.open(vid_path) if clip_frames is None: first = features_df['frame'].unique().min() last = features_df['frame'].unique().max() clip_frames = [first, last] # imgs indexing always starts at 0, its not aware of the dataframe or the clipping. f_img_start = 0 f_img_end = last - first arr = [] f_start, f_end = clip_frames for fnum, img in zip(range(f_start, f_end), imgs[f_img_start:f_img_end]): print(f'Frame -> {fnum}') frame = cv2.imread(img) fig = plt.figure(figsize=(16, 10)) plt.imshow(frame) axes = tp.plot_traj(features_df.query(f'frame<={fnum}'), label=True) plt.annotate(f"Frame -> {fnum} | Time -> {round(fnum / fps, 2)} s", (0, 20)) axes.set_yticklabels([]) axes.set_xticklabels([]) axes.get_xaxis().set_ticks([]) axes.get_yaxis().set_ticks([]) arr.append(cvtFig2Numpy(fig)) plt.close() makevideoFromArray(export_path, arr, fps) # number of FPS at the end
def displayTrajectory(array, dataframe, track_ids=None): # Initialize the display options colorby = "particle" label = True # Select the tracks to display if track_ids is not None: dataframe = dataframe[dataframe["particle"].isin(track_ids)] # Edit the options if needed if len(track_ids) == 1: colorby = "frame" label = False tp.plot_traj(dataframe, superimpose=array, colorby=colorby, label=label)
def plot_traj(frame,traj): fig=plt.figure(figsize=[frame.shape[0]*0.02,frame.shape[1]*0.02]) ax=plt.subplot(111) ax.imshow(frame,cmap='binary_r',alpha=0.8) ax = tp.plot_traj(traj,label=False,ax=ax,lw=2) plt.tight_layout() return ax
def plot_trajectories(img,dtraj,params_plot_traj={'label':False}): plt.figure() ax=plt.subplot(111) ax.imshow(img,cmap='binary_r',alpha=0.8,zorder=-1) ax = tp.plot_traj(dtraj,ax=ax,**params_plot_traj) ax.set_xlim(0,img.shape[0]) ax.set_ylim(0,img.shape[1]) plt.tight_layout()
def get_chart(self, data: ChartData): fig = plt.figure(figsize=(16, 9), dpi=300) ax = fig.add_subplot(1, 1, 1) plot = tp.plot_traj(data.filtered[:self.MAX_NUMBER_OF_TRAJECTORIES], ax=ax) plot_pil_image = trackpy_fig_to_pil(plot) fig.clear() plt.close(fig) return plot_pil_image
def plot_tracks_infos(tracks, name, frame=None): plt, sns = set_defaults() fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 8)) fig.suptitle(name) if frame is not None: im = ax1.imshow(frame) fig.colorbar(im, ax=ax1) ax1.grid(False) tp.plot_traj(tracks, ax=ax1) ax1.set_title('{:d} particle tracks'.format(tracks['particle'].nunique())) particle_infos = (tracks.groupby('particle').apply( lambda df: pd.Series({ 'min_frame': df['frame'].min(), 'max_frame': df['frame'].max(), 'n_frames': len(df), 'raw_mass': df['raw_mass'].median() })).reset_index()) ax2.hist(particle_infos['n_frames'], bins=50, log=True) ax2.set_xlabel('Number of frames') ax2.set_ylabel('Number of particles') ax3.barh(y=particle_infos['particle'], width=particle_infos['n_frames'], left=particle_infos['min_frame'], height=4 if particle_infos['particle'].max() > 100 else 1) ax3.set_xlabel('Frame index') ax3.set_ylabel('Particle index') ax4.loglog(particle_infos['n_frames'], particle_infos['raw_mass'], '.', alpha=0.5) ax4.set_xlabel('Number of frames') ax4.set_ylabel('median raw_mass') return fig
def whatever(): path = 'D:\\Microswimmers2D_SBR\\Data\\190808\\ANH_Chlamy_beads_Thickness18pt_60x_C001H001S0001\\NoBackground_median\\Clear' # path = 'D:\\Microswimmers2D_SBR\\Data\\190808\\ANH_Chlamy_beads_ThicknessLessThan18pt_60x_C001H001S0001\\NoBackground_median\\Clear' with open(path + '\\t_particles.csv') as csv_file: stack_particles = TrajectorySequence( pd.read_csv(csv_file, delimiter=',', dtype={ 'frame': int, 'particle': int, 'y': float, 'x': float }, usecols=['y', 'x', 'frame', 'particle'])) f_all = stack_particles.all_trajectories_dataframe f200 = f_all['frame'] <= 200 f_200 = f_all[f200] tp.plot_traj(f_200, label=True) plt.show()
def plot_trajectories_by_lenght(data, min_lenght=0, max_lenght=25000): selected_tracks = select_tracks_by_lenght(data, min_lenght, max_lenght) data = data.rename(columns={'track': 'particle'}) sub_data = data[data['particle'].isin(selected_tracks)] tp.plot_traj(sub_data)
cv2.destroyAllWindows() #%% trackpy-routine - trajectories, pictures, dataframe and saving # find trajectories - check http://soft-matter.github.io/trackpy/v0.3.0/generated/trackpy.link_df.html for all options traj_fish = tp.link_df(df_fish, search_range = 200, memory=50, neighbor_strategy="KDTree", link_strategy="nonrecursive") traj_fish_filter = tp.filtering.filter_stubs(traj_fish, threshold=20) df_isopod_counts = df_isopod["frame"].value_counts() df_isopod_filtered = df_isopod.groupby("frame").filter(lambda x: len(x) < 22) traj_isopod = tp.link_df(df_isopod_filtered, search_range = 50, memory=500, neighbor_strategy="KDTree", link_strategy="nonrecursive") traj_isopod_filter = tp.filtering.filter_stubs(traj_isopod, threshold=20) # plot fish trajectories plot = tp.plot_traj(traj_fish_filter, superimpose=v.frame) fig1 = plot.get_figure() fig1.savefig(os.path.join(main_dir, video_name + "_fish_trajectories.png"), dpi=300) plt.close('all') # plot isopod trajectories plot = tp.plot_traj(traj_isopod_filter, superimpose=v.frame, colorby="particle") fig2 = plot.get_figure() fig2.savefig(os.path.join(main_dir, video_name + "_isopod_trajectories.png"), dpi=300) plt.close('all') # save isopod trajectories to csv traj_fish.to_csv(os.path.join(main_dir, video_name + "_fish_trajectories_full.csv"), sep='\t') traj_isopod.to_csv(os.path.join(main_dir, video_name + "_isopod_trajectories_full.csv"), sep='\t')
#fig=tp.annotate(f, aa[0]) #fig.figure.savefig("./trackpyResult/trackpyAnnotation.jpg") #f = tp.batch(aa[:], 11, minmass=200, invert=True); #f = tp.batch(aa[:], 11, invert=True); fig, ax = plt.subplots() t = tp.link_df(f, 5, memory=3) t1 = tp.filter_stubs(t, 50) print(t1) t1.to_csv("./trackpyResult/t1.csv") # Compare the number of particles in the unfiltered and filtered data. print('Before:', t['particle'].nunique()) print('After:', t1['particle'].nunique()) #fig=plt.figure() #fig=tp.mass_size(t1.groupby('particle').mean()); # convenience function -- just plots size vs. mass #fig.figure.savefig("./trackpyResult/particle.jpg") fig=plt.figure() fig=tp.plot_traj(t1) fig.figure.savefig("./trackpyResult/trajectoryI.jpg") t2 = t1 fig=plt.figure() fig=tp.annotate(t2[t2['frame'] == 0], aa[0]); fig.figure.savefig("./trackpyResult/t2Annotation.jpg") d = tp.compute_drift(t2) fig=plt.figure() fig=d.plot() tm = tp.subtract_drift(t1.copy(), d) fig.figure.savefig("./trackpyResult/comDrift.jpg") fig=plt.figure() fig=tp.plot_traj(tm) fig.figure.savefig("./trackpyResult/traj.jpg")
tR = pred.link_df(fR, 3, memory=11, diagnostics=True) tR.to_csv('./Data/Shot{}/trackR_frame_inv.csv'.format(shot)) # In[ ]: #tR = pd.read_csv('./Data/Shot{}/trackR_frame_inv.csv'.formate(shot)) tR.head() # In[ ]: plt.figure(figsize=[12,12]) tp.plot_traj(tR); # In[ ]: plt.figure(figsize=[12,12]) plt.imshow(v0R+bk0R) #plt.scatter(tR['x'],tR['y'],s=0.3,c='g') plt.scatter(tR['x'],tR['y'],s=0.3,c=tR['mass']) plt.show() # In[ ]:
""" from MTM import matchTemplates import cv2 from skimage import io import matplotlib.pyplot as plt from template_opt import Template90 from track import make_batch import trackpy as tp fileID = r"C:\Users\MattiaV\Desktop\università\Interships\DynamicsOfGranularShapes\ParticleTracking\Images\First frames\*.png" images = io.imread_collection(fileID) temp_draft1 = images[0][320:433,520:650] temp0 = temp_draft1[23:92,28:105] Temp = Template90(temp0) list_template = Temp.create() features_match = {'N_obj':50, 'threshold':0.55, 'method':cv2.TM_CCOEFF_NORMED, 'max_overlap':0.22} batch = make_batch(images, list_template, features_match) t0 = tp.link(batch, 50, memory = 3) t1 = tp.filter_stubs(t0, 4) # Compare the number of particles in the unfiltered and filtered data. print('Before:', t0['particle'].nunique()) print('After:', t1['particle'].nunique()) plt.figure() tp.plot_traj(t1);
############################################ # The plt.figure() call only works if the X server # is running. Not via ssh. if 'DISPLAY' not in os.environ: print("Exciting because no display server found.") exit(1) plt.figure() ax1 = plt.gca() # gca = get current axes tp.plot_traj(tra2, ax=ax1) plt.xlim( 0, im_w ) plt.ylim( im_h, 0 ) # ax1.axis('equal') # didn't work with setting xlim and ylim. plt.gca().set_aspect('equal') # plt.show() oname = track_ims_dir + "/" + track_ims_vidname + ".png" print( "oname = [" + oname + "]" ) plt.savefig( oname, bbox_inches='tight' )
# Left frame pred = trackpy.predict.NearestVelocityPredict() #pred = trackpy.predict.ChannelPredict(0.5, 'x', minsamples=3) fL = tp.batch(FrameL, 3, minmass=5) tL = pred.link_df(fL, 3, memory=11, diagnostics=True) tL.to_csv('./Data/Shot{}/trackL_frame_inv.csv'.format(shot)) # In[ ]: #tL = pd.read_csv('./Data/Shot{}/trackL_frame_inv.csv'.formate(shot)) tL.head() # In[ ]: plt.figure(figsize=[12, 12]) tp.plot_traj(tL) # In[ ]: plt.figure(figsize=[12, 12]) plt.imshow(v0L + bk0L) #plt.scatter(tL['x'],tL['y'],s=0.3,c='g') plt.scatter(tL['x'], tL['y'], s=0.3, c=tL['mass']) plt.show() # In[ ]: # Remove tracks too few points (less than 500) tL1 = tp.filter_stubs(tL, 200) plt.figure(figsize=[12, 12]) tp.plot_traj(tL1)
print('After filter:', tra1['particle'].nunique()) plt.figure() tp.mass_size(tra1.groupby('particle').mean()); ##plots size vs mass fig,(ax1,ax2,ax3)=plt.subplots(1,3) fig.suptitle("Trajectories with/without Overall Drift") plt.figure() tp.plot_traj(tra1); d =tp.compute_drift(tra1) ##subtract overall drift from trajectory d.plot() plt.show() tm=tp.subtract_drift(tra1.copy(),d) ##plot filtered trajectory ax=tp.plot_traj(tm) plt.show() ##MSD Calculation and Plot im=tp.imsd(tm,1/5.,60) ##microns per pixel, frames per second=60 fig, ax = plt.subplots()
fig,ax = plt.subplots() ax.hist(f['mass'], bins=40) f = tp.batch(frames[-100:], 21, minmass = 1000, invert=True) t = tp.link_df(f, 5, memory=3) t.head() t1 = tp.filter_stubs(t, 25) print('before:', t['particle'].nunique()) print('after:', t1['particle'].nunique()) plt.figure() tp.plot_traj(t1) d = tp.compute_drift(t1) d.plot() plt.show() plt.savefig("1.pdf") tm = tp.subtract_drift(t1.copy(),d) ax = tp.plot_traj(tm) plt.show() plt.savefig("2.pdf") em = tp.emsd(tm, 0.00000119029/1, 30) # microns per pixel = 100/285., frames per second = 24
def main(): for case_idx, case in enumerate(cases.values()): res_path = gen_path + case[1] frames = pims.ImageSequence(gen_path + case[0], as_grey=True) # Stores the unfiltered annotated image of a frame to local file path if plots["Annotate_unfiltered"]: k = tp.locate(frames[0], 11, invert=[case_idx in [0, 1]], minmass=200) fig = plt.figure("Annotated_unfiltered_image_" + case[2]) ax1 = fig.add_subplot() a = ["k", "w"][case_idx in [2, 3]] tp.annotate(k, frames[0], color=a, ax=ax1) #ax1.set_title("Annotated unfiltered image case: "+ case[2]) #ax1.set_xlabel("x[px]", fontsize=size) #ax1.set_ylabel("y[px]", fontsize=size) ax1.tick_params(axis="both", which="both", top=False, bottom=False, labelbottom=False, right=False, left=False, labelleft=False) fig.savefig(res_path + "Annotated_unfiltered_image_" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close(fig) # If True: Tracks all frames and stores .csv to locally, else: imports such .csv file from local if plots["Generate_batch"]: f = tp.batch(frames[:225], 11, minmass=100, invert=[case_idx in [0, 1]]) f.to_csv(res_path + "batch_" + case[2] + ".csv") if not plots["Generate_batch"]: f = pd.read_csv(res_path + "batch_" + case[2] + ".csv") # Linking and filtering t = tp.link_df(f, 5, memory=3) t1 = tp.filter_stubs(t, 50) # Plots the size vs mass profile and saves to local file path if plots["Size_vs_mass"]: fig = plt.figure("Size_vs_mass_" + case[2]) ax1 = fig.add_subplot() tp.mass_size( t1.groupby('particle').mean(), ax=ax1) # convenience function -- just plots size vs. mass #ax1.set_title("Size vs mass case: " + case[2]) ax1.set_xlabel("mass", fontsize=size) ax1.set_ylabel("Gyration radius [px]", fontsize=size) ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.tick_params(axis="both", which="major", labelsize=size) ax1.tick_params(axis="both", which="minor", labelsize=size) fig.savefig(res_path + "Size_vs_mass_" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close(fig) if plots["Annotate_filtered"]: if case_idx in [0, 1]: # Set BF condition condition = lambda x: ( (x['mass'].mean() > 250) & (x['size'].mean() < 3.0) & (x['ecc'].mean() < 0.1)) elif case_idx in [2, 3]: # Set DF condition condition = lambda x: ( (x['mass'].mean() > 100) & (x['size'].mean() < 5.0) & (x['ecc'].mean() < 0.1)) t2 = tp.filter( t1, condition ) # a wrapper for pandas' filter that works around a bug in v 0.12 fig = plt.figure("Annotated_filtered_image_" + case[2]) ax1 = fig.add_subplot() k = ["k", "w"][case_idx in [2, 3]] tp.annotate(t2[t2['frame'] == 0], frames[0], color=k, ax=ax1) #ax1.set_title("Annotated filtered image case: " + case[2]) #ax1.set_xlabel("x[px]", fontsize=size) #ax1.set_ylabel("y[px]", fontsize=size) ax1.tick_params(axis="both", which="both", top=False, bottom=False, labelbottom=False, right=False, left=False, labelleft=False) fig.savefig(res_path + "Annotated_filtered_image_" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close(fig) if plots["Gyration_radius_filtered"]: size_dis_t1 = [i * ratio_μm_px for i in t1['size']] plt.figure("Gyration_radius_filtered_" + case[2]) plt.hist(size_dis_t1, bins=300, color="k", alpha=0.5) #plt.title("Gyration radius filtered case: "+ case[2]) plt.ylabel("Events", fontsize=size) plt.xlabel("Gyration radius [μm]", fontsize=size) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) plt.tick_params(axis="both", which="major", labelsize=size) plt.tick_params(axis="both", which="minor", labelsize=size) plt.savefig(res_path + "Gyration_radius_filtered" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close("all") if plots["Gyration_radius_unfiltered"]: size_dis_t = [i * ratio_μm_px for i in t['size']] plt.figure("Gyration_radius_unfiltered_" + case[2]) plt.hist(size_dis_t, bins=300, color="k", alpha=0.5) #plt.title("Gyration radius unfiltered case: " + case[2]) plt.ylabel("Events", fontsize=size) plt.xlabel("Gyration radius [μm]", fontsize=size) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) plt.tick_params(axis="both", which="major", labelsize=size) plt.tick_params(axis="both", which="minor", labelsize=size) plt.savefig(res_path + "Gyration_radius_unfiltered" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close("all") d = tp.compute_drift(t1) tm = tp.subtract_drift(t1, d) if plots["Trajectory_drift"]: fig = plt.figure("Trajectory_drift_subtracted_" + case[2]) ax1 = fig.add_subplot() ax1.tick_params(axis="both", which="major", labelsize=size) ax1.tick_params(axis="both", which="minor", labelsize=size) ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) tp.plot_traj(tm, ax=ax1) #ax1.set_title("Trajectory with drift subtracted case: " + case[2]) plt.savefig(res_path + "Trajectory_drift_subtracted_" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close(fig) if plots["Variance_all_parts"]: im = tp.imsd( tm, ratio_μm_px, fps, max_lagtime=225 ) # microns per pixel = 100/285., frames per second = 24 plt.figure("Variance_for_all_particles_" + case[2]) #plt.title("Variance for all particles case: " + case[2]) plt.plot(im.index, im, 'k-', alpha=0.1) # black lines, semitransparent plt.ylabel(r'$\langle \Delta r^2 \rangle$ [$\mu$m$^2$]', fontsize=size), plt.xlabel('time $t$', fontsize=size) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) plt.xscale('log') plt.yscale('log') plt.savefig(res_path + "Variance_for_all_particles_" + case[2] + ".png", bbox_inches="tight", pad_inches=0) if plots["Variance_linear"] or plots["Variance_power_fit"] or plots[ "Return_A_and_D"]: em = tp.emsd(tm, ratio_μm_px, fps, max_lagtime=225) if plots["Variance_linear"]: plt.figure("Variance_linear_fit_" + case[2]) #plt.title("Variance linear fit case: " + case[2]) plt.plot(em.index, em, 'ko', alpha=0.5) plt.ylabel(r'$\langle \Delta r^2 \rangle$ [$\mu$m$^2$]', fontsize=size), plt.xlabel('time $t$ [s]', fontsize=size) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) plt.tick_params(axis="both", which="major", labelsize=size) plt.tick_params(axis="both", which="minor", labelsize=size) plt.xscale('log') plt.yscale('log') plt.ylim(1e-2, 50) plt.savefig(res_path + "Variance_linear_fit_" + case[2] + ".png", bbox_inches="tight", pad_inches=0) if plots["Variance_power_fit"]: fig = plt.figure("Variance_power_fit_" + case[2]) ax1 = fig.add_subplot() tp.utils.fit_powerlaw(em, ax=ax1, color="k", alpha=0.5) #ax1.set_title("Variance power fitted case: " + case[2]) ax1.set_ylabel(r'$\langle \Delta r^2 \rangle$ [$\mu$m$^2$]', fontsize=size) ax1.set_xlabel('time $t$ [s]', fontsize=size) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) ax1.tick_params(axis="both", which="major", labelsize=size) ax1.tick_params(axis="both", which="minor", labelsize=size) fig.savefig(res_path + "Variance_power_fit_" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close(fig) if plots["Hydrodynamic_radius_filtered"]: im = tp.imsd(tm, ratio_μm_px, fps, max_lagtime=225) r_h = [] count = 0 im = im.rename_axis("ID").values for index in range(1, len(im[0])): if isinstance(im[40][index], float) and isinstance( im[8][index], float): D = (im[40][index] - im[8][index]) / (4 * (40 - 8) / fps) * 10**(-12) if isinstance(D, float): r_h += [abs(10**6 * (k_b * T) / (6 * np.pi * μ * D))] if 0 < abs(10**6 * (k_b * T) / (6 * np.pi * μ * D)) < 6: count += 1 print("In interval: ", count, "Total: ", len(r_h), "Ratio: ", count / len(r_h)) plt.figure("Hydrodynamic_radius_filtered_" + case[2]) plt.hist(r_h, bins=int(count / 3), color="k", alpha=0.5, range=(0, 6)) #plt.title("Hydrodynamic radius filtered case: "+ case[2]) plt.ylabel("Trajectories", fontsize=size) plt.xlabel("Hydrodynamic radius [μm]", fontsize=size) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) plt.tick_params(axis="both", which="major", labelsize=size) plt.tick_params(axis="both", which="minor", labelsize=size) plt.savefig(res_path + "Hydrodynamic_radius_filtered" + case[2] + ".png", bbox_inches="tight", pad_inches=0) plt.close("all") if plots["Return_A_and_D"]: A = tp.utils.fit_powerlaw(em, ax=ax1, color="k", alpha=0.5)["A"] * 10**(-12) print(tp.utils.fit_powerlaw(em, ax=ax1, color="k", alpha=0.5)) print("For case ", case[2], " A=", A, ", and D=", A / 4, ".")
1, r'\textbf{' + string.ascii_uppercase[0] + '}', transform=ax2.transAxes, size=8) im = mpimg.imread( '/Volumes/Samsung_T5/Experimental Data/Hans/B_raw_tiff/Schema.png') image1 = ax6.imshow(im, cmap='gray', zorder=1) ax1.axes.xaxis.set_visible(False) ax1.axes.yaxis.set_visible(False) ax2.axis("off") ax6.axes.xaxis.set_visible(False) ax6.axes.yaxis.set_visible(False) tf = pd.read_csv( '/Volumes/Samsung_T5/Experimental Data/Hans/E_output_data/500bp/tf/tf_movie_12.csv' ) tp.plot_traj(tf, label=False, ax=ax6, zorder=2, alpha=0.5) fig1.tight_layout() fig1.savefig(directory3 + '/scheme.png', dpi=300) fig2.savefig(directory3 + '/scheme1.png', dpi=300) ax7.set_xlim(0, 14) ax7.set_ylim(-0.1, 0.1) ax8.set_xlim(0, 14) ax8.set_ylim(0, 0.15) ax8.set(xlabel=r'$ t$' + ' ' + r'(s) ', ylabel=r'$\left |\Updelta \mathbf{r}\right |$' + ' ' + r'(\textmu m) ') #ax7.set(ylabel=r'$\Updelta x$'+' '+ r'(\textmu m) ') multicolor_ylabel(ax7, (r'$\Updelta x$', r'$\Updelta y$', ' ' + r'(\textmu m) '), ('k', 'r', 'b'), axis='y') for n, ax in enumerate((ax7, ax8)):
# -*- coding: utf-8 -*- """ Created on Thu Oct 31 10:13:30 2019 @author: labuser """ import trackpy as tp import pims import matplotlib.pyplot as plt images = pims.open(r'C:\Users\labuser\Documents\SEQconvert/*.png' ) # many PNGs with sequential names for i in range(50): plt.imshow(images[i]) plt.pause(0.1) f = tp.locate(images[0], 11) for i in range(30): g = tp.locate(images[i], 11, minmass=20) tp.annotate(g, images[i]) plt.pause(0.1) h = tp.batch(images[:], 11) h.head() plt.figure() tp.plot_traj(h)
# define max displacement max_disp = 5 # define frame memory for feature drop-out frame_memory = 5 t = tp.link_df(f, max_disp, memory=frame_memory) print(t.head()) # spurious ephemeral trajectory filtering # filter features that last for a given number of frames t1 = tp.filter_stubs(t, time_cutoff) # Compare the number of particles in the unfiltered and filtered data. print('Before:', t['particle'].nunique()) print('After:', t1['particle'].nunique()) # filter by appearance (size vs mass) plt.figure() tp.mass_size(t1.groupby('particle').mean()) plt.show() t2 = t1[((t1['mass'] > 0.05) & (t1['size'] < 3.0) & # fix mass (t1['ecc'] < 0.3))] plt.figure() tp.annotate(t2[t2['frame'] == 0], frames[0]) plt.show() plt.figure() tp.plot_traj(t1) plt.show()
def plot_tracks(self): if 'frame' not in self.df.columns: self.df['frame'] = self.df.index tp.plot_traj(self.df)
plt.figure() tp.plot_traj(t1) ''' # %% Link trajectory f = f[['y', 'x', 'frame']] searchRange = 90 memory = 30 minFrames = 20 t = Link(searchRange, memory, minFrames) # %% filter trajectory by minimum moving distance minFrames = 20 minDistance = 500 t = filterTrajectory(t, minDistance, minFrames) plt.figure() #t = t[t['particle'] == 5] tp.plot_traj(t, label = True) t.to_csv('./' + CaseName + 'Left.csv') listParticle = list(t['particle']) listParticle = list(set(listParticle)) print('There are %d trajectories' % len(listParticle)) # %% ---------------------------------------- Right Camera f1 = tp.locate(frames[87], 21, 7000) plt.figure() tp.annotate(f1, frames[87]); # %% run trajectory finding for Right estimateFeatureSizeRight = 29
plt.hist(f['mass'], bins=20) #ax.set(xlabel='mass', ylabel='count') plt.savefig("mass_distribution.png") t_Filtered = tp.filter_stubs(t, 30) #filter out Empheremeral trajectories t.to_csv("./trackpyResult/t_unfiltered_" + str(sr) + "_" + str(mem) + "minmass" + minmass + ".csv") t_Filtered.to_csv("./trackpyResult/t_filtered_" + str(sr) + "_" + str(mem) + "minmass" + minmass + ".csv") # compare filtered and unfiltered print('Before:', t['particle'].nunique()) print('After:', t_Filtered['particle'].nunique()) fig, ax = plt.subplots(figsize=(20, 12)) fig = tp.plot_traj(t_Filtered, fontsize=30) t2 = t_Filtered fig = plt.figure() fig = tp.annotate(t2[t2['frame'] == 0], aa[0]) fig.figure.savefig("./PureTrackpy/t2Annotation_" + str(sr) + "_" + str(mem) + "minmass" + minmass + ".jpg") d = tp.compute_drift(t2) fig = plt.figure() fig = d.plot() tm = tp.subtract_drift(t_Filtered.copy(), d) fig.figure.savefig("./PureTrackpy/comDrift_" + str(sr) + "_" + str(mem) + "minmass" + minmass + ".jpg") fig, ax = plt.subplots(figsize=(20, 12)) fig = tp.plot_traj(tm) ax.set_xlabel("X (pixel)", fontdict=font_axis_publish)
def Link(searchRange, memory, minFrames): t = tp.link(f, search_range = searchRange, memory = memory) t1 = tp.filter_stubs(t, minFrames) plt.figure() tp.plot_traj(t1, label = True) return t1