+ All Categories
Home > Documents > Handout Particle Tracking

Handout Particle Tracking

Date post: 20-Feb-2016
Category:
Upload: alessio-caciagli
View: 221 times
Download: 0 times
Share this document with a friend
Description:
-
31
Particle tracking with Matlab Eric M. Furst June 17, 2015 Version 2015-02-04-01 First version June 27, 2013 Copyright © 20132015 by Eric M Furst This tutorial summarizes the basic steps in particle tracking using the Matlab code authored by Daniel Blair and Eric Dufresne. The Matlab routines are based on the IDL code by John Crocker and Eric Weeks. Image quality Particle tracking begins with images of particles collected using video microscopy. While bright field images may be used, fluorescence microscopy provides a high contrast that leads to a good signal to noise ratio (SNR). The chief disadvantages of fluorescence imaging are photobleaching over time and the background fluorescence pro- duced by particles out of the focal plane, which contributes to the noise when estimating the locations of the particles. 10 0 10 1 10 2 10 3 10 4 number of pixels 250 200 150 100 50 0 intensity Figure 1: Sample fluorescence image and image histogram. Fig 3 shows a sample image of fluorescent particles. The image has 8-bit depth, so the grayscale pixels have integer values between 0 and 255. The image is 574×574 pixels. It was cropped from a larger image from a megapixel (1024×1024) camera. Notice that the image has a non-uniform background intensity. This must be corrected before particle tracking. The image has a good dynamic range that uses a wide extent of the possible 8-bit values. A histogram of the pixel intensity is shown in fig 3. Only two pixels reach the maximum value 255, and the rest are distributed with intensities well below this. The brightest pixels associated with in-focus particles are in the range of 200-255. A slightly lower intensity could be used to avoid image saturation, when multiple pixels are at the highest intensity value of the camera. Read this image file using the command: >> I = imread ( ’SampleImage . t i f ’ ) ; A quick way to check the image histogram is using the imhist com- mand in Matlab: >> imhist(I); We can also count the number of saturated pixels using the histc command. Assuming an 8-bit image in which the maximum value is 255, >> histc(I(:), 255 : 255 ) ans =
Transcript
Page 1: Handout Particle Tracking

Particle tracking with MatlabEric M. FurstJune 17, 2015 Version 2015-02-04-01

First version June 27, 2013

Copyright © 2013–2015 by Eric M FurstThis tutorial summarizes the basic steps in particle tracking usingthe Matlab code authored by Daniel Blair and Eric Dufresne. TheMatlab routines are based on the IDL code by John Crocker and EricWeeks.

Image quality

Particle tracking begins with images of particles collected using videomicroscopy. While bright field images may be used, fluorescencemicroscopy provides a high contrast that leads to a good signal tonoise ratio (SNR). The chief disadvantages of fluorescence imagingare photobleaching over time and the background fluorescence pro-duced by particles out of the focal plane, which contributes to thenoise when estimating the locations of the particles.

100101102103104

num

ber o

f pix

els

250200150100500intensity

Figure 1: Sample fluorescence imageand image histogram.

Fig 3 shows a sample image of fluorescent particles. The image has8-bit depth, so the grayscale pixels have integer values between 0 and255. The image is 574×574 pixels. It was cropped from a larger imagefrom a megapixel (1024×1024) camera. Notice that the image has anon-uniform background intensity. This must be corrected beforeparticle tracking. The image has a good dynamic range that usesa wide extent of the possible 8-bit values. A histogram of the pixelintensity is shown in fig 3. Only two pixels reach the maximum value255, and the rest are distributed with intensities well below this. Thebrightest pixels associated with in-focus particles are in the rangeof 200-255. A slightly lower intensity could be used to avoid imagesaturation, when multiple pixels are at the highest intensity value ofthe camera.

Read this image file using the command:

>> I = imread ( ’ SampleImage . t i f ’ ) ;

A quick way to check the image histogram is using the imhist com-mand in Matlab:

>> imhist ( I ) ;

We can also count the number of saturated pixels using the histc

command. Assuming an 8-bit image in which the maximum value is255,

>> h i s t c ( I ( : ) , 2 5 5 : 2 5 5 )

ans =

Page 2: Handout Particle Tracking

particle tracking with matlab 2

1

>>

The sample output indicates that there is one pixel that has the max-imum value, which is acceptable. A large number of saturated pixelswould likely lead to poor particle tracking. It is better to detect satu-rated pixels at the beginning of an experiment.

In a fluorescence image, particles that are closest to the focal planeappear as bright disks with an approximately Gaussian intensity dis-tribution. Particles above and below the focal plane will appear asrings with a central spot, as shown in fig 2. These images typify theconvolution of the particle image with the point spread function (PSF)of the imaging system. The PSF represents an intensity distributionresulting from a point source when viewed through the microscope.The maximum lateral resolving power d of a microscope is deter-mined by the diffraction limit

d =0.61λ0

NA(1)

where NA is the numerical aperture of the objective.1 For a high 1 The numerical aperture also deter-mines the amount of light collected bythe microscope.

quality water immersion microscope objective with NA = 1.2 andfluorescence emission λ = 520nm (the peak emission for fluoresceinisothiocyanate, FITC) the lateral resolution is at best 520 nm, whichis substantial fraction of the physical particle size. Non-immersionobjectives are limited to NA values below 1; the lateral resolutionfor a 40× plan-apochromat objective with NA = 0.7 is 890 nm. It isimportant that the rings remain symmetric as the particles move inand out of the focal plane. Rings that appear pinched or skewed arean indication that the illumination or imaging system is not alignedproperly.

Figure 2: Images of one particle in theparaxial focal plane and two that areout of focus.

A number of factors influence the quality of video microscopydata, including:

1. exposure time and frame rate of the camera

2. detection noise

3. fluorescence brightness of the particles and electronic gain of thedetector

Video microscopy uses an electronic camera with a pixelated ar-ray of detectors. Like any optical detector, the camera converts lightpower to electrical current, and can be a charge-coupled device (ccd),intensified ccd (iccd), electron-multiplied ccd (EM-ccd) or so-calledCMOS device based on an active-pixel sensor. The basis of operationis similar. Each pixel accumulates photoelectrons during an integra-tion time,2 σ. The number of charges accumulated is converted by the 2 Also referred to as exposure time or

shutter time.

Page 3: Handout Particle Tracking

particle tracking with matlab 3

camera to a numerical value (digital) or voltage (analog) representingthe detected light intensity.

Frame rate and exposure time

Most video cameras today acquire images at a frame rate specifiedby the user, such as 100 frames per second (fps). The frame rate isthe time between complete images, and ultimately limits the shortestlag times of particle tracking data τmin = 1/ f , are chosen such thatthe exposure time σ is at most one tenth as long as the time betweenframes, σ ≤ 0.1τmin. This ensures that the particles do not movetoo much during the image acquisition. The minimum exposuretime will depend on the sensitivity of the camera, the intensity offluorescence emission of the particles, and the overall tolerance tonoise.3 3 Are there any examples of the particle

intensity as a function of size?The frame rate of NTSC compatible ccd cameras (known as theRS-170 standard) is fixed at 30 fps. Such analog cameras are stillcommon and can be recorded directly to video tape or DVD for laterretrieval.4 4 The NTSC standard produces 480i

video—480 interlaced vertical lines. Thehorizontal resolution is typically 640

pixels and the pixels have an aspectratio of 4:3. PAL video standards usedin Europe are 525i at 25Hz.

Detection noise

Noise is inherent to electronic imaging systems due to both the quan-tization of light as photons and the electronics that carry minutephotoelectron charges and convert them into the information we seeas a pixel value in an image.

Photons are absorbed by the detector to create photoelectrons.5 5 This is the semi-classical descriptionof light; it propagates as waves, but isdetected as particles.

The instantaneous conversion rate α(t) in photoelectrons per time isproportional to the instantaneous incident power W(t) at the detec-tor,

α(t) =η(λ)

hνW(t) (2)

where η(ν) is the detector quantum efficiency at the wavelengthλ = c/ν and h is Planck’s constant.6 While eqn 2 is straightforward 6 What are the typical quantum efficien-

