02_TrackRoot.py 17.2 KB
 Jonathan Barés committed Apr 23, 2019 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 `````` #~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~# #Intialisation: ##Load libraries: import numpy as np import math as m from scipy import misc from scipy import signal as sg import fnmatch import os import cv2 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.widgets import RectangleSelector ##Input parameter: ###Proximity threshold for root tip connection: ThrProxConn=70 ###Proximity threshold for root tip detection: ThrProxDetec=15 ##Count the number of pictures in the folder to get the number of keeped steps: NbStp=len(fnmatch.filter(os.listdir('pictureWh'),'*.jpg')) #~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~# #Pick initial variable for the image post processing ##Load the last picture: pict0=misc.imread('pictureWh/'+str(NbStp-1).zfill(4)+'.jpg')[:,:,0] ##Pick an intensity threshold to make mask: ###Pick an initial value ThrdPict=(np.amax(pict0)+np.amin(pict0))/2. flag0=1 ###Pick a value on a scale until it is suitable while flag0: try: pict1=pict0>ThrdPict plt.subplot(1,2,1) plt.imshow(pict1,cmap=plt.cm.Greys) plt.title('threshold value: '+'%0d'%ThrdPict) plt.subplot(1,2,2) plt.imshow(pict0) plt.colorbar() plt.title('pick a threshold value on the scale \n or close') a=plt.ginput(1,timeout=-1) plt.close() plt.show() ThrdPict=(np.amax(pict0)-np.amin(pict0))*a[0][1]+np.amin(pict0) except: flag0=0 ##Save threshold: os.system('mkdir pictureSkeleton > /dev/null') np.savetxt('pictureSkeleton/image_threshold.txt',np.array([ThrdPict])) ##Select the areas not to consider to follow the root: ###Define selection functions: def line_select_callback(eclick, erelease): global x1, y1, x2, y2 x1,y1=eclick.xdata,eclick.ydata x2,y2=erelease.xdata,erelease.ydata def toggle_selector(event): print(' Key pressed.') if event.key in ['Q', 'q'] and toggle_selector.RS.active: print(' RectangleSelector deactivated.') toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.RS.active: print(' RectangleSelector activated.') toggle_selector.RS.set_active(True) ###Stepwise selection of the ROI: pict1_int=1-pict1.astype('int') flag_tog=True pict_mask=np.ones(pict1_int.shape) while flag_tog: pict1_int=pict1_int*pict_mask x1=0; y1=0; x2=0; y2=0 fig,current_ax=plt.subplots() plt.imshow(pict1_int,cmap=plt.cm.Greys) plt.title('select area not to consider, close to validate, close 2 times to quit') toggle_selector.RS=RectangleSelector(current_ax,line_select_callback,drawtype='box',useblit=True,button=[1, 3],minspanx=5,minspany=5,spancoords='pixels',interactive=True) plt.connect('key_press_event',toggle_selector) plt.show() plt.close() if (x1>0 or x2>0): pict_mask[int(y1):int(y2),int(x1):int(x2)]=0 else: break ###Save mask: misc.imsave('pictureSkeleton/ROI_mask.png',pict_mask) ##Select seed: ###Load the last picture: pict0=misc.imread('pictureWh/'+'%04d'%(0)+'.jpg')[:,:,0] ###Select: pict1=pict0>ThrdPict pict1=(pict1.astype(int)-pict_mask)<0 plt.imshow(pict1,cmap=plt.cm.Greys) plt.title('select 2 points to zoom on the root top') a=plt.ginput(2,timeout=-1) plt.axis([min(a[0][0],a[1][0]),max(a[0][0],a[1][0]),max(a[0][1],a[1][1]),min(a[0][1],a[1][1])]) plt.title('zoom and clic on the head of the root and close') JIseed=plt.ginput(1,timeout=-1) plt.close() #~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~# #Extract the mask root network: ##Extraction for the last image: ###Compute the connected areas: pict3=np.uint8(misc.imread('pictureWh/'+str(NbStp-1).zfill(4)+'.jpg')[:,:,0]) pict3=(((pict3>ThrdPict).astype(int)-pict_mask)<0).astype(int) pict3=cv2.connectedComponents(np.uint8(pict3),4)[1] ###Extract the root area: pict4=pict3==pict3[int(JIseed[0][1]),int(JIseed[0][0])] ##Compute the ROI limits: I=np.where(pict4==1) Imin=int(0.9*min(I[0])); Imax=int(min((1.1*max(I[0]),pict3.shape[0]))) Jmin=int(0.9*min(I[1])); Jmax=int(min((1.1*max(I[1]),pict3.shape[1]))) ##Save limits and seed position: np.savetxt('pictureSkeleton/IJ_edge.txt',np.array([Imin,Imax,Jmin,Jmax]),delimiter=' ') np.savetxt('pictureSkeleton/IJ_seed.txt',np.array([JIseed[0][1],JIseed[0][0]]),delimiter=' ') ##Extract the mask of the root network for all the pictures: print('Is extracting root mask...') os.system('mkdir pictureSkeleton/mask') ###Loop over the pictures: for iPct in range(NbStp): print(str(iPct)+' / '+str(NbStp)) ####Load pictures: pictA=misc.imread('pictureWh/'+'%04d'%iPct+'.jpg')[:,:,0] ####Threshold and crop it: pictA=(((pictA>ThrdPict).astype(int)-pict_mask)<0).astype(int) pictA[0:int(JIseed[0][1]),:]=0. #~ pictA=(pictA<0.5 #~ #!debug! #~ plt.imshow(pictA) #~ plt.show() #~ plt.close() ####Compute the connected areas: A=cv2.connectedComponentsWithStats(np.uint8(pictA),4) Nb=A[0] pictA=A[1] areaA=A[2][:,4] centA=A[3] ####Look for the correct area: if iPct==0: itArea=0; flag1=1 while (flag1 & (itArea<=Nb)): itArea+=1 #####Get current pixels I=np.where(pictA==itArea) #####If current area is big enough to be considered: `````` Jonathan Barés committed May 23, 2019 164 `````` if (len(I[0])>500): `````` Jonathan Barés committed Apr 23, 2019 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 `````` #####If the seed point is in the current area this is the root: if np.min(np.sqrt((I[0]-JIseed[0][1])**2.+(I[1]-JIseed[0][0])**2.))<2: flag1=0 area0=len(I[0]) cent0=centA[np.where(area0==areaA)[0],:][0] else: #####Compute the difference of area: dArea=np.abs(areaA-area0) #####Compute the distance between centroids: dCent=np.sqrt((centA[:,0]-cent0[0])**2.+(centA[:,1]-cent0[1])**2.) #####Select the component with the closest area and centroid: I1=np.argsort(dArea)[0:5] I2=np.argsort(dCent)[0:5] I3=np.intersect1d(I1,I2) if len(I3)>0: itArea=I3[np.where(dArea[I3]==np.min(dArea[I3]))][0] else: print('root not properly detected') cent0=centA[itArea,:] area0=areaA[itArea] ###Extract the root area: pictA=pictA==itArea ###Crop the picture: pictA=pictA[Imin:Imax,Jmin:Jmax].astype(int) ###Save picture: misc.imsave('pictureSkeleton/mask/'+'%04d'%iPct+'.png',pictA) print('...extraction done') #~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~# #Detection of the root tips: ##Prepare storage folder: os.system('mkdir rootTip') os.system('mkdir rootTip/byStep') ##Load time: timePic=np.loadtxt('time.txt') ##Loop over the steps: `````` Jonathan Barés committed May 23, 2019 208 ``````for iPct in range(NbStp): `````` Jonathan Barés committed Apr 23, 2019 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 `````` ###Load the mask: pict4=misc.imread('pictureSkeleton/mask/'+'%04d'%iPct+'.png') ###Computation of the mask contour: image,contour,h=cv2.findContours(pict4,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) contour=contour[0] ###Computation of the crossproduct direction: ####Load the contour coordinate: X=contour[:,0,0].astype('float') Y=contour[:,0,1].astype('float') ####If the root is long enough: if (len(X)>10): ####Smothen it: X0=np.convolve(X,np.ones(5)/5.,mode='same'); X0[0]=X[0]; X0[1]=X[1]; X0[-1]=X[-1]; X0[-2]=X[-2] Y0=np.convolve(Y,np.ones(5)/5.,mode='same'); Y0[0]=Y[0]; Y0[1]=Y[1]; Y0[-1]=Y[-1]; Y0[-2]=Y[-2] #~ # ! Debug !: #~ plt.imshow(pict4) #~ plt.plot(X,Y,'-r') #~ plt.plot(X0,Y0,'-g') #~ plt.show() ####Computation of the cross-product: Curv=np.zeros(len(contour)) `````` Jonathan Barés committed May 23, 2019 232 `````` for itCurv in range(1,len(contour)-1): `````` Jonathan Barés committed Apr 23, 2019 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 `````` x0=X0[itCurv-1]; y0=Y0[itCurv-1] x1=X0[itCurv]; y1=Y0[itCurv] x2=X0[itCurv+1]; y2=Y0[itCurv+1] abs1=m.sqrt((x1-x0)**2+(y1-y0)**2) n1x=-(y1-y0)/abs1 n1y=(x1-x0)/abs1 abs2=m.sqrt((x2-x1)**2+(y2-y1)**2) n2x=-(y2-y1)/abs2 n2y=(x2-x1)/abs2 Curv[itCurv]=n1x*n2y-n1y*n2x ####Smoothen it: Curv0=np.convolve(Curv,np.ones(10)/10.,mode='same') # ! Debug !: #~ plt.plot(Curv,'-r') #~ plt.plot(Curv0,'-g') #~ plt.show() ###Detection of the root tips: ####Extract cross-product extremum and save tip positions: I=np.where((Curv0<-0.12) & (Y0>10))[0] if (len(I)>0): #####Detect continuous low curvature areas: J=np.unique(np.append([0],np.where(I[0:len(I)-1]-I[1:len(I)]<-2)[0])) if (len(J)>1): IXtr=np.zeros(len(J)) for itXtr in range(len(J)-1): IXtr[itXtr]=I[J[itXtr]+np.where(Curv0[I[J[itXtr]+1:J[itXtr+1]+1]]==np.amin(Curv0[I[J[itXtr]+1:J[itXtr+1]+1]]))[0][0]] IXtr[len(J)-1]=I[J[itXtr+1]+np.where(Curv0[I[J[itXtr+1]+1:len(I)]]==np.amin(Curv0[I[J[itXtr+1]+1:len(I)]]))[0][0]] IXtr=IXtr.astype(int) else: IXtr=np.array([I[np.where(Curv0[I]==np.amin(Curv0[I]))[0][0]]]) #####Extract root tip coordinates: vecTip=np.zeros([1,2]) for itXtr in range(len(IXtr)): vecTip=np.append(vecTip,[np.array([X0[IXtr[itXtr]],Y0[IXtr[itXtr]]])],axis=0) vecTip=np.delete(vecTip,0,0) #####Remove multi detection: if vecTip.shape[0]>1: vecD=np.sqrt((vecTip[0:-1,0]-vecTip[1:,0])**2.+(vecTip[0:-1,1]-vecTip[1:,1])**2.) I=np.where(vecD1: X.append(XY_tmp[:,0]) Y.append(XY_tmp[:,1]) T.append(timePic[iPct]*np.ones(XY_tmp.shape[0])) else: if XY_tmp[0]!=0: X.append(np.array(XY_tmp[0])) Y.append(np.array(XY_tmp[1])) T.append(np.array(timePic[iPct])) ###Make position vector: X0=np.hstack(X) Y0=np.hstack(Y) T0=np.hstack(T) pict4=misc.imread('pictureSkeleton/mask/'+'%04d'%(NbStp-1)+'.png') plt.imshow(pict4,plt.cm.Greys) sc=plt.scatter(X0,Y0,c=T0,s=5,cmap=plt.cm.get_cmap('jet')) plt.colorbar(sc) plt.title('root tip position in time') plt.savefig('rootTip/rootTipTime.png',dpi=400) plt.savefig('rootTip/rootTipTime.svg') plt.close() #~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~# #Tracking of the root tips: ##Prepare storage folder: os.system('mkdir rootTip/byTip') ###Loop over the steps `````` Jonathan Barés committed May 23, 2019 326 ``````for iPct in range(NbStp): `````` Jonathan Barés committed Apr 23, 2019 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 `````` ###Load current tips position vector: A=np.loadtxt('rootTip/byStep/'+'%04d'%iPct+'.txt') if (A.ndim>0): ####Load the positions: if (A.ndim==1): Xc=np.array([A[0]]); Yc=np.array([A[1]]) else: Xc=A[:,0]; Yc=A[:,1] ####Check that root tip have been properly detected: if Xc[0]!=0: ####Load the time: tc=timePic[iPct] if (iPct==0): ###Initialize storage matrix: `````` Jonathan Barés committed May 23, 2019 342 `````` for iPt in range(len(Xc)): `````` Jonathan Barés committed Apr 23, 2019 343 344 345 346 347 348 349 350 351 352 353 354 355 `````` if (iPt==0): MatRoot=[np.array([Xc[iPt],Yc[iPt],tc])] else: MatRoot=MatRoot+[np.array([Xc[iPt],Yc[iPt],tc])] else: ###Track roots: while (len(Xc)>0): ####Get current coordinates: xc=Xc[0]; yc=Yc[0] ####Remove them from storage vector: Xc=np.delete(Xc,0); Yc=np.delete(Yc,0) ####Measure the distance to the previously detected tips: Dc=np.zeros(len(MatRoot)) `````` Jonathan Barés committed May 23, 2019 356 `````` for iPt in range(len(MatRoot)): `````` Jonathan Barés committed Apr 23, 2019 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 `````` #####Load the last position: if (MatRoot[iPt].ndim==1): xcc=MatRoot[iPt][0]; ycc=MatRoot[iPt][1] else: xcc=MatRoot[iPt][-1][0]; ycc=MatRoot[iPt][-1][1] #####Measure the distance: Dc[iPt]=m.sqrt((xc-xcc)**2.+(yc-ycc)**2.) ####Connect to the closest if close enough or add a new root: iPt0=np.where(Dc==np.min(Dc))[0][0] if Dc[iPt0]1): ####Load the current root: curRoot=MatRoot0[iMrt] ####Compute the root amplitude: rtAmp=np.max(np.array([np.max(curRoot[:,0])-np.min(curRoot[:,0]),np.max(curRoot[:,1])-np.min(curRoot[:,1])])) ####Keep if the root is long enough: if rtAmp>ThrProxConn/2.: if (len(MatRoot)==0): MatRoot=[curRoot] else: MatRoot=MatRoot+[MatRoot0[iMrt]] # ! Debug !: `````` Jonathan Barés committed May 23, 2019 392 ``````#~ for iMrt in range(len(MatRoot)): `````` Jonathan Barés committed Apr 23, 2019 393 394 395 396 397 398 399 400 401 402 `````` #~ curRoot=MatRoot0[iMrt] #~ plt.plot(curRoot[:,0],curRoot[:,1],'-') #~ plt.show() #~ plt.close() ##Computation of the speed: ###Prepare to store the speed amplitude: Vmin=float("inf"); Vmax=0. ###Loop over root trajectories: `````` Jonathan Barés committed May 23, 2019 403 ``````for iMrt in range(len(MatRoot)): `````` Jonathan Barés committed Apr 23, 2019 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 `````` ####Get the current trajectory: Xc=MatRoot[iMrt][:,0]; Yc=MatRoot[iMrt][:,1]; Tc=MatRoot[iMrt][:,2] ####Compute the speed: Vc=np.sqrt((Xc[1:len(Xc)]-Xc[0:len(Xc)-1])**2+(Yc[1:len(Yc)]-Yc[0:len(Yc)-1])**2)/(Tc[1:len(Tc)]-Tc[0:len(Tc)-1]) Vc=np.append(Vc,0.) ####Get the speed amplitude: if (max(Vc[np.where(VcVmax): Vmax=max(Vc[np.where(Vc0)])0)]) ####Smooth data: if (len(Vc)>10): Vc=np.convolve(Vc,np.ones(4)/4.,mode='same') ####Store data: MatRoot[iMrt]=np.transpose(np.vstack((Xc,Yc,Tc,Vc))) ##Storage of the data: `````` Jonathan Barés committed May 23, 2019 425 ``````for iMrt in range(len(MatRoot)): `````` Jonathan Barés committed Apr 23, 2019 426 427 428 429 430 431 432 `````` np.savetxt('rootTip/byTip/'+'%04d'%iMrt+'.txt',MatRoot[iMrt],delimiter=' ') ##Plot by speed: ###Prepare for graphical output: pict4=misc.imread('pictureSkeleton/mask/'+'%04d'%(NbStp-1)+'.png') plt.imshow(pict4,plt.cm.Greys) ###Loop over roots: `````` Jonathan Barés committed May 23, 2019 433 ``````for iMrt in range(len(MatRoot)): `````` Jonathan Barés committed Apr 23, 2019 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 `````` Xc=MatRoot[iMrt][:,0]; Yc=MatRoot[iMrt][:,1]; Tc=MatRoot[iMrt][:,2]; Vc=MatRoot[iMrt][:,3] if iMrt==0: sc=plt.scatter(Xc,Yc,c=Vc,s=5,cmap=plt.cm.get_cmap('jet')) plt.colorbar(sc) else: plt.scatter(Xc,Yc,c=Vc,s=5,cmap=plt.cm.get_cmap('jet')) plt.title('root tip speed') plt.savefig('rootTip/rootTipSpeed.png',dpi=400) plt.savefig('rootTip/rootTipSpeed.svg') plt.close() #~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~#~/"\~# #Other graphical outputs: ##function to plot the root skeleton with the time: timePic=np.loadtxt('time.txt') os.system('mkdir tmp') def PlotSkeleton(iPct): global timePic `````` Jonathan Barés committed May 23, 2019 456 `````` print(iPct) `````` Jonathan Barés committed Apr 23, 2019 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 `````` ###Load the time: t0=timePic[iPct] h0,m0=divmod(t0,60) j0,h0=divmod(h0,24) ###Load pictures: pictA=misc.imread('pictureSkeleton/mask/'+'%04d'%iPct+'.png') ###Plot picture: plt.imshow(pictA,cmap=plt.cm.Greys) plt.axis('off') plt.title('%02d'%j0+'days '+'%02d'%h0+'hours - '+str(iPct)) plt.savefig('tmp/'+'%04d'%iPct+'.png',dpi=150) plt.close() ##Cropping: print('... is plotting root skeleton') `````` Jonathan Barés committed May 23, 2019 472 ``````for itStp in range(NbStp): `````` Jonathan Barés committed Apr 23, 2019 473 474 475 476 477 478 479 480 481 482 483 484 485 486 `````` PlotSkeleton(itStp) ##Make movie: print('... is making the movie') null=os.system('ffmpeg -y -r 15 -f image2 -i tmp/%04d.png -qscale 1 RtSkl.avi > /dev/null') ##Remove folders: null=os.system('rm -f -R tmp') ##space time root network: os.system('mkdir tmp') fig = plt.figure() ax = fig.gca(projection='3d') `````` Jonathan Barés committed May 23, 2019 487 ``````for iMrt in range(len(MatRoot)): `````` Jonathan Barés committed Apr 23, 2019 488 489 490 491 492 493 494 495 `````` Xc=MatRoot[iMrt][:,0]; Yc=MatRoot[iMrt][:,1]; Tc=MatRoot[iMrt][:,2]; ax.plot(Tc/(24*60),Xc,-Yc,'k-',linewidth=3) plt.title('Root tip positions') ax.set_xlabel('time (d)') ax.set_ylabel('x (px)') ax.set_zlabel('y (px)') ang=np.linspace(70,70+360,360) `````` Jonathan Barés committed May 23, 2019 496 ``````for iPic in range(len(ang)): `````` Jonathan Barés committed Apr 23, 2019 497 498 499 500 501 502 503 504 505 506 `````` ax.view_init(5,ang[iPic]) plt.savefig('tmp/'+'%04d'%iPic+'.png',dpi=150) plt.close() null=os.system('ffmpeg -y -r 15 -f image2 -i tmp/%04d.png -qscale 1 TimeSpaceRoot.avi') null=os.system('rm -f -R tmp') ``````