-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBrightObjectTracker.m
614 lines (472 loc) · 19.3 KB
/
BrightObjectTracker.m
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
164
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
function [objPt, frameIndx] = BrightObjectTracker(loadfun,findFeaturesFun,minFrame,maxFrame,optAltChLoc)
% Load in a frame at a time and allows the user to navigate between frames.
%
% IMPORTANT: See sample.m for development
%
% This is the main code for tracking objects. It includes the code to
% create the GUI.
%
% For programming and development see sample.m in the same folder. That
% provides a testbed to run this function.
%
%%%% INPUTS:
% loadfun is a function handle to load in a frame, generated by
% getLoadFrameHandle.m
%
% findFeaturesFun is a function to find features in the image, it is
% generated by getFindFEaturesCandidatesHandle.m
%
% minFrame and maxFrame define the range of frames to analyze
%
% optAltChLoc [optional, for temporally alternating red/green channel only]
% A matrix containing the x y coordinate locations of the neuron
% in the alternate channel. This is used to help the user find the location
% of dim GCaMP3 signals, because it shows where the neuron is in the
% mCherry channel immediately before and after the frame of interest.
% The elements should be indexed such that the nth frame is the nth element
%
% Note the convention is that for current channel frame x the alternate channel
% frame x-1 is previous in time and the alternate channel # x is forward in
% time
%
%%% Outputs
%
%
%Note! FrameIndx merely lists the frames that were analyzed.
% The vector point contains the location of those points found.
% so for example, if the neuron was located in frames 500-510, then the
% vector "objPt" would have 510 elements in them, the first 499 would be
% (-1,-1) and elements 500-510 would contain the actual location of the
% neurons.
%
% This is a stupid system. It means that, for example, there can't be a
% zero frame. But at this point everything is working and I don't feel like
% going back and fixing it.
%
% Andrew Leifer
% leifer@fas.harvard.edu
% 13 March 2012
%Check input
if ~exist('optAltChLoc','var')
optAltChLoc='';
end
% Define State Variables
frame=minFrame; %Current frame
I=[]; %Current Image
status=''; %Are we out of range?
currPts=[]; %current Extracted features
manPt=[]; %current manually entered pt.
dispFeat=true; %display features?
record=true; %record features
featRadius=15;
currFeat=1; %current Feature (brightest, 2nd brightest, occluded, manual, etc..)
%A note about current features... the following table determines the
%value of current feature:
% -2: Not yet analyzed
% -1: Occluded
% 0: Manually Specificed Value
% 1: Brightest Feature
% 2: 2nd Brightest
% 3: 3rd Brightest
% 4: 4th Brighest
% .
% .
% .
mutEx=[]; %array of mutually exclusive toggle button handles (one for occluded, one for brightest, etc..)
brightVsPosHandle=[]; %Array of handles to the two mutually exclusive
%buttons for finding each frame based on the same
%relative brightness as the previous frame or based
%on the closest position to the previous frame.
BRIGHTNESS=1;
POSITION=2;
featReccomendMode=BRIGHTNESS; %This is the feature location recommendation mode
%Brightness is the default mode.
statusTextHandle=[]; %Handle to text object
% Feature Data
frameIndx=minFrame:maxFrame; %index of frames
featureType=-2.*ones(size(frameIndx)); %type of feature for each frame
featureLoc=ones(size(1:frameIndx(end)),2).*-1; %Location of the feature
%each row corresponds a frame in
%NOTE: that the nth element
%corresponds to frame #n.
%This is not at all ideal, but it
%seems to be how I wrote it.
% Initialize System
fig = figure('KeyPressFcn',@keyHandler,'CloseRequestFcn',@closeTracker);
LoadExtractAndDisplayEverything(frame);
%Draw the Gui
drawgui;
%Pause the UI and wait for the user to close
uiwait(fig);
% Exit
objPt=featureLoc; %Copy featureLoc to function output
status=1;
%% Display and Plot the current Image (& Draw Gui)
function RefreshDisplayAndPlot
gcf; clf
drawgui;
%plot the image
imagesc(I);
if currFeat == 0 %if we are in manual entry
clear('manPt');
manPt=ginput(1); %have the user select a point
plotCurrentPts(manPt,currFeat); % display that point
elseif dispFeat %Plot Current Pts
plotCurrentPts(currPts,currFeat)
end
end
%% Load in a frame, Find Features, Display Image, Plot Points
function LoadExtractAndDisplayEverything(frame)
%Set the desired frame
set(gcf,'Name',['Frame: ' num2str(frame)]);
[I,status]=loadfun(frame); %Load in the frames
currPts=findFeaturesFun(I,featRadius,frame); %Find the first N candidate features
%If we are in position mode, we should select the current feature
% by finding the one closes to the previous frame.
if featReccomendMode==POSITION
currFeat=findFeatClosestToPrevFrame(currPts,frame,featureLoc);
end
RefreshDisplayAndPlot;
end
function closestFeat=findFeatClosestToPrevFrame(currPts,frame,featureLoc);
%If the last frame had an occluded point or is out of bounds,
% keep the currently recommended feature brightness level
%(e.g. occluded, or diamond or whatever)
closestFeat=currFeat; %Keep current recommendation
%If frame-1 exists
if (frame-1>0)
prevFrameLoc=featureLoc(frame-1,:); %Get Location from Prev Frame
%If the frame isn't empty and isn't occluded
if ~isempty(featureLoc(frame-1,:))&& ~all( prevFrameLoc<1)
%find the feature whose location is nearest to the one from the previous frame.
%Calculate cartesion distance between each currPt and the
%previous frame location
distForEachFeat=sqrt(sum((currPts-repMat(prevFrameLoc,size(currPts,1),1)).^2,2));
%Find min
[~,minDistFeat]=min(distForEachFeat); %Find the index of the minimum(s)
closestFeat=minDistFeat(1); %overwrite the closest feawture
end
end
end
%% Figure Close Function
function closeTracker(src,evnt)
button = questdlg('Are you sure you are finished?','Finished?','Exit!','Return to data entry','Return to data entry');
if strcmp(button,'Exit!')
uiresume(gcbf);
delete(gcf);
end
ReleaseFocus(gcbf);
end
%% CLick Increment / Decrement the Frame
function clickIncrement(src,evnt)
recordFeature;
ReleaseFocus(gcbf);
incrementFrame;
end
function clickDecrement(src,evnt)
recordFeature;
ReleaseFocus(gcbf);
decrementFrame;
end
%% Decrement Frame
function decrementFrame
if frame-1>=minFrame
frame=frame-1;
disp('Backward')
%Load & Display Everything
LoadExtractAndDisplayEverything(frame)
else
disp('Out of range');
end
end
%% Increment Frame
function incrementFrame
if frame+1<=maxFrame
frame=frame+1;
disp('Forward')
%Load & Display Everything
LoadExtractAndDisplayEverything(frame)
else
disp('Out of range');
end
end
%% Record Feature for this Frame
function recordFeature
if record
featureType(frame)=currFeat;
if currFeat ~=0 && currFeat >-2 %not manual & is valid
if currFeat>0 %if not occluded
featureLoc(frame,:)=currPts(currFeat,:);
else
featureLoc(frame,:)=[-1,-1];
end
else
%Manual
featureLoc(frame,:)=manPt;
end
end
%Record is turned off so don't do anythning
end
%% KeyHandler
function keyHandler(src,evnt)
if ~isempty(evnt.Modifier)
for ii = 1:length(evnt.Modifier)
out = sprintf('Character: %c\nModifier: %s\nKey: %s\n',evnt.Character,evnt.Modifier{ii},evnt.Key);
disp(out)
end
else
out = sprintf('Character: %c\nModifier: %s\nKey: %s\n',evnt.Character,'No modifier key',evnt.Key);
disp(out)
end
%Forward
if strcmp(evnt.Key,'space') || strcmp(evnt.Key,'rightarrow')
recordFeature;
incrementFrame;
%Backward
elseif strcmp(evnt.Key,'backspace') || strcmp(evnt.Key,'leftarrow')
recordFeature;
decrementFrame;
elseif strcmp(evnt.Character,'h')
dispFeat=~dispFeat;
RefreshDisplayAndPlot;
disp('Hide/Show Features');
end
%Ignore the key stroke
end
%% Toggle Feature Record Callback
function RecordCallback(src,evnt)
record=logical(get(gcbo,'Value'));
ReleaseFocus(gcbf);
end
%% mutEx Button Callbacks
function mutExButtonCallback(src,evnt,feature)
%When a mutually exclusive toggle button is clicked, record the
%currently clicked button and then untoggle all the others.
thisButton=gcbo;
set(thisButton,'Value',1); %Depressed
%Turn off all the other mutually excluded feature buttons
for k=1:length(mutEx)
if thisButton~=mutEx(k)
set(mutEx(k),'Value',0); %Not Depressed
end
end
%Set the current Feature
currFeat=feature;
ReleaseFocus(gcbf);
RefreshDisplayAndPlot;
end
%% Toggle between find same brightness mode or find same position mode
function flipBrightnessVsPosition(src,evnt)
%This handles clicking in the brigthness mode or the position mode
%button. The two are mutually exclusive. One instructs the software
%to default to the point that has the same brigthness as the
%previou frame's. The other defaults to choosing the point that is
%closest to the previous frames.
thisButton=gcbo;
set(thisButton,'Value',1); %Depress the current button
assert(thisButton==brightVsPosHandle(POSITION)|| thisButton==brightVsPosHandle(BRIGHTNESS));
%Unpress the other button
if thisButton==brightVsPosHandle(BRIGHTNESS)
set(brightVsPosHandle(POSITION),'Value',0);
featReccomendMode=BRIGHTNESS; %Set mode to Brigthness
else
set(brightVsPosHandle(BRIGHTNESS),'Value',0);
featReccomendMode=POSITION; %Set Mode to Position
end
ReleaseFocus(gcbf);
RefreshDisplayAndPlot;
end
%% Get Status Text To Display
function text=getStatusText
if record
if currFeat==-1
text=['RECORDING Feature: Occluded']
elseif currFeat==0
text=['RECORDING Feature: ' num2str(currFeat) ...
' Loc: (' num2str(manPt) ')' ] ;
elseif currFeat >0
text=['RECORDING Feature: ' num2str(currFeat) ...
' Loc: (' num2str(currPts(currFeat,:)) ')' ] ;
else
text=['This feature is not supported'];
end
else
text=['Viewing Feature: ' num2str(featureType(frame)) ...
' Loc: (' num2str(featureLoc(frame,:)) ')' ] ;
end
end
%Set the Feature Radius
function setFeatRadius(svc,evnt)
featRadius=round(get(gcbo,'Value'));
set(findobj('Tag','featRadiusText'),'String',num2str(featRadius));
LoadExtractAndDisplayEverything(frame) ;
end
%% GUI
function drawgui
leftPosOfButtons=.72;
btnWidth=.27;
set(gca,'Position',[0.01,0.01,0.7,1]);
gcf;
%Overwriting
recordButton=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .93 btnWidth .06],...
'String','Record ON/OFF',...
'Value',record,...
'CallBack',@RecordCallback);
%Status Text Handle
statusTextHandle=uicontrol('Style','text',...
'Units','Normalized',...
'Position',[leftPosOfButtons .875 btnWidth .055],...
'String',getStatusText);
%Use Same Brightness vs Same Position
brightVsPosHandle(1)=uicontrol('Style','PushButton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .79 .13 .08],...
'String','Brightness',...
'Value',featReccomendMode==BRIGHTNESS,...
'CallBack',@flipBrightnessVsPosition);
brightVsPosHandle(2)=uicontrol('Style','PushButton',...
'Units','Normalized',...
'Position',[leftPosOfButtons+.135 .79 .13 .08],...
'String','Position',...
'Value',featReccomendMode==POSITION,...
'CallBack',@flipBrightnessVsPosition);
%Brightest
mutEx(2)=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .71 btnWidth .07],...
'String','1st (Diamond)',...
'Value',currFeat==1,...
'CallBack',{@mutExButtonCallback,1});
%2nd Brightest
mutEx(3)=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .63 btnWidth .07],...
'String','2nd (Circle)',...
'Value',currFeat==2,...
'CallBack',{@mutExButtonCallback,2});
%3rd Brightest
mutEx(4)=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .55 btnWidth .07],...
'String','3rd (Square)',...
'Value',currFeat==3,...
'CallBack',{@mutExButtonCallback,3});
%4th Brightest
mutEx(5)=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .47 btnWidth .07],...
'String','4th (+)',...
'Value',currFeat==4,...
'CallBack',{@mutExButtonCallback,4});
%5th Brightest
mutEx(6)=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .39 btnWidth .07],...
'String','5th (*)',...
'Value',currFeat==5,...
'CallBack',{@mutExButtonCallback,5});
%If the feature finding function gives us less than 5 potential features to choose from,
%then we should disable some of the buttons
numFeats=size(currPts,1); %Number of Features
numButtons=5;
if numFeats <numButtons
%Turn off the unnecessary buttons
set(mutEx( (numFeats+1:numButtons) +1 ),'Enable','off')
end
%STatus Text
%Left and Right Buttons
uicontrol('Style','PushButton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .27 .13 .1],...
'String','<-',...
'CallBack',@clickDecrement);
uicontrol('Style','PushButton',...
'Units','Normalized',...
'Position',[leftPosOfButtons+.135 .27 .13 .1],...
'String','->',...
'CallBack',@clickIncrement);
%Occluded
mutEx(1)=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .19 btnWidth .07],...
'String','Occluded',...
'Value',currFeat==-1,...
'CallBack',{@mutExButtonCallback,-1});
%Manual
mutEx(7)=uicontrol('Style','togglebutton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .11 btnWidth .07],...
'String','Manual Entry',...
'Value',currFeat==0,...
'CallBack',{@mutExButtonCallback,0});
%Feature Size Control
uicontrol('Style','slider',...
'Units','Normalized',...
'Position',[leftPosOfButtons .06 .23 .03],...
'String','FeatureSize',...
'Min',1, 'Max',50,...
'Value',featRadius,...
'SliderStep',[.1 1/50],...
'CallBack',@setFeatRadius);
%Feature Size Control Text!
uicontrol('Style','text',...
'Units','Normalized',...
'Position',[leftPosOfButtons+.22, .06, .06, .03],...
'String',num2Str(featRadius),...
'Tag','featRadiusText');
%Done
doneButton = uicontrol('Style','PushButton',...
'Units','Normalized',...
'Position',[leftPosOfButtons .01 btnWidth .04],...
'String','Done',...
'CallBack',@closeTracker);
end
%% Plot Current Points
function plotCurrentPts(currPts,currFeat)
shapeList={'d','o','s','+','*','^'};
defaultColor='w';
defaultWidth=1;
specialColor='r';
specialWidth=2;
gcf;
hold on;
if currFeat ~=0 %If we aren't doing manual data entry
%Plot the brightest points
for k=1:size(currPts,1)
if k==currFeat
%use special values
c=specialColor;
w=specialWidth;
else
%use default values
c=defaultColor;
w=defaultWidth;
end
plot(currPts(k,1), currPts(k,2),shapeList{k},...
'MarkerEdgeColor',c,'MarkerSize',8,'LineWidth',w)
end
else
plot(currPts(1), currPts(2),'o',...
'MarkerEdgeColor',specialColor,'MarkerSize',8,'LineWidth',specialWidth)
end
%If this is temporally interleaved red/green channel
% recording, plot the location of the neuron before and after this frame
% as located in the other channel if provided.
if ~isempty(optAltChLoc) && frame < length(optAltChLoc) && frame >1
%Display location of neuron from other channel as found
%in previous frame
prevLocAltCh=optAltChLoc(frame-1,:);
nextLocAltCh=optAltChLoc(frame,:);
if ~isempty(prevLocAltCh)
plot(prevLocAltCh(1), prevLocAltCh(2),'>',...
'MarkerEdgeColor',[1 .5 0],'MarkerSize',8,'LineWidth',defaultWidth+.5);
end
if ~isempty(nextLocAltCh)
plot(nextLocAltCh(1), nextLocAltCh(2),'s',...
'MarkerEdgeColor',[1 .5 0],'MarkerSize',8,'LineWidth',defaultWidth+.5);
end
end
end
end