cies of ccd cameras?in that the instantaneous photocurrent is proportional to the instan-taneous power, consider that photons arrive at random intervals, andthus W(t) is stochastic. Therefore, the number of photoelectrons gen-erated during the detector integration time will vary. This fluctuationis the shot noise. If n is the measured number of photoelectron con-versions over the detector integration time σ, then the mean value issimply 〈n〉 = σ〈α〉σ photoelectrons per second, but the normalizedvariance is

〈n2〉 − 〈n〉2〈n〉2 =

1〈n〉 +

〈W2〉σ − 〈W〉2σ〈W〉2σ

(3)

Page 4: Handout Particle Tracking

particle tracking with matlab 4

where 〈W〉σ is the time-averaged source intensity, which is also as-sumed to fluctuate. There are two contributions to the normalizedvariance of n in eqn 3—one from the fluctuations of the source, andthe first term on the right side of the eqn, which comes from thequantum noise. We see that the shot noise scales inversely with themean photoelectron current. Shot noise will limit the signal-to-noiseratio of an image at low light intensity levels or short exposure times.In general, the SNR is the inverse of the normalized variance. Basedon eqn 3, In the absence of source fluctuations, the SNR is propor-tional to the rate of photoelectron conversions. Therefore, increasingthe light intensity or integration time should improve the SNR.

In most cases, shot noise will be the limiting source of noise of thecamera. Nonetheless, there are several forms of noise in video imag-ing that should be also kept in mind. An additional source of noise isthe dark current of the detector. This noise is thermionic in origin forsemiconductor-based detectors—the thermal energy at the detectoractive area produces a background current even in the absence oflight. This is the reason that some sensitive cameras used under lowlight conditions or for short exposure times employ a cooled detec-tor. Similarly, there is the Johnson noise of the camera electronics dueto the finite temperature of the charge carriers.7 Johnson noise is a 7 See H. Nyquist, “Thermal Agitation of

Electric Charge in Conductors”, Phys.Rev. 32, 110 (1928)

manifestation of fluctuation-dissipation. Finally, readout noise arisesin the photoelectron digitization process. For ccd cameras with slowreadout frequencies (< 1 MHz), typical readout noises are small.However, for fast ccd cameras (readout frequencies ≥ 10 MHz), read-out noise can dominate shot noise.

In image processing, it is common to characterize image SNR indecibels (dB) as8 8 See Russ, p. 376

SNR = 10 log(

σimage

σnoise

)(4)

where σimage and σimage are standard deviations of the image andnoise pixel intensities, respectively. The simpler images of brightparticles on a (mostly) dark background suggest simpler criteria forthe SNR. Savin and Doyle,9 for instance, calculate the signal as the 9 Savin, T. & Doyle, P. S. Static and

Dynamic Errors in Particle TrackingMicrorheology. Biophys. J. 88, 623–638

(2005).

difference between the local maximum brightness value of a particleand the average brightness around the spot. The noise is the standarddeviation of the brightness in regions that exclude in-focus and out-of-focus particles.10 The Rose Criterion states that a SNR of at least 5

10 Some define this as a contrast-to-noise(CNR) ratio. See, for instance, Edelstein,W. A.; Bottomley, P. A.; Hart, H. R.;Smith, L. S. (1983). "Signal, noise andcontrast in nuclear magnetic resonance(NMR) imaging". Journal of ComputerAssisted Tomography 7 (3): 391–401.

dB is required to distinguish image features with 100% certainty.11

11 Bushberg, J. T., et al., The EssentialPhysics of Medical Imaging, (2e).Philadelphia: Lippincott Williams &Wilkins, 2006, p. 280.

Let’s take a closer look at the signal and noise histograms. Thefunction SNR.m provides a measure of the signal-to-noise ratio of aparticle tracking image. Based on Savin and Doyle’s method, par-ticles are located by the particle tracking methods discussed below.

Page 5: Handout Particle Tracking

particle tracking with matlab 5

These particle images are masked and the pixel intensities of theremaining image calculated. This constitutes the background fromwhich particles are distinguished. Likewise, the pixel intensities ofthe masked particles are calculated.

Figure 3: (Top) Image detail beforefiltering. (Bottom) A close-up of a singleparticle. Pixel-to-pixel noise is evidentin this magnified image.

This is a measure of the signal. The SNR is

SNR =signal− noise

σnoise. (5)

Generate a histogram of the noise with the command

>> I = double ( imread ( ’ SampleImage . t i f ’ ) ) ;>> [ s ignal , noise ] = SNR( I , 5 ) ;

The second value in SNR is the typical feature size, roughly the di-mensions of a particle in pixels. The SNR.m routine will output thefollowing:

Maximum imagebp value i s 53 .1866

Using values > 31 .912

lo ca ted 24 p a r t i c l e s .Mean s i g n a l : 222

Mean noise : 129 .9838

Standard devia t ion noise : 9 .5949

Signal−to−noise : 9 . 5 9 0 1 ( 9 . 8 1 8 2 dB )

An image appears that shows the masked regions (signal) and thebackground region used to calculate the signal-to-noise-ratio.

The signal-to-noise data can be written to files for further analysis.Likewise, generate a histogram for the signal,

>> [ s i g n a l h i s t , s i g n a l b i n ] = h i s t ( s igna l , ( max ( s i g n a l ) . . .−min ( s i g n a l ) ) ) ;

and noise

>> [ n o i s e h i s t , noisebin ] = h i s t ( noise , ( max ( noise )−min ( noise ) ) ) ;

then check the histograms in Matlab using

>> bar ( s igna lb in , s i g n a l h i s t )>> holdCurrent plot held>> bar ( noisebin , n o i s e h i s t )

Figure 4: Masked regions (black) usedto calculate the signal in reference tothe unmasked background regions(noise). Out of focus particles constitutepart of the noise in the image.

The number of pixels that make up noise vastly outnumber the num-ber of pixels that constitutes the signal. We normalize both by theirrespective areas to illustrate their relative distributions and relation-ships to each other.

>> s i g p i x = sum( s i g n a l h i s t ) ;>> noisepix = sum( n o i s e h i s t ) ;>> s i g n a l h i s t = s i g n a l h i s t / s i g p i x ;>> n o i s e h i s t = n o i s e h i s t / noisepix ;

Now replot the normalized histograms.

Page 6: Handout Particle Tracking

particle tracking with matlab 6

>> bar ( noisebin , n o i s e h i s t )

Both signal and noise histograms can be written to files to use otherdata plotting software:

>> dlmwrite ( ’ noise_histogram ’ , [ n o i s e h i s t ; noisebin ] ’ ) ;>> dlmwrite ( ’ s ignal_his togram ’ , [ s i g n a l h i s t ; s i g n a l b i n ] ’ ) ;

60 80 100 120 140 160 180 200 220 240 2600

0.02

0.04

0.06

0.08

0.1

0.12

0.14

Figure 5: Normalized histograms ofthe noise (lower values) and signal(higher values). A wide separation ofthese distributions indicates a highsignal-to-noise ratio.

These are shown in fig 5. The normalized histograms clearly showthe distribution of the signal and noise intensities, and their separa-tion.

A final note: The SNR function masks candidate particles to calcu-late the image noise. Likewise, the brightness of the particle imagesis also calculated. However, the brightness distribution is sensitive tothe feature size w. Depending on its value, pixels near the edges ofparticles are included in the noise or with the signal. To reduce thissensitivity, we double the value of w when calculating the mask forthe noise image, and use w− 2 when evaluating the signal.

Other imaging artifacts. When the integration time of a ccddetector is sufficiently long, photoelectron charges collected in thesensor’s electronic “bins” in the brightest part of the image will over-flow to neighboring bins. This results in blooming of the image. Theintensity or exposure time should be reduced to avoid this condition.

Finally, some cameras produce interlaced images. Each video frameconsists of two fields consisting of the odd and even lines of the im-age. For the RS-170 standard, the fields are acquired 1/60th of asecond apart. Since particles may move during the time betweenthe fields are scanned, interlaced images can have a “wavy” appear-ance that results in poor tracking. These image frames should bede-interlaced by using only one of the fields before they are processedfurther.

