/
pyABC.py
executable file
·1793 lines (1559 loc) · 71.1 KB
/
pyABC.py
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: UTF-8
"""
pyAnimalBehaviourCoder
An open-source software written in Python
for tracking animal body and coding animal behaviour
with collected video data.
This program was coded and tested in macOS 10.13.
Jinook Oh, Cognitive Biology department, University of Vienna
October 2019.
Dependency:
wxPython (4.0)
NumPy (1.17)
OpenCV (4.1)
------------------------------------------------------------------------
Copyright (C) 2019 Jinook Oh, W. Tecumseh Fitch
- Contact: jinook.oh@univie.ac.at, tecumseh.fitch@univie.ac.at
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
------------------------------------------------------------------------
User input with mouse and keyboard
------------------------------------------------------------------------
* Left mouse click: Set the head direction by click-and-drag
* Right mouse click: Set the head direction as -1 (when it's not available)
* Spacebar: Continue to proceed to next frames
* M: Toggle 'manual input' (Script will keep previously determined head direction until this is off)
* Cmd + S: Save CSV result data of head direction
* Cmd + Q: Quit the app
* If an user selects consecutive multiple cells (rows) in data sheet and set the head direction by click-and-drag on image,
all the selected rows will be updated as manual input.
Any column (such as head position, direction or any other column) can be selected for this operation.
------------------------------------------------------------------------
Changelog
------------------------------------------------------------------------
v.0.1: (2015-2016)
- Initial development.
v.0.2: (2019.01)
- Modification for 'Dove19' tracking.
- Re-added refactored (from 2015 code) reivison module.
v.0.3: (2019.11-12)
- Changed to pyABC from HDC.
- Changed video handling with image file to direct handling
with video file, with videoRW.py.
- Removed (commenting out for now) 'Dove19'.
- Refactoring some variable names, function names, etc.
- Added 'Macaque19' (Study by Hiroki Koda)
v.0.3.1: (2020.02)
- Changed output data array from Numpy's character array
to structred array.
"""
import queue
from threading import Thread
from os import getcwd, path
from sys import argv
from copy import copy
from time import time, sleep
from datetime import timedelta
from glob import glob
from random import shuffle
import wx, wx.adv, wx.grid
import wx.lib.scrolledpanel as SPanel
import cv2
import numpy as np
from cv_proc import CVProc
#from reviseCSV import ReviseCSV
from videoRW import VideoRW
from fFuncNClasses import GNU_notice, get_time_stamp, writeFile, getWXFonts
from fFuncNClasses import load_img, add2gbs, setupStaticText, PopupDialog
from fFuncNClasses import updateFrameSize, receiveDataFromQueue, stopAllTimers
from fFuncNClasses import calcI2DIRatio
DEBUG = False
__version__ = "0.3.1"
#=======================================================================
class AnimalBehaviourCoderFrame(wx.Frame):
""" Frame for AnimalBehaviourCoder
Attributes:
Each attribute is commented in 'setting up attributes' section.
"""
def __init__(self):
if DEBUG: print("AnimalBehaviourCoderFrame.__init__()")
### init frame
wPos = [0, 25]
wg = wx.Display(0).GetGeometry()
wSz = (wg[2], int(wg[3]*0.85))
wx.Frame.__init__(
self,
None,
-1,
"pyABCoder v.%s"%(__version__),
pos = tuple(wPos),
size = tuple(wSz),
style=wx.DEFAULT_FRAME_STYLE^(wx.RESIZE_BORDER|wx.MAXIMIZE_BOX),
)
self.SetBackgroundColour('#333333')
### set app icon
self.tbIcon = wx.adv.TaskBarIcon(iconType=wx.adv.TBI_DOCK)
icon = wx.Icon("icon.ico")
self.tbIcon.SetIcon(icon)
##### [begin] setting up attributes -----
self.th = None # thread
self.q2m = queue.Queue() # queue from thread to main
self.q2t = queue.Queue() # queue from main to thread
self.wPos = wPos # window position
self.wSz = wSz # window size
self.fonts = getWXFonts(initFontSz=8, numFonts=3)
pi = self.setPanelInfo()
self.pi = pi # pnael information
self.gbs = {} # for GridBagSizer
self.panel = {} # panels
self.timer = {} # timers
self.session_start_time = -1
self.oData = [] # output data
self.fPath = "" # folder path including frame images
self.flagVRec = False # whether to record analysis result video
self.vRecSzR = 0.25 # ratio to the original frame size
self.isRunning = False # analysis is running by pressing spacebar
self.isLBPressed = False # whether left mouse button is pressed or not
self.flagBlockUI = False # block user input
### description of parameters
self.paramDesc = {}
d = "Number of iterations of morphologyEx (for reducing noise"
d += " & minor features after absdiff from background image)."
d += " [cv2.MORPH_OPEN operation]"
self.paramDesc["bgsMExOIter"] = d
d = "Number of iterations of morphologyEx (for reducing noise"
d += " & minor features after absdiff from background image)."
d += " [cv2.MORPH_CLOSE operation]"
self.paramDesc["bgsMExCIter"] = d
d = "Parameter for cv2.threshold before edge detection."
self.paramDesc["bgsThres"] = d
d = "Parameters for hysteresis threshold of Canny function"
d += " (in edge detection of difference from background image)."
self.paramDesc["cannyTh"] = d
d = "Minimum contour size (width + height) in recognizing"
d += " contours of detected edges."
self.paramDesc["contourTh"] = d
d = "Lower and upper threshold for recognizing a motion in"
d += " a frame. Threshold value is a square root of"
d += " sum(different_pixel_values)/255."
self.paramDesc["motionTh"] = d
d = "Length (in pixels) of head direction line to draw."
self.paramDesc["hdLineLen"] = d
d = "If head direction differece is over this threshold,"
d += " reject the calculated head direction and copy the previous"
d += " frame's head direction."
self.paramDesc["uDegTh"] = d
d = "Number of clusters for k-means clustering."
self.paramDesc["uNKMC"] = d
# animal experiment cases
self.animalECaseChoices = [
'Macaque19',
'Marmoset04',
'Rat05',
#'Dove19'
]
# current animal experiment case
self.animalECase = self.animalECaseChoices[0]
# set corresponding parameters
self.setAECaseParam()
# display image type choice
self.dispImgTypeChoices = ["RGB", "Greyscale(Diff)"] #"Greyscale(Edge)"
# current display image type
self.dispImgType = self.dispImgTypeChoices[0]
self.frameImgFNformat = "f%06i.jpg"
self.lpWid = [] # wx widgets in left panel
self.ratFImgDispImg = None # ratio between frame image and
# display image on app
self.flagContManualInput = False # continuous manual input
self.dataGridSelectedCells = []
self.setDataCols() # set ouput data columns (self.dataCols),
# initival values (self.dataInitVal) and column indices
self.cv_proc = CVProc(self) # computer vision processing module
self.vRW = VideoRW(self) # for reading/writing video file
##### [end] setting up attributes -----
### create panels
for pk in pi.keys():
self.panel[pk] = SPanel.ScrolledPanel(
self,
name="%s_panel"%(pk),
pos=pi[pk]["pos"],
size=pi[pk]["sz"],
style=pi[pk]["style"],
)
self.panel[pk].SetBackgroundColour(pi[pk]["bgCol"])
##### [begin] set up top panel interface -----
tpSz = pi["tp"]["sz"]
vlSz = (-1, 20) # size of vertical line separator
self.gbs["tp"] = wx.GridBagSizer(0,0)
row = 0; col = 0
btn = wx.Button(self.panel["tp"],
-1,
label="Analyze video",
name="analyze_btn")
btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
add2gbs(self.gbs["tp"], btn, (row,col), (1,1))
'''
col += 1
btn = wx.Button(self.panel["tp"],
-1,
label="Revise analyzed results (CSV file)",
name="revise_btn")
btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
add2gbs(self.gbs["tp"], btn, (row,col), (1,1))
'''
col += 1
add2gbs(self.gbs["tp"],
wx.StaticLine(self.panel["tp"],
-1,
size=vlSz,
style=wx.LI_VERTICAL),
(row,col),
(1,1)) # vertical line separator
col += 1
sTxt = setupStaticText(
self.panel["tp"],
"Animal: ",
font=self.fonts[2],
)
add2gbs(self.gbs["tp"], sTxt, (row,col), (1,1))
col += 1
cho = wx.Choice(
self.panel["tp"],
-1,
name="animalECase_cho",
choices=self.animalECaseChoices,
)
cho.Bind(wx.EVT_CHOICE, self.onChoice)
cho.SetSelection(self.animalECaseChoices.index(self.animalECase))
add2gbs(self.gbs["tp"], cho, (row,col), (1,1))
col += 1
add2gbs(self.gbs["tp"],
wx.StaticLine(self.panel["tp"],
-1,
size=vlSz,
style=wx.LI_VERTICAL),
(row,col),
(1,1)) # vertical line separator
col += 1
sTxt = setupStaticText(
self.panel["tp"],
"Display-image: ",
font=self.fonts[2],
)
add2gbs(self.gbs["tp"], sTxt, (row,col), (1,1))
col += 1
cho = wx.Choice(
self.panel["tp"],
-1,
name="imgType_cho",
choices=self.dispImgTypeChoices,
)
cho.Bind(wx.EVT_CHOICE, self.onChoice)
add2gbs(self.gbs["tp"], cho, (row,col), (1,1))
col += 1
add2gbs(self.gbs["tp"],
wx.StaticLine(self.panel["tp"],
-1,
size=vlSz,
style=wx.LI_VERTICAL),
(row,col),
(1,1)) # vertical line separator
col += 1
chk = wx.CheckBox(
self.panel['tp'],
id=-1,
label='Continuous manual input',
name="contManualInput_chk",
style=wx.CHK_2STATE,
)
chk.Bind(wx.EVT_CHECKBOX, self.onCheckBox)
chk.SetForegroundColour('#CCCCCC')
add2gbs(self.gbs["tp"], chk, (row,col), (1,1))
nCol = int(col) # number columns
row += 1; col = 0 # new row
btn = wx.Button(self.panel["tp"],
-1,
label="Quit",
name="quit_btn")
btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
add2gbs(self.gbs["tp"], btn, (row,col), (1,2))
col += 2
sTxt = setupStaticText(
self.panel["tp"],
"0:00:00",
font=self.fonts[2],
name="ssTime_sTxt",
) # elapsed time since session starts
sTxt.SetBackgroundColour('#000000')
sTxt.SetForegroundColour('#CCCCFF')
add2gbs(self.gbs["tp"], sTxt, (row,col), (1,2))
col += 2
sTxt = setupStaticText(
self.panel["tp"],
"FPS",
font=self.fonts[2],
name="fps_sTxt",
)
sTxt.SetForegroundColour('#cccccc')
add2gbs(self.gbs["tp"], sTxt, (row,col), (1,2))
col += 2
sTxt = setupStaticText(
self.panel["tp"],
"FOLDER NAME",
font=self.fonts[2],
name="fp_sTxt",
)
sTxt.SetForegroundColour('#ffffff')
add2gbs(self.gbs["tp"], sTxt, (row,col), (1,nCol-col))
self.panel["tp"].SetSizer(self.gbs["tp"])
self.gbs["tp"].Layout()
self.panel["tp"].SetupScrolling()
##### [end] set up top panel interface -----
##### [begin] set up left panel interface -----
cho = wx.FindWindowByName("animalECase_cho", self.panel["tp"])
self.initLPWidgets() # left panel widgets
##### [end] set up left panel interface -----
##### [begin] set up image panel interface -----
### for displaying frame image
self.dispImg_sBmp_sz = pi['ip']['sz']
self.dispImg_sBmp = wx.StaticBitmap(
self.panel['ip'],
-1,
wx.NullBitmap,
(0,0),
pi['ip']['sz']
)
self.dispImg_sBmp.Bind(wx.EVT_ERASE_BACKGROUND, lambda evt: None)
self.dispImg_sBmp.Bind(wx.EVT_LEFT_DOWN, self.onMLBD_dispImg)
self.dispImg_sBmp.Bind(wx.EVT_LEFT_UP, self.onMLBU_dispImg)
self.dispImg_sBmp.Bind(wx.EVT_MOTION, self.onMMove_dispImg)
self.dispImg_sBmp.Bind(wx.EVT_RIGHT_UP, self.onMRBU_dispImg)
##### [end] set up image panel interface -----
##### [begin] set up right panel interface -----
nCol = 2
self.gbs["rp"] = wx.GridBagSizer(0,0)
row = 0; col = 0
self.dataGrid = Grid(self.panel["rp"], np.empty((0,0), dtype=np.uint8))
self.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.onDataGridCellChanged)
self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.onDataGridCellSelected)
self.Bind(wx.grid.EVT_GRID_RANGE_SELECT, self.onDataGridCellsSelected)
add2gbs(self.gbs["rp"], self.dataGrid, (row,col), (1,nCol))
row += 1; col = 0
btn = wx.Button(self.panel["rp"],
-1,
label="to the next frame",
name="nextFrame_btn")
btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
add2gbs(self.gbs["rp"], btn, (row,col), (1,1))
col += 1
btn = wx.Button(self.panel["rp"],
-1,
label="Move to the selected frame",
name="jump2frame_btn")
btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
add2gbs(self.gbs["rp"], btn, (row,col), (1,1))
col += 1
sTxt = setupStaticText(
self.panel["rp"],
"-",
font=self.fonts[2],
name="navProg_sTxt",
)
sTxt.SetForegroundColour('#cccccc')
add2gbs(self.gbs["rp"], sTxt, (row,col), (1,1))
self.panel["rp"].SetSizer(self.gbs["rp"])
self.gbs["rp"].Layout()
self.panel["rp"].SetupScrolling()
##### [end] set up right panel interface -----
### set up menu
menuBar = wx.MenuBar()
pyABCMenu = wx.Menu()
quit = pyABCMenu.Append(wx.Window.NewControlId(), item="Quit\tCTRL+Q")
menuBar.Append(pyABCMenu, "&pyABC")
self.SetMenuBar(menuBar)
### keyboard binding
exitId = wx.NewIdRef(count=1)
saveId = wx.NewIdRef(count=1)
spaceId = wx.NewIdRef(count=1) # for running analysis
miId = wx.NewIdRef(count=1) # for continuous manual input
nextFrameId = wx.NewIdRef(count=1) # for loading one frame only
self.Bind(wx.EVT_MENU, self.onClose, id=exitId)
self.Bind(wx.EVT_MENU, self.onSave, id=saveId)
self.Bind(wx.EVT_MENU, self.onSpace, id=spaceId)
self.Bind(wx.EVT_MENU,
lambda event: self.onCheckBox(event, "contManualInput_chk"),
id=miId)
self.Bind(wx.EVT_MENU,
lambda event: self.onRight(True),
id=nextFrameId)
accel_tbl = wx.AcceleratorTable([
(wx.ACCEL_CMD, ord('Q'), exitId ),
(wx.ACCEL_CMD, ord('S'), saveId ),
(wx.ACCEL_NORMAL, wx.WXK_SPACE, spaceId),
(wx.ACCEL_NORMAL, ord('M'), miId),
(wx.ACCEL_CMD, wx.WXK_RIGHT, nextFrameId),
# [Deprecated] navigation with Left/Right key
#(wx.ACCEL_SHIFT, wx.WXK_RIGHT, right_btnId ),
#(wx.ACCEL_SHIFT, wx.WXK_LEFT, left_btnId ),
#(wx.ACCEL_ALT, wx.WXK_RIGHT, rightJump_btnId ),
#(wx.ACCEL_ALT, wx.WXK_LEFT, leftJump_btnId ),
#(wx.ACCEL_CMD, wx.WXK_LEFT, leftJumpFurther_btnId),
#(wx.ACCEL_CMD, wx.WXK_RIGHT, rightJumpFurther_btnId),
])
self.SetAcceleratorTable(accel_tbl)
### set up status-bar
self.statusbar = self.CreateStatusBar(1)
self.sbBgCol = self.statusbar.GetBackgroundColour()
self.timer["sb"] = None
updateFrameSize(self, wSz)
self.Bind( wx.EVT_CLOSE, self.onClose )
#-------------------------------------------------------------------
def setPanelInfo(self):
""" Set up panel information.
Args:
None
Returns:
pi (dict): Panel information.
"""
if DEBUG: print("AnimalBehaviourCoderFrame.setPanelInfo()")
wSz = self.wSz # window size
pi = {} # panel information to return
# top panel for buttons, etc
pi["tp"] = dict(pos=(0, 0),
sz=(wSz[0], 80),
bgCol="#666666",
style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
tpSz = pi["tp"]["sz"]
# left side panel for setting parameters
pi["lp"] = dict(pos=(0, tpSz[1]),
sz=(250, wSz[1]-tpSz[1]),
bgCol="#333333",
style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
lpSz = pi["lp"]["sz"]
# right side panel for displaying coded data
pi["rp"] = dict(pos=(wSz[0]-400, tpSz[1]),
sz=(400, lpSz[1]),
bgCol="#333333",
style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
rpSz = pi["rp"]["sz"]
# panel for displaying frame image
pi["ip"] = dict(pos=(lpSz[0], tpSz[1]),
sz=(wSz[0]-lpSz[0]-rpSz[0], lpSz[1]),
bgCol="#000000",
style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
return pi
#-------------------------------------------------------------------
def setDataCols(self):
""" Set output data columns depending on animal experiment case
Args: None
Returns: None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.setDataCols()")
if self.animalECase in ["Marmoset04", "Macaque19", "Rat05"]:
self.dataCols = [
"hD", # head direction
"mHD", # head direction is manually fixed
"hPosX", # head position (x)
"hPosY", # head position (y)
"mHPos", # head position is manually fixed
"bPosX", # body postion (x)
"bPosY", # body position (y)
"remarks",
] # data columns
self.dataInitVal = [
"None", # hD
"False", # mHD
"None", # hPosX
"None", # hPosY
"False", # mHPos
"None", # bPosX
"None", # bPosY
"None", # remarks
] # initial values for data columns
### store indices for each data column
self.hdi = self.dataCols.index("hD")
self.mhdi = self.dataCols.index("mHD")
self.hxi = self.dataCols.index("hPosX")
self.hyi = self.dataCols.index("hPosY")
self.mhpi = self.dataCols.index("mHPos")
self.bxi = self.dataCols.index("bPosX")
self.byi = self.dataCols.index("bPosY")
self.dataStruct = [
('hD', (np.str_, 4)), # head direction
('mHD', (np.str_, 5)), # head direction is manually fixed
('hPosX', (np.str_, 4)), # head position (x)
('hPosY', (np.str_, 4)), # head position (y)
('mHPos', (np.str_, 5)), # head position is manually fixed
('bPosX', (np.str_, 4)), # base position (x)
('bPosY', (np.str_, 4)), # base position (y)
('remarks', (np.str_, 20)), # remakrs
] # data types for numpy structured array
'''
elif self.animalECase == "Dove19":
self.dataCols = [
"hD", # head direction
"mHD", # head direction is manually fixed
"bD", # body direction
"hPosX", # head position (x)
"hPosY", # head position (y)
"mHPos", # head position is manually fixed
"bPosX", # body postion (x)
"bPosY", # body position (y)
"b1PosX", # body position-1 (x)
"b1PosY", # body position-1 (y)
"b2PosX", # body position-2 (x)
"b2PosY", # body position-2 (y)
] # data columns
self.dataInitVal = [
"None", # hD
"False", # mHD
"None", # bD
"None", # hPosX
"None", # hPosY
"False", # mHPos
"None", # bPosX
"None", # bPosY
"None", # b1PosX
"None", # b1PosY
"None", # b2PosX
"None", # b2PosY
] # initial values for data columns
### store indices for each data column
self.hdi = self.dataCols.index("hD")
self.mhdi = self.dataCols.index("mHD")
self.bdi = self.dataCols.index("bD")
self.hxi = self.dataCols.index("hPosX")
self.hyi = self.dataCols.index("hPosY")
self.mhpi = self.dataCols.index("mHPos")
self.bxi = self.dataCols.index("bPosX")
self.byi = self.dataCols.index("bPosY")
self.b1xi = self.dataCols.index("b1PosX")
self.b1yi = self.dataCols.index("b1PosY")
self.b2xi = self.dataCols.index("b2PosX")
self.b2yi = self.dataCols.index("b2PosY")
'''
#-------------------------------------------------------------------
def initLPWidgets(self):
""" initialize wx widgets in left panel
Args: None
Returns: None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.initLPWidgets()")
for i, w in enumerate(self.lpWid):
# through widgets in left panel
self.gbs['lp'].Detach(w) # detach grid from gridBagSizer
w.Destroy() # destroy the widget
### make a list to produce widgets with parameter keys
lst = list(self.aecParam.keys()) # list of keys for parameter items
uLst = [] # this parameter items will be more likely modified by users.
for i in range(len(lst)):
if lst[i][0] == 'u':
uLst.append(str(lst[i]))
lst[i] = None
while None in lst: lst.remove(None)
lst = sorted(lst) + ["---"] + sorted(uLst)
##### [begin] set up left panel interface -----
self.gbs["lp"] = wx.GridBagSizer(0,0)
self.lpWid = [] # wx widgets in left panel
lpSz = self.pi["lp"]["sz"]
hlSz = (int(lpSz[0]*0.9), -1) # size of horizontal line
row = 0; col = 0
for key in lst:
if key == "---":
sLine = wx.StaticLine(self.panel["lp"],
-1,
size=hlSz,
style=wx.LI_HORIZONTAL)
sLine.SetForegroundColour('#CCCCCC')
self.lpWid.append(sLine)
add2gbs(self.gbs["lp"], sLine, (row,col), (1,3))
row += 1; col = 0
continue
p = self.aecParam[key]
sTxt = setupStaticText(
self.panel["lp"],
label=key,
font=self.fonts[1],
)
sTxt.SetForegroundColour('#CCCCCC')
self.lpWid.append(sTxt)
add2gbs(self.gbs["lp"], sTxt, (row,col), (1,1))
col += 1
btn = wx.Button(self.panel["lp"],
-1,
label="?",
name="%s_help_btn"%(key),
size=(25,-1))
btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
self.lpWid.append(btn)
add2gbs(self.gbs["lp"], btn, (row,col), (1,1))
col += 1
val = str(p["value"]).strip("[]")
txt = wx.TextCtrl(self.panel["lp"],
-1,
value=val,
name="%s_txt"%(key))
self.lpWid.append(txt)
add2gbs(self.gbs["lp"], txt, (row,col), (1,1))
row += 1; col = 0
###
btn = wx.Button(self.panel["lp"],
-1,
label="Analyze changed parameters",
name="applyParam_btn")
btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
self.lpWid.append(btn)
add2gbs(self.gbs["lp"], btn, (row,col), (1,3))
###
self.panel["lp"].SetSizer(self.gbs["lp"])
self.gbs["lp"].Layout()
self.panel["lp"].SetupScrolling()
##### [end] set up left panel interface -----
#-------------------------------------------------------------------
def setAECaseParam(self):
""" Set up parameters for the current animal experiment case.
* Parameter key starts with a letter 'u' means that
it will probably modified by users more frequently.
Args: None
Returns: None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.setAECaseParam()")
if self.animalECase == "":
return
elif self.animalECase == "Marmoset04":
# Common marmoset monkey experiment in 2004
# Reber, Slipogor et al
self.aecParam = {}
self.aecParam["bgsMExOIter"] = dict(value=8)
self.aecParam["bgsMExCIter"] = dict(value=8)
self.aecParam["bgsThres"] = dict(value=60)
self.aecParam["cannyTh"] = dict(value=[150, 150])
self.aecParam["contourTh"] = dict(value=50)
self.aecParam["motionTh"] = dict(value=[35, 100])
self.aecParam["hdLineLen"] = dict(value=50)
self.aecParam["uDegTh"] = dict(value=20)
elif self.animalECase == "Macaque19":
# Macaque monkey experiment in 2019
# Koda et al
subjNames = ["PoCo", "PiGe", "Lutku"]
subj = subjNames[2]
d = "Head rect size"
self.paramDesc["uHRSz"] = d
d = "HSV color min values to detect bluish wooden panel."
self.paramDesc["uCol0Min"] = d
d = "HSV color max values to detect bluish wooden panel."
self.paramDesc["uCol0Max"] = d
d = "HSV color min values to detect macaque's head."
self.paramDesc["uCol1Min"] = d
d = "HSV color max values to detect macaque's head."
self.paramDesc["uCol1Max"] = d
d = "HSV color min values to detect macaque's head."
d += ", when screen color was chaning macaque's face color."
self.paramDesc["uCol2Min"] = d
d = "HSV color max values to detect macaque's head."
d += ", when screen color was chaning macaque's face color."
self.paramDesc["uCol2Max"] = d
d = "HSV color min values to detect macaque's face."
self.paramDesc["uCol3Min"] = d
d = "HSV color max values to detect macaque's face."
self.paramDesc["uCol3Max"] = d
d = "HSV color min values to detect macaque's face"
d += ", when screen color was chaning macaque's face color."
self.paramDesc["uCol4Min"] = d
d = "HSV color max values to detect macaque's face"
d += ", when screen color was chaning macaque's face color."
self.paramDesc["uCol4Max"] = d
self.aecParam = {}
if subj == "PoCo": self.aecParam["uHRSz"] = dict(value=0.5)
elif subj == "PiGe": self.aecParam["uHRSz"] = dict(value=0.45)
elif subj == "Lutku": self.aecParam["uHRSz"] = dict(value=0.5)
self.aecParam["bgsMExOIter"] = dict(value=1)
self.aecParam["bgsMExCIter"] = dict(value=-1)
self.aecParam["bgsThres"] = dict(value=30)
self.aecParam["cannyTh"] = dict(value=[10, 30])
self.aecParam["contourTh"] = dict(value=50)
self.aecParam["motionTh"] = dict(value=[35, 300])
self.aecParam["hdLineLen"] = dict(value=150)
### bluish color of wooden panel below macaque's head
self.aecParam["uCol0Min"] = dict(value=[60,0,0])
self.aecParam["uCol0Max"] = dict(value=[100,150,150])
### brownish color of macaque's head
self.aecParam["uCol1Min"] = dict(value=[0,100,30])
self.aecParam["uCol1Max"] = dict(value=[20,255,120])
### brownish color of macaque's head when screen changes its color
self.aecParam["uCol2Min"] = dict(value=[0,100,30])
self.aecParam["uCol2Max"] = dict(value=[20,255,130])
### pinkish color of macaque's face
if subj == "PoCo":
self.aecParam["uCol3Min"] = dict(value=[0,100,150])
self.aecParam["uCol3Max"] = dict(value=[10,255,230])
elif subj == "PiGe":
self.aecParam["uCol3Min"] = dict(value=[0,120,150])
self.aecParam["uCol3Max"] = dict(value=[12,255,230])
elif subj == "Lutku":
self.aecParam["uCol3Min"] = dict(value=[0,140,100])
self.aecParam["uCol3Max"] = dict(value=[10,255,220])
### purplish color of macaque's face when screen changes its color
#self.aecParam["uCol3Min"] = dict(value=[150,120,100])
self.aecParam["uCol4Min"] = dict(value=[150,120,120])
self.aecParam["uCol4Max"] = dict(value=[200,255,230])
elif self.animalECase == "Rat05":
# Rat tracking in 2005 (for testing purpose)
self.aecParam = {}
self.aecParam["bgsMExOIter"] = dict(value=2)
self.aecParam["bgsThres"] = dict(value=50)
self.aecParam["cannyTh"] = dict(value=[150, 150])
self.aecParam["contourTh"] = dict(value=5)
self.aecParam["motionTh"] = dict(value=[25, 100])
self.aecParam["hdLineLen"] = dict(value=30)
self.aecParam["uDegTh"] = dict(value=30)
self.aecParam["uNKMC"] = dict(value=4)
'''
elif self.animalECase == "Dove19":
# Dove tracking in 2019
### params used for dove19 experiment
d = "Size threshold to find distal part of head."
self.paramDesc["uSzTh4DH"] = d
d = "Size threshold to find proximate part of head."
self.paramDesc["uSzTh4DH"] = d
d = "Minimum distance between valid bPos and hPos."
self.paramDesc["uBHDistMin"] = d
d = "Minimum size to detect dove."
self.paramDesc["uBlobSzMin"] = d
d = "Maximum size to detect dove."
self.paramDesc["uBlobSzMax"] = d
d = "Threshold to determine one of two ways to determine"
d += " the calculation method for head-direction"
d += " calculation. This value ranges from 0.0 to 1.0."
d += " Low value means the head is out of body line."
d += " High value means the head is tucked in the body line."
self.paramDesc["uHDCalcTh"] = d
self.aecParam = {}
self.aecParam["bgsMExOIter"] = dict(value=1)
self.aecParam["bgsThres"] = dict(value=20)
self.aecParam["cannyTh"] = dict(value=[150, 150])
self.aecParam["contourTh"] = dict(value=30)
self.aecParam["motionTh"] = dict(value=[20, 500])
self.aecParam["hdLineLen"] = dict(value=50)
self.aecParam["uDegTh"] = dict(value=45)
self.aecParam["uSzTh4DH"] = dict(value=75)
self.aecParam["uSzTh4PH"] = dict(value=400)
self.aecParam["uBHDistMin"] = dict(value=3)
self.aecParam["uBlobSzMin"] = dict(value=30000)
self.aecParam["uBlobSzMax"] = dict(value=50000)
self.aecParam["uHDCalcTh"] = dict(value=0.5)
'''
### add description to the dictionary
for k in self.aecParam.keys():
self.aecParam[k]["desc"] = self.paramDesc[k]
#-------------------------------------------------------------------
def onButtonPressDown(self, event, objName=""):
""" wx.Butotn was pressed.
Args:
event (wx.Event)
objName (str, optional): objName to emulate the button press
of the button with the given name.
Returns:
None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.onButtonPressDown()")
if self.flagBlockUI: return
if objName == '':
obj = event.GetEventObject()
objName = obj.GetName()
else:
obj = wx.FindWindowByName(objName, self.panel["tp"])
if not obj.IsEnabled(): return
if objName == "analyze_btn":
self.startStopAnalyzeVideo()
elif objName == "quit_btn":
self.onClose(None)
elif objName == "nextFrame_btn":
self.onRight(True)
elif objName == "jump2frame_btn":
self.jumpToFrame()
elif objName == "applyParam_btn":
self.applyChangedParam()
elif objName.endswith("_help_btn"):
key = objName.replace("_help_btn", "")
msg = self.aecParam[key]["desc"]
wx.MessageBox(msg, "Info", wx.OK|wx.ICON_INFORMATION)
'''
elif objName == "revise_btn":
self.dataRevision()
'''
#-------------------------------------------------------------------
def onChoice(self, event, objName=""):
""" wx.Choice was changed.
Args:
event (wx.Event)
objName (str, optional): objName to emulate wx.Choice event
with the given name.
Returns:
None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.onChoice()")
if self.flagBlockUI: return
if objName == "":
obj = event.GetEventObject()
objName = obj.GetName()
else:
# funcion was called by some other function without wx.Event
obj = wx.FindWindowByName(objName, self.panel["tp"])
objVal = obj.GetString(obj.GetSelection()) # text of chosen option
if objName == "animalECase_cho":
# animal experiment case was chosen
self.animalECase = objVal
self.setAECaseParam() # set animal experiment case parameters
self.initLPWidgets() # initialize left panel
self.proc_img() # display frame image
if objName == "imgType_cho":
# display image type changed
self.dispImgType = objVal
self.proc_img()
#-------------------------------------------------------------------
def onCheckBox(self, event, objName=""):
""" wx.CheckBox was changed.
Args:
event (wx.Event)
objName (str, optional): objName to emulate wx.CheckBox event
with the given name.
Returns: None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.onCheckBox()")
if self.flagBlockUI: return
if objName == "":
obj = event.GetEventObject()
objName = obj.GetName()
isChkBoxEvent = True
else:
# funcion was called by some other function without wx.Event
obj = wx.FindWindowByName(objName, self.panel["tp"])
isChkBoxEvent = False
objVal = obj.GetValue() # True/False
if objName == "contManualInput_chk":
if isChkBoxEvent:
self.flagContManualInput = objVal
else: # called by hotkey
val = not objVal # opposite of the current checkbox value
### update checkbox & flag
obj.SetValue(val)
self.flagContManualInput = val
self.cv_proc.last_motion_frame = self.vRW.currFrame.copy()
#-------------------------------------------------------------------
def onRight(self, isLoadingOneFrame=False):
""" Navigate forward
Args:
isLoadingOneFrame (bool): whether load only one frame,
False by defualt.
Returns:
None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.onRight()")
if self.flagBlockUI: return
elif self.fPath == '': return
if isLoadingOneFrame: self.isRunning = False
if self.isRunning: # if continuous analysis is running
### FPS update
self.fps += 1
if time()-self.last_fps_time >= 1:
sTxt = wx.FindWindowByName("fps_sTxt", self.panel["tp"])
sTxt.SetLabel( "FPS: %i"%(self.fps) )
self.fps = 0
self.last_fps_time = time()
if self.isRunning and self.vRW.fi >= self.vRW.nFrames-1:
# continuous running reached the end of frames
self.onSpace(None) # stop continuous running
if self.vRW.fi >= self.vRW.nFrames-1: return
self.vRW.getFrame(-1) # read one frame
self.proc_img() # process the frame
#-------------------------------------------------------------------
def onSpace(self, event):
""" start/stop continuous frame analysis
Args:
event (wx.Event)
Returns:
None
"""
if DEBUG: print("AnimalBehaviourCoderFrame.onSpace()")
if self.flagBlockUI: return
if self.fPath == '': return
if self.isRunning == False:
if self.vRW.fi >= self.vRW.nFrames-1: return
self.isRunning = True
self.fps = 0
self.last_fps_time = time()
self.timer["run"] = wx.CallLater(1, self.onRight)
else:
try: # stop timer
self.timer["run"].Stop()
self.timer["run"] = None
except:
pass
sTxt = wx.FindWindowByName("fps_sTxt", self.panel["tp"])