Page 7: Handout Particle Tracking

particle tracking with matlab 7

Image filtering

The first step in particle tracking is to filter noise from the image.Read the image in with the command

>> I = double ( imread ( ’ SampleImage . t i f ’ ) ) ;

Fig 3 is a cropped image represented by the two-dimensional array Ibefore the filtering operations are applied.

Contrast gradients in the image complicate the process of identi-fying potential particles, but such variations can easily be subtractedusing a boxcar average due to the small image size and wide separa-tion of the particle features. The boxcar average is taken over a region2w + 1, where w is an integer larger than the single sphere’s imageradius in pixels, but smaller than the spacing between particles. Eachpixel is given a new value

Iw(x, y) =1

(2w + 1)2

w

∑i,j=−w

I(x + i, y + j). (6)

Figure 6: Image detail after applyingthe bpass(I,1,10) function. This topimage uses the entire dynamic rangeof the color map, while the bottom hasbeen scaled.

The second filter reduces the random noise of individual pixels byaveraging the value of nearby pixels. We perform a Gaussian averagefor each pixel with a half-width ξ = 1 pixel over the same region w,

Iξ(x, y) =∑w

i,j=−w I(x + i, y + j) exp(− i2+j2

4ξ2

)[∑w

i=−w exp (−i2/4ξ2)]2 . (7)

Since both high- and low-pass filters are performed over the sameregion w, they are calculated simultaneously using the bpass.m func-tion.12 The function output is a new image, which we call Ib,

12 Note that the Matlab code uses thefeature diameter and not the radius!

>> Ib = bpass ( I , 1 , 1 0 ) ;

The three parameters of bpass are image_array, lnoise, and lobject,corresponding to the image, the noise correlation ξ and the regiondimension w. View the filtered image with the command

>> imshow ( Ib ) ;

The output image, fig 6, shows the result of bpass.m. The imageappears quite dim, since it now has a range of values between 1 and51.2. An image scaled to the entire colormap can be viewed using

>> imshow ( Ib , [ 0 max (max ( Ib ) ) ] ) ;

and saved by first scaling the image (assuming an 8-bit image) thenwriting the image file

>> I b s c a l e d = Ib ./max (max ( bcrop ) ) . * 2 5 5 . ;>> imwrite ( Ibsca led , gray , ’ ScaledImage . png ’ ) ;

Page 8: Handout Particle Tracking

particle tracking with matlab 8

When saving files it is best to use a file format that does not use alossy compression algorithm. The portable network graphics (PNG)format is a good choice, and TIFF files are also acceptable, as longas they do not use a JPEG compression. Matlab defaults to a non-compressed TIFF file, which lead to large image files. Although Mat-lab will write JPEG format with a lossless compression algorithm,some operating systems, including OS X, do not read these files na-tively.

A sequence of unscaled and scaled images using 2w = 5, 10,and 20 are shown in fig 7. Notice that the brightness of the imagesincreases as w increases. The brightness is given by the normalizationconstant

K0 =1B

{w

∑i=−w

exp[−(i2/2ξ2)

]}2

−[

B/(2w + 1)2]

(8)

where B =[∑w

i=−w exp(−i2/4ξ2)]2.

Figure 7: A sequence of unscaled (toprow) and scaled (bottom row) imagesusing 2w = 5, 10, and 20 and ξ = 1.

Now that the background intensity variations and pixel-to-pixelnoise have been filtered, we can proceed to finding the location ofeach particle.

Page 9: Handout Particle Tracking

particle tracking with matlab 9

Locate particles

Determining particle locations in an image follows two steps: identi-fying candidate particles by the brightest pixels, then refining theselocation estimates by calculating the centroid-weighted position.

First locate the brightest pixels. A magnified image of asingle particle is shown in Fig 8. Let I(x, y) represent the intensityof the particle image. Remember, this isn’t an “exact” image of theparticle, but a convolution of the particle’s fluorescence emission andthe point spread function of the imaging system after applying thelow- and high-frequency bandpass filters.

We first identify the locally brightest pixel for each particle, whichserves as an initial estimate of the particle location, (x0, y0). Thelocally brightest pixels in the image are those with the highest valueswithin w pixels, where w is approximately the radius of the particleimage and smaller than the average distance between particles. Fromhere, most tracking routines only accept the brightest 30-40% of thesepixels as particle candidates.

Referring to the magnified particle image in Fig 8 again, thebrightest pixel is close to the image center, and to a reasonable ap-proximation, the image Ii of this ith particle is two-dimensionalGaussian centered at the position ri,

Ii(r) = I0 exp(−|r− ri|2

s2

). (9)

200150100500

intensity

1050-5-10pixel

Figure 8: (Top) A magnified image of asingle fluorescent particle after apply-ing bpass. (Bottom) A histogram of theparticle intensity and correspondingGaussian fit.

The width of the intensity distribution in Fig 8 is s = 2.98± 0.04pixels. Notice that the brightest pixel isn’t quite at the center of thefitted Gaussian distribution. It is located to the left by about 0.02pixels. This offset reflects the fact that the center of the intensity dis-tribution can be located more accurately than the maximum—whichis at best within a half a pixel of the center—and serves as a methodof refining the location of each particle to sub-pixel resolution.

To find the brightest pixels as candidate particles, we use thepkfnd.m function:

>> pk = pkfnd ( Ib , 42 , 1 0 ) ;

This function has three parameters pkfnd(im,th,sz): im is the imageto process, th is the threshold value for identifying the brightestpixels, and sz is an optional parameter for noisy data that should beset roughly to the diameter of the particle image.

A rough estimate of the threshold value can be determined by themaximum pixel value in the bandpass filtered image,

>> max ( Ib ( : ) )

Page 10: Handout Particle Tracking

particle tracking with matlab 10

ans =70 .5293

A good estimate of the threshold value is about 60% of the maximumpixel value.

The pkfnd function above locates 28 candidate particles in ourimage,

>> whos pkName Size Bytes Class A t t r i b u t e s

pk 28 x2 448 double

The array consists of two columns, the initial positions of each par-ticle (x0, y0). In fig 9 we overlay the values of pkfnd with the imageI:

>> imshow ( I , gray )>> hold on>> plot ( pk ( : , 1 ) , pk ( : , 2 ) , ’ ro ’ , ’ MarkerSize ’ , 1 0 , ’ LineWidth ’ , 2 )

Figure 9: pkfnd output indicated byred circles on the original (unfiltered)image.

The first ten location estimates in this case are:

>> pk

pk =16 422

40 442

64 78

90 562

126 194

127 330

164 293

176 247

194 484

196 348

Refine the initial location. The intensity weighted centroidsurrounding the brightest pixel serves as a refinement for the particlelocation and provides sub-pixel resolution for particle tracking. Foreach particle, this correction is calculated as(

εx

εy

)=

1m0

∑i2+j2≤w2

(ij

)I(x0 + i, y0 + j) (10)

where m0 = ∑i2+j2≤w2 I(x0 + i, y0 + j) is the integrated brightness ofthe particle image. The refined particle location is

(xi, yi) = (x0 + εx, y0 + εy). (11)

Calculating the centroid location is accomplished using the cntrd.m

function:

Page 11: Handout Particle Tracking

particle tracking with matlab 11

>> cnt = cntrd ( Ib , pk , 1 3 ) ;

The function has three input parameters, cntrd(im,mx,sz). Theparameter im is the image to process. The bandpass filtered imageIb is used here. The second parameter, mx are the locations of localmaxima to pixel-level accuracy from pkfnd.m. The third parameter,sz is the diameter of the window used to calculate the centroid. Thevalue of sz should be large enough to capture the entire particle, butnot so large that it includes other nearby particles. The recommendedsize is the diameter used with bpass plus 2, sz = 2w + 2, but sz mustbe an odd integer.

The cntrd function outputs four values for each particle: the x-coordinate, y-coordinate, brightness, and square of the radius ofgyration. Notice that not all particles are passed out of cntrd.m.

>> whos cntName Size Bytes Class A t t r i b u t e s

cnt 25 x4 800 double

Three particles are missing when we compare cnt to the originalparticle list pk produced by the pkfnd.m function. These particlesare within 1.5× the value of sz from the edge of the image and areexcluded from the final output. In fig 10 we replot the particle po-sitions cnt on the original image in blue. The locations pk are stillrepresented by red circles.

Figure 10: cntrd.m output indicated byblue circles on the original (unfiltered)image. The initial location estimatesproduced by pkfnd.m are shown in red.

Sample output for the first ten particles is listed below.

>> cnt

cnt =

1 . 0 e+03 *

0 .0397 0 .4415 2 .0651 0 .0127

0 .0640 0 .0780 1 .8489 0 .0093

0 .1263 0 .1937 1 .6106 0 .0078

0 .1271 0 .3301 2 .0742 0 .0085

0 .1641 0 .2934 2 .1422 0 .0086

0 .1757 0 .2471 1 .3045 0 .0086

0 .1945 0 .4836 1 .6830 0 .0100

0 .1955 0 .3480 2 .2580 0 .0095

0 .2099 0 .3060 2 .3052 0 .0126

0 .2133 0 .0724 2 .2438 0 .0126

The first row in cnt corresponds to the second row in pk. The origi-nal location (40, 442) has been refined to (39.7, 441.5).

An important check of the centroid location algorithm is to plota histogram of the particle location corrections produced by cntrd.m.Once many particle positions are collected over multiple frames, the

Page 12: Handout Particle Tracking

particle tracking with matlab 12

histogram should be examined. For instance, with the output arraypos_lst where the x- and y-values of the centroids are pos_lst(:,1)

and pos_lst(:,2), respectively, the command is

>> h i s t (mod( pos_loc ( : , 1 ) , 1 ) , 2 0 ) ;

which produces a histogram of the x-positions modulo 1. The his-togram should look flat, which ensures there is no bias in the posi-tion correction. We can also plot a histogram of the x- and y-positionsmodulo 1:

>> h i s t ( c a t ( 1 ,mod( p o s _ l s t ( : , 1 ) , 1 ) ,mod( p o s _ l s t ( : , 2 ) , 1 ) ) , 2 0 ) ;

or the shortened form

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

200

400

600

800

1000

1200

1400

1600

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

200

400

600

800

1000

1200

1400

1600

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

200

400

600

800

1000

1200

1400

1600

Figure 11: Histogram of x- and y-positions modulo 1 is used to discernbias in the centroid location algorithm.The top histogram was generated usinga value of the feature size in pixels, w= 11, the middle using w = 9, and thebottom histogram using w = 7. Thereare 30,354 positions in each histogram.

>> h i s t ( [mod( p o s _ l s t ( : , 1 ) , 1 ) ; mod( p o s _ l s t ( : , 2 ) , 1 ) ] , 2 0 ) ;

This plot is shown to the right. A common failure is to have peaksin the histogram near 0 and 1 and a dip at 0.5. This pattern ap-pears when the feature size is made too small, causing the x- andy-coordinates to round off to the nearest integer value. Fig 11 showsthe centroid remainders for 104 particle positions. To generate thehistograms, use the following commands:

>> [ n , xout ] = h i s t ( [mod( p o s _ l s t _ 9 ( : , 1 ) , 1 ) ;mod( p o s _ l s t _ 9 ( : , 2 ) , 1 ) ] , 2 0 ) ;

>> s t a i r s ( xout , n , ’ c o l o r ’ , [ 0 . 5 0 . 5 0 . 5 ] )>> ylim ( [ 0 1 6 0 0 ] )>> box o f f

Page 13: Handout Particle Tracking

particle tracking with matlab 13

Particle trajectories

The previous steps showed us how to locate particles in each im-age frame of video sequence. The frames, if they are acquired atregular intervals13, should act as a time stamp. Next we will use 13 Verify that the image acquisition

is not skipping frames or acquiringimages at uneven intervals.

the particle location routines for a series of images that make up avideo sequence. This is a two-step process of locating the particles ineach frame, followed by connecting the particle positions in adjacentframes to create particle trajectories in time.

Generate particle positions in all frames. First, we willprocess all of the frames in an image sequence using the routineFtrack.m. This function creates a concatenated list of particle posi-tions for each frame. Ftrack handles reading the image files succes-sively and calling the functions bpass, pkfnd, and cntrd, correspond-ing to the image bandpass filter, peak finding routine, and centroidcorrection, respectively. The image sequence is assumed to be com-posed of individual files in the working directory with the filenamefileheadxxxx.tif. The Ftrack(filehead,first,last,feature)

function has four input parameters. The parameters first and last

correspond to the image frame to start and end with. The parame-ter feature is the expected size (diameter) of the particle image, thesame feature size that is used in bpass, pkfnd and cntrd. Note thatfeature needs to be odd. The function will return an error if it is not.

The video sequence we will analyze consists of 400 frames, savedas uncompressed tiff files, with the header “frame.” Here is the out-put of the function. 14 14 It is interesting to adjust the threshold

value to change the number of particlestracked.>> p o s l i s t = Ftrack ( ’ frame ’ , 1 , 4 0 0 , 1 1 ) ;

Frame number : 10

Frame number : 20

Frame number : 30

Frame number : 40

Frame number : 50

. . .Frame number : 390

Frame number : 400

>>

The output, poslist, is a matrix with five columns.

>> whos p o s l i s tName Size Bytes Class A t t r i b u t e s

p o s l i s t 15177 x5 607080 double

Here are the first five rows of poslist.

>> format shortG>> p o s l i s t ( 1 : 5 , : )

ans =

Page 14: Handout Particle Tracking

particle tracking with matlab 14

153 .66 535 .81 3 .6716 e+05 9 .0154 1

165 .05 568 .53 4 .4652 e+05 13 .243 1

193 .36 702 .24 3 . 001 e+05 8 .6519 1

255 .68 276 .72 3 .1019 e+05 9 .3801 1

285 .72 737 .54 4 .6125 e+05 9 .5741 1

The five output columns are the x-position, y-position, m0 and m2

values, followed by the frame number. The first and second moments,m0 and m2 are useful for evaluating the particle location results. Forinstance, the user may limit particles within specific value ranges ofm0 and m2 as part of a cluster analysis, since these parameters tendto cluster systematically, as discussed by Crocker and Grier.

Save the poslist data with the command

>> dlmwrite ( ’ p o s l i s t _ w a t e r _ 1 0 1 f p s ’ , p o s l i s t )

Check the tracking results with the function Ftrack_movie. Theinput parameters are identical to Ftrack, but the routine generatesthe image with circles representing the pkfnd and cntrd results.Notice how the selection of variables such as the threshold valuein pkfnd and the feature size affect the tracking results. You will seea number of particles “blinking” on and off as they move in andout of the focal plane. This out-of-plane movement has importantimplications when creating particle trajectories, as we discuss next.

Link particle trajectories. The final step is to link particlepositions in each frame into trajectories as a function of time. Thetrack routine accomplishes this by identifying the same particle inadjoining frames. To use track(xyzs,maxdisp,param), we need tworequired parameters and one optional parameter. The first, xyzs, isthe particle position data in the format:

( x ) ( y ) ( frame )pos = 3 .60000 5 .00000 0 .00000

15 .1000 22 .6000 0 .00000

4 .10000 5 .50000 1 .00000

15 .9000 20 .7000 2 .00000

6 .20000 4 .30000 2 .00000

Note that pos(0:d-1,*) contains the d coordinates and data forall the particles, at the different times and must be positive, whilepositionlist(d,*) contains the time t that the position was deter-mined, and must be an integer (e.g. a frame number.) These valuesmust monotonically increase and be uniformly gridded in time.

To prune down poslist, we can use the command

>> pos = p o s l i s t ( : , [ 1 : 2 , 5 ] ) ;

to include on the x and y positions and frame number. However,this is not entirely necessary, since the optional param can be used to

Page 15: Handout Particle Tracking

particle tracking with matlab 15

pass additional information to the track routine that allows the otherinformation about the particles to be sorted as well. More about thatin a bit.

The second required parameter, maxdisp, is an estimate of themaximum distance that a particle moves in a single time interval.This enables particles to be associated in one frame to another andis based on the random thermal motion of non-interacting particles.While many systems of interest may not precisely fit this definition,the algorithm generally works well. However, it will work not workwell for particles moving by a strong convection. Other methods areneeded in that case.

One thing to realize is that if a particle moves out of the focalplane and returns some time later, it will be given a different identi-fier and be treated as a separate particle. However, in some trackingsoftware it is possible to specify the number of frames which a singleparticle can be “missed” and still retain its identifying number. Inthe sample data, particle 1 is not tracked in frame 3. It’s location ismissing, but the particle is tracked again in frames 4 and 5. Linking aparticle trajectory across skipped frames has the advantage of gener-ating longer trajectories, which improves the statistics for longer lagtimes.

Finally, there is the optional param structure, which has four fields,which are assigned to four function variables:

memory_b = param .mem;goodenough = param . good ;dim = param . dim ;quie t = param . quie t ;

If the parameters are not specified, then they are assigned defaultvalues.

The variable memory_b is the number of time steps a particle canbe skipped before it is assigned a new identifier. This is useful formaintaining trajectories of particles that move briefly out of the focalplane and reduces the degree of trajectory truncation. The defaultsetting is zero. The second variable, goodenough limits trajectories tothose with values equal to or greater than its value. The default valueis two. This eliminates “noise” trajectories. The boolean variablequiet eliminates text output from the routine when it is set to 1.

Set the parameters for track using the command:

>> param = s t r u c t ( ’mem’ , 0 , ’ good ’ , 0 , ’dim ’ , 2 , ’ qu ie t ’ , 0 )

param =

mem: 0

good : 0

dim : 2

quie t : 0

Page 16: Handout Particle Tracking

particle tracking with matlab 16

This creates a structure with the four required fields. Here we areusing the default values. Then pass param to the function,

>> l inked = t r a c k ( pos , 1 0 , param ) ;50 of400 done . Tracking41 p a r t i c l e s 1 5 8 t r a c k s t o t a l100 of400 done . Tracking38 p a r t i c l e s 1 2 6 t r a c k s t o t a l150 of400 done . Tracking36 p a r t i c l e s 1 3 8 t r a c k s t o t a l200 of400 done . Tracking28 p a r t i c l e s 1 4 7 t r a c k s t o t a l250 of400 done . Tracking31 p a r t i c l e s 1 0 5 t r a c k s t o t a l300 of400 done . Tracking34 p a r t i c l e s 1 3 9 t r a c k s t o t a l350 of400 done . Tracking37 p a r t i c l e s 1 1 4 t r a c k s t o t a l400 of400 done . Tracking39 p a r t i c l e s 1 4 7 t r a c k s t o t a l>>

The total number of trajectories generated are (assuming a 4-columnoutput)

>> max ( l inked ( : , 4 ) )

ans =

814

The number of trajectories generated for this data set is 814!Clearly there is some movement of particles into and out of the fo-cal plane. Let’s look at the distribution of trajectory lengths. Thetabulate command is useful for this. For every particle identified incolumn 4, tabulate will return the number of positions returned andthe frequency in the overall distribution.

>> t a b u l a t e ( l inked ( : , 4 ) )Value Count Percent

1 42 0 . 2 8%2 2 0 . 0 1%3 9 0 . 0 6%4 35 0 . 2 3%5 34 0 . 2 2%6 8 0 . 0 5%7 4 0 . 0 3%8 6 0 . 0 4%9 20 0 . 1 3%

10 13 0 . 0 9%. . .

We can plot a histogram of the trajectory lengths,

>> t r a j _ l e n g t h = t a b u l a t e ( l inked ( : , 4 ) )>> [ n , xout ] = h i s t ( t r a j _ l e n g t h ( : , 2 ) , 2 0 ) ;>> s t a i r s ( xout , n , ’ c o l o r ’ , [ 0 . 5 0 . 5 0 . 5 ] ) ;>> box o f f ;

which is shown in fig 12.

0 50 100 150 200 250 3000

100

200

300

400

500

600

700

Figure 12: Histogram of trajectorylengths. The vast majority are shorttrajectories due to particle movementout of the focal plane.

There are two things we can do at this point. We can accept“skipped” frames and link particle candidates across several frames,which will reduce the number of independent trajectories. This is ac-complished using the memory variable. There is a drawback, however,in that our data will include trajectories with skipped time steps. We

Page 17: Handout Particle Tracking

particle tracking with matlab 17

have to be careful when calculating the trajectory statistics, such asthe mean-squared displacement, to take into account the fact thatsequential image positions may be separated by more than one timestep. A key advantage is that the statistics at longer lag times willimprove by reducing the trajectory truncation.

Second, we can limit the output to trajectories of a certain lengthby specifying a value of goodenough. This parameter ensures that alltrajectories included in the results have a minimum length. Givinggoodenough a value of 2 or 3 will help reduce the overhead on thetracking routine—there is no sense having a trajectory with only oneobservation if we are to calculate the displacement of the particles.

Changing mem to 2 reduces the number of short trajectories, asshown in fig 13. The second histogram shows the results of particletracking with mem = 0 and goodenough = 20, which truncates thedata even further.

0 50 100 150 200 250 300 3500

50

100

150

200

250

300

50 100 150 200 250 3000

2

4

6

8

10

12

14

16

18

20

Figure 13: (Top) Histogram of trajectorylengths with mem = 2 and goodenough= 0. (Bottom) Trajectory lengths withmem = 0 and goodenough = 20.

Now we have an array of particle positions as a function of timewith increasing particle number. Use the last column to find thenumber of particles tracked. Obviously this is larger than the totalnumber of particles in the frame at any time due to trajectory trunca-tion. (How does this value change if memory_b is increased? What isthe longest trajectory? What is the shortest trajectory? What are thetrajectory statistics?

Calculating the MSD. The function msd = MSD(linked) calcu-lates the MSD for non-overlapping lag times. Using the raw inputfrom the previous functions, the output will be the mean-squareddisplacement in pixels2 versus the lag time in frames. The third col-umn is the number of observations for each row. Shorter lag timeshave a larger number of observations. These decrease initially as thereciprocal of the number of frames. At longer lag times, trajectorytruncation causes the number of observations to decrease even morequickly. Calibration is required to express these in terms of the realdisplacement, and the frame rate is needed to convert the lag time toa real time.

MSD.m will assume that linked consists of four columns: the x- andy- positions, the frame number and the particle ID. If tracked waspassed along with m0 and m1, then it can be pruned down using thecommand

>> l inked2 = l inked ( : , [ 1 : 2 , 5 : 6 ] ) ;

assuming that columns 3 and 4 contain the extraneous data.To summarize, calculate the MSD with the command:

>> msd = MSD( l inked ) ;

and plot it with

Page 18: Handout Particle Tracking

particle tracking with matlab 18

>> loglog (msd ( : , 1 ) , msd ( : , 2 : 3 ) )

The third column is the number of observations per data point (lagtime).

Exporting the data. The MSD data can be exported for plottingusing a graphics program. Use the command:

>> dlmwrite ( ’ msd_cmos_water_101fps_roi2048 ’ ,msd ) ;

Page 19: Handout Particle Tracking

particle tracking with matlab 19

Matlab code

What follows is Matlab code for the following functions:

SNR.m – Analyze the signal to noise ratio for an image.

vignette.m – Called by SNR.m to create masks

bpass.m – Band pass filter used to remove noise in images prior tolocating particles

pkfnd.m – Location estimate based on brightest pixel

cntrd.m – Particle location refinement based on centroid

Ftrack.m – Call the bpass, pkfnd and cntrd functions and generatethe (unsorted) position list of particles in each frame. The positionlist will be used by track to create particle trajectories.

track.m – Constructs trajectories from unsorted list of particlepositions, i.e. the output of Ftrack.m

MSD.m – Take trajectory data from track.m and calculate the MSD.

These functions are listed here in the typical order in which they arecalled.

Page 20: Handout Particle Tracking

particle tracking with matlab 20

function p o s _ l s t =Ftrack ( f i l ehead , f i r s t , l a s t , f e a t u r e )% out= c n t r d ( im , mx , sz , i n t e r a c t i v e )%% PURPOSE:% For e a c h image in a d i r e c t o r y% Read image f i l e% F i l t e r t h e image% Find b r i g h t e s t p i x e l s% Find p i x e l c e n t r o i d s% C o n c a t e n a t e p o s i t i o n s t o p o s _ l s t%%% INPUT :% f i l e h e a d : A s t r i n g common t o t h e image f i l e names% i . e . we assume t h a t t h e f i l e n a m e i s o f t h e form ’ f ramexxxx . t i f ’%% s t a r t : F i r s t f r ame t o r e a d% end : F i n a l f r ame t o r e a d%% f e a t u r e : E x p e c t e d s i z e o f t h e p a r t i c l e ( d i a m e t e r )%% NOTES:%% OUTPUT:%% CREATED: E r i c M. Furst , U n i v e r s i t y o f Delaware , J u l y 23 , 2013% M o d i f i c a t i o n s :

i f mod( fea ture , 2 ) == 0

warning ( ’ f e a t u r e s i z e must be an odd value ’ ) ;out = [ ] ;return ;

end

p o s _ l s t = [ ] ;for frame= f i r s t : l a s t

i f mod( frame ,50 )==0

disp ( [ ’ Frame number : ’ num2str ( frame ) ] ) ;end

% r e a d in f i l eimage = double ( imread ( [ f i l ehead , num2str ( frame , ’%04u ’ ) , ’ . t i f ’ ] ) ) ;

% Bandpass f i l t e rimagebp = bpass ( image , 1 , f e a t u r e ) ;

% Find l o c a t i o n s o f t h e b r i g h t e s t p i x e l s Need t o change t h e ’ th ’% ( t h r e s h o l d ) argument t o someth ing t h a t i s s p e c i f i e d or d e t e r m i n e d .% Current v a l u e i s 8000 . A rough g u i d e i s 0 . 6 * max ( imagebp ( : ) )pk = pkfnd ( imagebp , 8000 , f e a t u r e ) ;

% R e f i n e l o c a t i o n e s t i m a t e s us ing c e n t r o i dcnt = cntrd ( imagebp , pk , f e a t u r e + 2 ) ;

% c n t r d can a l s o a c c e p t " i n t e r a c t i v e " mode% c n t = c n t r d ( imagebp , pk , f e a t u r e +2 , 1 ) ;

% Add f rame number t o t r a c k i n g d a t a . Use 0 as t h e r e f e r e n c e f rame .cnt ( : , 5 ) = frame ;

% C o n c a t e n a t e t h e new frame t o t h e e x i s t i n g d a t ap o s _ l s t = [ pos_ ls t , cnt ’ ] ;

end

% Format t h e p o s i t i o n l i s t s o t h a t we have f o u r columns : x , y , m_0 , m_2 , f r amep o s _ l s t = pos_ ls t ’ ;

% I t ’ s b e t t e r t o s e p a r a t e t h e p a r t i c l e t r a c k i n g from t h e t r a j e c t o r y% a n a l y s i s . Once t h e p a r t i c l e s a r e l o c a t e d in e a c h frame , we can re−run t h e% t r a j e c t o r y a n s l y s i s us ing d i f f e r e n t p a r a m e t e r s .%% A f t e r g e n e r a t i n g t h e u n s o r t e d p o s i t i o n l i s t s , run t r a c k .m t o g e n e r a t e t h e% p a r t i c l e t r a j e c t o r i e s . The r o u t i n e t a k e s t h e f o l l o w i n g i n p u t :

Page 21: Handout Particle Tracking

particle tracking with matlab 21

% For t h e i n p u t d a t a s t r u c t u r e ( p o s i t i o n l i s t ) :% ( x ) ( y ) ( t )% pos = 3 .60000 5 .00000 0 .00000% 15 .1000 22 .6000 0 .00000% 4 .10000 5 .50000 1 .00000% 15 .9000 20 .7000 2 .00000% 6 .20000 4 .30000 2 .00000%% Use t h e command :% t r a j e c t o r i e s = t r a c k ( [ p o s _ l s t ( : , 1 : 2 ) , p o s _ l s t ( : , 5 ) ] , 1 0 ) ;

Page 22: Handout Particle Tracking

particle tracking with matlab 22

function msd = MSD( t rackdata )%% PURPOSE:% C a l c u a t e t h e MSD from t h e o u t put o f t r a c k .m%%% INPUT :% t r a c k d a t a : T r a j e c t o r y d a t a o f t h e form :% x−p o s i t i o n y−p o s i t i o n f rame p a r t i c l e i . d .%% NOTES: The p a r t i c l e i . d . i s assumed t o i n c r e m e n t from 1 t o a maximum% number o f p a r t i c l e s . For e a c h p a r t i c l e i . d . t h e f rame number i s assumed% t o i n c r e a s e . T r a j e c t o r i e s can i n c l u d e s k i p p e d f r a m e s .%% OUTPUT:% MSD: w i l l have t h r e e columns :% Column 1 : l a g t ime ( in f r a m e s )% Column 2 : MSD ( in p i x e l s )% Column 3 : number o f o b s e r v a t i o n s in a v e r a g e%% CREATED: E r i c M. Furst , U n i v e r s i t y o f Delaware , Sep t ember 8 , 2013% M o d i f i c a t i o n s :

MSD_list = [ ] ;

% Step through a l l p a r t i c l e s in t h e t r a c k e d d a t a s e tfor ( p a r t i c l e i d =1 :max ( t rackdata ( : , 4 ) ) )

% Find t h e s t a r t i n g row o f t h e p a r t i c l e i d in t r a c k d a t a% Thi s i s t h e o f f s e tindex=find ( t rackdata ( : , 4 ) = = p a r t i c l e i d , 1 ) ;

% Find t h e number o f f r a m e s f o r t h e p a r t i c l e% NOTE t h a t t h i s i s NOT e q u i v a l e n t t o t ime s t e p s o f 1 i f t h e d a t a has% " s k i p p e d f r a m e s "t o t a l f r a m e = sum( t rackdata ( : , 4 ) = = p a r t i c l e i d ) ;

% The maximum frame s e p a r a t i o n i s t o t a l f r a m e − 1max_step = t o t a l f r a m e − 1 ;

% Only a n a l y z e i f t h e r e i s more than one f rame t o c a l c u l a t e% d i s p l a c e m e n ti f max_step >= 1

disp ( [ ’ P a r t i c l e ’ , num2str ( p a r t i c l e i d ) , ’ of ’ , . . .num2str (max ( t rackdata ( : , 4 ) ) ) , ’ . Tota l frames : ’ , . . .

num2str ( t o t a l f r a m e ) ] ) ;% Step through a l l f r ame s e p a r a t i o n s s t a r t i n g from 1 up t o max_stepfor s tep =1 : max_step

% Remove comment f o r debugging% d i s p ( [ ’ Number o f s t e p s o f l e n g t h ’ , . . .% num2str ( s t e p ) , ’ : ’ , num2str ( f i x ( t o t a l f r a m e / s t e p ) ) ] ) ;

for j = 1 : ( f i x ( max_step/step ) )

% C a c u l a t e l a g t ime and mean−s q u a r e d d i s p l a c e m e n t be tween s t e p sd e l t a _ t = t rackdata ( index+ j * step , 3 ) . . .

− t rackdata ( index +( j −1)* step , 3 ) ;d e l t a _ r 2 = ( t rackdata ( index+ j * step , 1 ) . . .

− t rackdata ( index +( j −1)* step , 1 ) ) ^ 2 . . .+ ( t rackdata ( index+ j * step , 2 ) . . .− t rackdata ( index +( j −1)* step , 2 ) ) ^ 2 ;

% Remove comment f o r debugging% d i s p ( [ ’ S t ep ’ , num2str ( j ) , ’ o f ’ , . . .% num2str ( f i x ( t o t a l f r a m e / s t e p ) ) , ’ D e l t a t = ’ , . . .% num2str ( d e l t a _ t ) , ’ D e l t a r ^2 = ’ , num2str ( d e l t a _ r 2 ) ] ) ;

MSD_list = [ MSD_list , [ d e l t a _ t , d e l t a _ r 2 ] ’ ] ;end

endend

end

MSD_list = MSD_list ’ ;

Page 23: Handout Particle Tracking

particle tracking with matlab 23

% B u i l d t h e MSD from t h e MSD_list% t h e MSD w i l l have t h r e e columns :% Column 1 : l a g t ime ( in f r a m e s )% Column 2 : MSD ( in p i x e l s )% Column 3 : number o f o b s e r v a t i o n s in a v e r a g e

msd = [ ] ;min_lag = min ( MSD_list ( : , 1 ) ) ;max_lag = max ( MSD_list ( : , 1 ) ) ;for lag=min_lag : max_lag

number_obs = sum( MSD_list ( : , 1 ) = = lag ) ;i f ( number_obs >=1)

ind = find ( MSD_list ( : , 1 ) = = lag ) ;msd = [msd , [ lag mean ( MSD_list ( ind , 2 ) ) number_obs ] ’ ] ;

endend

msd = msd ’ ;

% Run with% >>msd = MSD( r e s u l t )% P l o t wi th% >> l o g l o g ( msd ( : , 1 ) , msd ( : , 2 : 3 ) )

end

Page 24: Handout Particle Tracking

particle tracking with matlab 24

function [ s igna l , noise ]=SNR( image , f ea ture , maskradius )% [ s i g n a l , n o i s e ]=SNR( image , f e a t u r e , m a s k r a d i u s )%% PURPOSE: C a l c u l a t e t h e SNR f o r a s i n g l e image . We c a l c u l a t e t h e% d i s t r i b u t i o n o f p i x e l s t h a t c o n s i s t o f our s i g n a l and t h e n o i s e . The% s i g n a l a r e t h e p i x e l s a s s o c i a t e d with t r a c k e d p a r t i c l e s . The n o i s e% c o n s i s t s o f a l l p i x e l s t h a t a r e not s i g n a l . We do t h i s by masking t h e% t r a c k e d p a r t i c l e s ( a s s i g n i n g t h e i r r e g i o n with a n e g a t i v e v a l u e ) . Note% t h a t t h e s i g n a l a r e a i s two p i x e l s s m a l l e r than t h e f e a t u r e s i z e and t h e% n o i s e a r e a i s two TIMES f e a t u r e s i z e l a r g e r . Th i s i s t o p r e v e n t t h e e d g e s% o f p a r t i c l e s from c o n t r i b u t i n g t o t h e s i g n a l o r n o i s e .%% Load t h e image with command : I = d o u b l e ( imread ( ’ t e s t . t i f ’ ) ) ;%%%% INPUT :%% image : The image t o a n a l y z e%% f e a t u r e : E x p e c t e d s i z e o f t h e p a r t i c l e ( d i a m e t e r ) t h a t c o n s t i t u t e s t h e% s i g n a l r e g i o n . A v a l u e 5 seems t o work w e l l .%% OPTIONAL INPUT :%% m a s k r a d i u s : I f an image i s v i g n e t t e d , t h i s i s t h e r a d i u s% o f t h e image t o use in c a l c u l a t i o n s . Otherwise , t h i s d e f a u l t s t o a v a l u e% 4 5 0 . A m a s k r a d i u s e q u a l t o −1 w i l l i g n o r e t h e v i g n e t t e .%% NOTES:%% OUTPUT:% s i g n a l : A v e c t o r o f p i x e l v a l u e s o f t h e t r a c k e d p a r t i c l e s% n o i s e : A v e c t o r o f p i x e l v a l u e s o f t h e background image e x c l u d i n g t a c k e d% p a r t i c l e s%% CREATED: E r i c M. Furst , U n i v e r s i t y o f Delaware , J u l y 25 , 2013% M o d i f i c a t i o n s :

i f mod( fea ture , 2 ) == 0 || f e a t u r e < 3

warning ( ’ Feature s i z e must be an odd value >= 3 . ’ ) ;s i g n a l = [ ] ;noise = [ ] ;return ;

end

% S e t t h e m a s k r a d i u s t o a d e f a u l t v a l u ei f nargin==2

maskradius =450 ;end

% r e a d in f i l e% image = d o u b l e ( imread ( f i l e n a m e ) ) ;

% Bandpass f i l t e rimagebp = bpass ( image , 1 , f e a t u r e ) ;

% Find l o c a t i o n s o f t h e b r i g h t e s t p i x e l s Need t o change t h e ’ th ’% ( t h r e s h o l d ) argument t o someth ing t h a t i s s p e c i f i e d or d e t e r m i n e d .% A rough g u i d e i s 0 . 6 * max ( imagebp ( : ) )th = 0 . 6 * max ( imagebp ( : ) ) ;pk = pkfnd ( imagebp , th , f e a t u r e ) ;disp ( [ ’Maximum imagebp value i s ’ , num2str (max ( imagebp ( : ) ) ) ] ) ;disp ( [ ’ Using values > ’ , num2str ( th ) ] ) ;disp ( [ ’ l oc a te d ’ num2str ( s ize ( pk , 1 ) ) ’ p a r t i c l e s . ’ ] ) ;

% Now we have p a r t i c l e p o s i t i o n s . Need t o mask t h e image a t t h e s e% l o c a t i o n s . Make t h e p a r t i c l e mask . Th i s i s an a r r a y with −1 f o r% v a l u e s w i t h i n a r a d i u s o f h a l f t h e f e a t u r e s i z e .sz = 2* f e a t u r e +1 ;r = ( sz−1)/2 ;[ x , y]= meshgrid (−( r ) : ( sz−r−1) ,−( r ) : ( sz−r −1 ) ) ;par t ic lemask = ( ( x .^2+y.^2) <= r ^ 2 ) ;

Page 25: Handout Particle Tracking

particle tracking with matlab 25

part ic lemask = ( ( x .^2+y.^2 ) > r^2)−part ic lemask ;

% go through l i s t o f p a r t i c l e l o c a t i o n s% make a c i r c l e o f r a d i u s f e a t u r e a t e a c h l o c a t i o n with v a l u e −1imagenoise = image ;for i =1 : s ize ( pk , 1 ) ;

x = pk ( i , 1 ) ;y = pk ( i , 2 ) ;imagenoise ( ( y−r ) : ( y+r ) , ( x−r ) : ( x+r ) ) = . . .

image ( ( y−r ) : ( y+r ) , ( x−r ) : ( x+r ) ) . * par t ic lemask ;end

% Make t h e mask f o r t h e s i g n a lsz = feature −2;r = ( sz−1)/2 ;[ x , y]= meshgrid (−( r ) : ( sz−r−1) ,−( r ) : ( sz−r −1 ) ) ;par t ic lemask = ( ( x .^2+y.^2) <= r ^ 2 ) ;par t ic lemask = ( ( x .^2+y.^2 ) > r^2)−part ic lemask ;

% go through l i s t o f p a r t i c l e l o c a t i o n s% make a c i r c l e o f r a d i u s f e a t u r e a t e a c h l o c a t i o n with v a l u e −1imagesignal = image ;for i =1 : s ize ( pk , 1 ) ;

x = pk ( i , 1 ) ;y = pk ( i , 2 ) ;imagesignal ( ( y−r ) : ( y+r ) , ( x−r ) : ( x+r ) ) = . . .

image ( ( y−r ) : ( y+r ) , ( x−r ) : ( x+r ) ) . * par t ic lemask ;end

imagesignal = −imagesignal ;

% F i n a l l y , mask t h e image t o e x c l u d e v i g n e t t e r e g i o n simagenoise = v i g n e t t e ( imagenoise , maskradius , −1 ) ;imagesignal = v i g n e t t e ( imagesignal , maskradius , −1 ) ;

% Now t h a t we have maskimage , l e t ’ s c a l c u l a t e t h e n o i s e% S t a t i s t i c s o f a l l r e g i o n s with p o s i t i v e v a l u e s > 0index = find ( imagenoise > 0 ) ;noise = image ( index ) ;index = find ( imagesignal > 0 ) ;s i g n a l = image ( index ) ;

imagesc ( imagenoise ./max ( imagenoise ( : ) ) ) ;disp ( [ ’Mean s i g n a l : ’ , num2str (mean ( s i g n a l ) ) ] ) ;disp ( [ ’Mean noise : ’ , num2str (mean ( noise ) ) ] ) ;disp ( [ ’ Standard devia t ion noise : ’ , num2str ( std ( noise ) ) ] ) ;disp ( [ ’ S ignal−to−noise : ’ , num2str ( ( mean ( s i g n a l )−mean ( noise ) ) / std ( noise ) ) , . . .

’ ( ’ , num2str ( 1 0 * log10 ( ( mean ( s i g n a l )−mean ( noise ) ) / std ( noise ) ) ) , ’ dB ) ’ ] ) ;

end

Page 26: Handout Particle Tracking

particle tracking with matlab 26

function masked_image = v i g n e t t e ( image , radius , value )% out= c n t r d ( im , mx , sz , i n t e r a c t i v e )%% PURPOSE:% Mask a v i g n e t t e d image by s e t t i n g t h e l o c a t i o n s o u t s i d e o f a% r a d i u s e q u a l t o v a l u e . The d e f a u l t v a l u e i s 0 .%%% INPUT :% image : The o r i g i n a l image% r a d i u s : The r a d i u s o f t h e d e s i r e d v i g n e t t e in p i x e l s . I f t h e r a d i u s i s% −1, j u s t r e t u r n t h e o r i g i n a l image .% v a l u e : S e t t o v a l u e . OPTIONAL . D e f a u l t t o 0 .%% NOTES:%% OUTPUT: A masked image%% CREATED: E r i c M. Furst , U n i v e r s i t y o f Delaware , J u l y 23 , 2013% M o d i f i c a t i o n s :

i f nargin==2

value =0 ;end

i f radius <0

masked_image = image ;

e lse% Make mask% Get t h e s i z e o f image%[ ix , iy ] = s ize ( image ) ;

% cx and cy a r e t h e c e n t e r c o o r d i n a t e s o f t h e c i r c l ecx= i x /2 ;cy=iy /2 ;

%[ x , y]= meshgrid (−( cx −1 ) : ( ix−cx ) ,− ( cy−1 ) : ( iy−cy ) ) ;c_mask = ( ( x .^2+y.^2) <= radius ^ 2 ) ;mask_outside = ( c_mask−1)*(−value ) + c_mask ;

masked_image = image . * c_mask + mask_outside ;end

Page 27: Handout Particle Tracking

particle tracking with matlab 27

Notes on the routine cntrd.m

First, we basically make a mask with radius r = (sz + 1)/2.Here, sz = 11. The variable ind was created by making a similararray (dst) and using the values of the radius at each of the matrixentries.

>> msk( ind ) = 1 . 0 ;>> msk

msk =

0 0 0 0 1 1 1 1 0 0

0 0

0 0 1 1 1 1 1 1 1 1

0 0

0 1 1 1 1 1 1 1 1 1

1 0

0 1 1 1 1 1 1 1 1 1

1 0

1 1 1 1 1 1 1 1 1 1

1 1

1 1 1 1 1 1 1 1 1 1

1 1

1 1 1 1 1 1 1 1 1 1

1 1

1 1 1 1 1 1 1 1 1 1

1 1

0 1 1 1 1 1 1 1 1 1

1 0

0 1 1 1 1 1 1 1 1 1

1 0

0 0 1 1 1 1 1 1 1 1

0 0

0 0 0 0 1 1 1 1 0 0

0 0

Page 28: Handout Particle Tracking

particle tracking with matlab 28

Notes on Matlab

Image processing

For help: help images

Help topic Description

images/colorspaces - Image Processing Toolbox — colorspacesimages/images - Image Processing Toolboximages/imuitools - Image Processing Toolbox — imuitoolsimages/iptformats - Image Processing Toolbox — File Formatsimages/iptutils - Image Processing Toolbox — utilitiesimages/imdemos - Image Processing Toolbox — demos and sample images

Helpful image processing commands

Note that a grayscale image can be either single or double butmust have values between 0 and 1. There are three commands to dis-play an image, depending on the data type (image or array): imshow,image, or imagesc.

Command Description

I = imread(’SampleImage.tif’); read an imageimshow(I) show image (native type)I = double(imread(’SampleImage.tif’)); read an image as type double

image(I); display array as image (use for double types)imagesc(I); scale data and display as image

imwrite(I,’filename.png’) write an image file. Format set by extension.imhist(I); produce a histogram of the image I

max(max(b)) maximum value of matrix b

max(b(:)) alternate maximum value of matrix b

histc(I(:),255:255) count the number of saturated pixels in an 8-bit image

deconvblind Deblur image using blind deconvolution

figure Create a new figure window. Select using figure(1).

Image processing used in particle tracking

Command Description

imagesc Scale data and display as imageimwrite(b,gray,’test.tif’) Write matrix b, where b = bpass(image,1,15)

The “Image enhancement and analysis” help page provides somesteps for flattening an image background (this could be helpful for

Page 29: Handout Particle Tracking

particle tracking with matlab 29

analyzing the images of riso pasta.)

Image statistics

Command Description

mean(I(:)) Calculate the mean value of an imagestd(I(:)) Calculate the standard deviation of an image

Plotting commands

Command Description

plot(X, Y, params) Plot valuesplot(pos_lst(:,6),pos_lst(:,5),’.’,’Color’,[0.5 0.5 0.5]) Plot with gray dot symbol

hist(data, bins) or hist(data) Create a histogram of datah = findobj(gca,’Type’,’patch’); Change the color of a histogramset(h,’FaceColor’,[0.5 0.5 0.5],’EdgeColor’,’w’)

box off Remove the plot frame

[n,xout] = hist(...) returns vectors n and xout containing the frequency countsbar(xout,n) and the bin locations. Plot with the bar command orstairs(X, Y, ’line spec’); the stairs command.set(gca, ’YScale’, ’log’) set logarithmic scale

Basic Matlab

When using Matlab matrices, remember that Matlab uses a(row, column) format.

Make a matrix with dimensions row × column:

>> matrix =

Loading a tab-delimited data file, such as the output to aparticle tracking routine:

>> foo = dlmread(’filename’);

To write a delimitated file,

>> dlmwrite(’filename’, M, ’delimiter’);

The default —

Given the 7-column vector T,

Page 30: Handout Particle Tracking

particle tracking with matlab 30

>> whos T

Name Size Bytes Class Attributes

T 110943x7 6212808 double

select the first column using

>> T(:,1)

ans =

493.4690

493.4720

493.5570

493.5880

493.1810

493.5850

493.3890

493.1830

493.2670

493.2690

...

or a subset of the column,

>> T(1:10,1)

Size of matrix Use the size command.

>> s ize ( back , 1 )

ans =

92

For instance, to display the number of data points collected (herebackscatterdist is a matrix with columns t, x, y, and z)

disp ( [ ’Number of b a c k s c a t t e r e d t r a j e c t o r i e s : ’ , . . .num2str ( s ize ( b a c k s c a t t e r d i s t , 2 ) ) ] ) ;

Display format

The command format sets the output format. The default setting isshort. See help format for additional formats. Below is the differ-ence between short and shortG

>> format short

>> foo

Page 31: Handout Particle Tracking

particle tracking with matlab 31

foo =

1.0e+03 *

0.0397 0.4415 2.0651 0.0127

0.0640 0.0780 1.8489 0.0093

0.1263 0.1937 1.6106 0.0078

0.1271 0.3301 2.0742 0.0085

0.1641 0.2934 2.1422 0.0086

0.1757 0.2471 1.3045 0.0086

0.1945 0.4836 1.6830 0.0100

0.1955 0.3480 2.2580 0.0095

0.2099 0.3060 2.3052 0.0126

0.2133 0.0724 2.2438 0.0126

>> format shortG

>> foo

foo =

39.7 441.5 2065.1 12.7

64 78 1848.9 9.3

126.3 193.7 1610.6 7.8

127.1 330.1 2074.2 8.5

164.1 293.4 2142.2 8.6

175.7 247.1 1304.5 8.6

194.5 483.6 1683 10

195.5 348 2258 9.5

209.9 306 2305.2 12.6

213.3 72.4 2243.8 12.6

>>


Recommended