forked from lukefi/FishTracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
playback_manager.py
686 lines (561 loc) · 22.2 KB
/
playback_manager.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
"""
This file is part of Fish Tracker.
Copyright 2021, VTT Technical research centre of Finland Ltd.
Developed by: Mikael Uimonen.
Fish Tracker 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.
Fish Tracker 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 Fish Tracker. If not, see <https://www.gnu.org/licenses/>.
"""
import sys, os, errno
import traceback
import file_handler as fh
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import cv2, time
import numpy as np
from queue import Queue
import gc
from polar_transform import PolarTransform
from log_object import LogObject
FRAME_SIZE = 1.5
class Event(list):
def __call__(self, *args, **kwargs):
for f in self:
f(*args, **kwargs)
def __repr__(self):
return "Event(%s)" % list.__repr__(self)
class PlaybackManager(QObject):
# Signals that polar mapping is done and a PolarTransform object is created
mapping_done = pyqtSignal()
# Signals that all polar frames are loaded.
polars_loaded = pyqtSignal()
# Called before frame_available. This is done in the main thread for every frame, no heavy calculation here.
frame_available_immediate = Event()
# Signal that passes the current frame (cartesian) to all connected functions.
frame_available = pyqtSignal(tuple)
# Signal that passes the current sonar file to all connected functions.
file_opened = pyqtSignal(fh.FSONAR_File)
# Signals that playback has been terminated.
playback_ended = pyqtSignal()
# Signals that the current session has been terminated.
file_closed = pyqtSignal()
def __init__(self, app, main_window):
super().__init__()
self.main_window = main_window
self.thread_pool = QThreadPool()
self.thread_pool.setMaxThreadCount(16)
self.playback_thread = None
self.path = ""
self.sonar = None
self.setTitle()
self.frame_timer = None
self.fps = 30
app.aboutToQuit.connect(self.applicationClosing)
def openFile(self, open_path=None, selected_filter="Sonar Files (*.aris *.ddf)", update_conf=True):
"""
Select .aris file using QFileDialog
"""
open_path = open_path if open_path is not None else fh.getLatestDirectory()
file_path_tuple = QFileDialog.getOpenFileName(self.main_window, "Open File", open_path, selected_filter)
if update_conf:
fh.setLatestDirectory(os.path.dirname(file_path_tuple[0]))
self.loadFile(file_path_tuple[0])
def selectSaveDirectory(self, open_path=None, selected_filter=QFileDialog.ShowDirsOnly, update_conf=True):
"""
Select save directory using QFileDialog
"""
open_path = open_path if open_path is not None else fh.getLatestSaveDirectory()
print(selected_filter)
path = QFileDialog.getExistingDirectory(self.main_window, "Select directory", open_path, selected_filter)
if update_conf:
fh.setLatestSaveDirectory(path)
return path
def selectSaveFile(self, open_path=None, selected_filter="", update_conf=True):
"""
Select a file for saving detections or tracking results using QFileDialog
"""
open_path = open_path if open_path is not None else fh.getLatestSaveDirectory()
file_path_tuple = QFileDialog.getSaveFileName(self.main_window, "Save file", open_path, selected_filter)
if update_conf:
fh.setLatestSaveDirectory(os.path.dirname(file_path_tuple[0]))
return file_path_tuple[0]
def selectLoadFile(self, open_path=None, selected_filter="", update_conf=True):
"""
Select a detection or tracking result file to be loaded using QFileDialog
"""
open_path = open_path if open_path is not None else fh.getLatestSaveDirectory()
file_path_tuple = QFileDialog.getOpenFileName(self.main_window, "Load File", open_path, selected_filter)
if update_conf:
fh.setLatestSaveDirectory(os.path.dirname(file_path_tuple[0]))
return file_path_tuple[0]
def openTestFile(self):
path = fh.getTestFilePath()
if path is not None:
# Override test file length
self.loadFile(path, 1000)
else:
self.openFile()
def loadFile(self, path, overrideLength=-1):
sonar = fh.FOpenSonarFile(path)
if overrideLength > 0:
sonar.frameCount = min(overrideLength, sonar.frameCount)
if self.playback_thread:
#LogObject().print("Stopping existing thread.")
#self.playback_thread.signals.playback_ended_signal.connect(self.setLoadedFile)
self.closeFile()
self.setLoadedFile(sonar)
else:
self.setLoadedFile(sonar)
self.path = path
self.setTitle(path)
LogObject().print(f"Opened file '{path}'")
def setLoadedFile(self, sonar):
self.sonar = sonar
#self.fps = sonar.frameRate
# Initialize new PlaybackThread
self.playback_thread = PlaybackThread(self.path, self.sonar, self.thread_pool)
# Initialize frame forwarding
self.playback_thread.signals.frame_available_signal.connect(self.frame_available_f)
# Initialize other signals
self.playback_thread.signals.polars_loaded_signal.connect(self.polars_loaded)
self.playback_thread.signals.playback_ended_signal.connect(self.stop)
self.playback_thread.signals.mapping_done_signal.connect(self.mapping_done)
self.thread_pool.start(self.playback_thread)
# Start
self.file_opened.emit(self.sonar)
self.startFrameTimer()
def checkLoadedFile(self, path, secondary_path="", override_open=True):
"""
Checks if file with matching base name is already open. If not,
tries to open file at path, then at secondary_path and if neither exists,
opens a file dialog for selecting the correct .aris file.
Returns True, if file is already open, otherwise False.
"""
if os.path.basename(self.path) == os.path.basename(path):
return True
if override_open:
if os.path.exists(path):
self.loadFile(path)
return False
elif secondary_path != "" and os.path.exists(secondary_path):
self.loadFile(secondary_path)
return False
else:
self.openFile()
return False
def frame_available_f(self, value):
"""
Forwards signal form PlaybackThread to the two signals below.
"""
#self.frame_available_early.emit(value)
self.frame_available_immediate(value)
self.frame_available.emit(value)
def closeFile(self):
self.stopAll()
if self.playback_thread is not None:
self.playback_thread.clear()
del self.playback_thread
self.playback_thread = None
self.sonar = None
LogObject().print(f"Closed file '{self.path}'")
self.path = ""
self.setTitle()
self.file_closed.emit()
#self.polar_transform = None
def getFileName(self, extension=True):
if self.path == "":
return ""
basename = os.path.basename(self.path)
if extension:
return basename
else:
return basename.split('.')[0]
def setTitle(self, path=""):
if self.main_window is None:
return
if path == "":
self.main_window.setWindowTitle("FishTracker")
else:
self.main_window.setWindowTitle(path)
def runInThread(self, f):
"""
Run threads in thread_pool.
"""
thread = Worker(f)
self.thread_pool.start(thread)
def play(self):
"""
Enables frame playback.
"""
if self.playback_thread and self.playback_thread.polar_transform:
LogObject().print("Start")
#print("F:", sys.getrefcount(self.playback_thread))
self.playback_thread.is_playing = True
self.showNextImage()
def startFrameTimer(self):
"""
Used to start frame_timer, the main pipeline for displaying frames.
"""
if self.frame_timer is None:
self.frame_timer = QTimer(self)
self.frame_timer.timeout.connect(self.displayFrame)
self.frame_timer.start(1000.0 / self.fps)
def displayFrame(self):
"""
Reroutes the displayFrame function for frame_timer.
Signal progression might stop abruptly otherwise.
"""
if self.playback_thread:
self.playback_thread.displayFrame()
def refreshFrame(self):
"""
Used for one time refreshing only.
"""
if self.playback_thread:
self.playback_thread.last_displayed_ind = -1
self.playback_thread.displayFrame()
def togglePlay(self):
"""
UI function that toggles playback.
"""
if self.playback_thread:
if self.playback_thread.is_playing:
self.stop()
else:
self.play()
def showNextImage(self):
"""
Shows next frame without entering play mode.
"""
if self.playback_thread:
ind = self.playback_thread.last_displayed_ind + 1
if ind >= self.sonar.frameCount:
ind = 0
self.setFrameInd(ind)
def showPreviousImage(self):
"""
Shows previous frame without entering play mode.
"""
if self.playback_thread:
ind = self.playback_thread.display_ind - 1
if ind < 0:
ind = self.sonar.frameCount - 1
self.setFrameInd(ind)
def getFrameInd(self):
"""
Returns the index of the current frame being displayed.
"""
if self.playback_thread:
return self.playback_thread.display_ind
else:
return 0
def setFrameInd(self, ind):
"""
Sets the index of the frame that is displayed next.
"""
if self.playback_thread:
frame_ind = max(0, min(ind, self.sonar.frameCount - 1))
self.playback_thread.display_ind = frame_ind
self.playback_thread.next_to_process_ind = frame_ind
def getPolarBuffer(self):
if self.playback_thread:
return self.playback_thread.buffer
else:
return None
def stop(self):
LogObject().print2("Stop")
if self.playback_thread:
self.playback_thread.is_playing = False
self.playback_thread.display_ind = self.playback_thread.last_displayed_ind
self.playback_ended.emit()
def stopAll(self):
self.stop()
if self.frame_timer is not None:
self.frame_timer.timeout.disconnect(self.displayFrame)
self.frame_timer.stop()
self.frame_timer = None
def getFrameNumberText(self):
if self.playback_thread:
return "Frame: {}/{}".format(self.playback_thread.display_ind+1, self.sonar.frameCount)
else:
return "No File Loaded"
def getRadiusLimits(self):
return self.playback_thread.polar_transform.radius_limits
def getBeamDistance(self, x, y, invert=True):
"""
Transforms cartesian coordinates to polar coordinates in metric units,
using the current PolarTransform.
Note: Use isMappingDone to check if this function can be used.
Returns: (distance, angle)
"""
return self.playback_thread.polar_transform.cart2polMetric(y, x, invert)
def isPlaying(self):
return self.playback_thread is not None and self.playback_thread.is_playing
def setDistanceCompensation(self, value):
pass
def getRelativeIndex(self):
if self.playback_thread:
return float(self.playback_thread.display_ind) / self.sonar.frameCount
else:
return 0
def setRelativeIndex(self, value):
if self.sonar:
self.setFrameInd(int(value * self.sonar.frameCount))
def applicationClosing(self):
LogObject().print2("Closing PlaybackManager . . .")
self.stopAll()
time.sleep(1)
def getFrame(self, i):
"""
Non-threaded option to get cartesinan frames.
"""
polar = self.playback_thread.buffer[i]
if polar is None:
polar = self.sonar.getPolarFrame(i)
self.playback_thread.buffer[i] = polar
return self.playback_thread.polar_transform.remap(polar)
def getFrameCount(self):
if self.sonar:
return self.sonar.frameCount
else:
return 0
def getRecordFrameRate(self):
"""
Return frame rate of the recording (ARIS file).
Note that this might differ from the playback frame rate.
"""
if self.sonar:
return self.sonar.frameRate
else:
return None
def getImageShape(self):
"""
Returns (width, height) of the cartesian image in pixels.
"""
if self.playback_thread and self.playback_thread.polar_transform:
shape = self.playback_thread.polar_transform.cart_shape
return shape[1], shape[0]
else:
return None
def getPixelsPerMeter(self):
"""
Return the conversion rate from world (meters) to image (pixels)
"""
if self.playback_thread and self.playback_thread.polar_transform:
return self.playback_thread.polar_transform.pixels_per_meter
else:
return None
def pausePolarLoading(self, value):
if self.playback_thread is not None:
self.playback_thread.pause_polar_loading = value
if not self.isPolarsDone():
if value:
LogObject().print2("Polar loading paused.")
else:
LogObject().print2("Polar loading continued.")
def isMappingDone(self):
return self.playback_thread is not None and self.playback_thread.polar_transform is not None
def isPolarsDone(self):
return self.playback_thread is not None and self.playback_thread.polars_loaded
class PlaybackSignals(QObject):
"""
PyQt signals used by PlaybackThread
"""
# Signals that playback can be started (cartesian mapping created).
mapping_done_signal = pyqtSignal()
# Signals that all polar frames have been read to memory.
polars_loaded_signal = pyqtSignal()
# Used to pass the current frame.
frame_available_signal = pyqtSignal(tuple)
# Signals that playback has ended.
playback_ended_signal = pyqtSignal()
class PlaybackThread(QRunnable):
"""
A QRunnable class, that is created when a new .aris-file is loaded.
It keeps track of the currently displayed frame and makes sure that new frames
are processed before / when they are needed.
Pausing does not stop this thread, since it is necessary for smoother interaction with UI.
"""
def __init__(self, path, sonar, thread_pool):
super().__init__()
self.signals = PlaybackSignals()
self.is_playing = False
self.path = path
self.thread_pool = thread_pool
self.sonar = sonar
self.buffer = [None] * sonar.frameCount
self.polar_transform = None
self.last_displayed_ind = -1
self.display_ind = 0
self.polars_loaded = False
self.pause_polar_loading = False
self.alive = True
def __del__(self):
#print("Playback thread destroyed")
pass
def run(self):
pt = self.createMapping()
self.mappingDone(pt)
self.loadPolarFrames()
self.polarsDone()
def loadPolarFrames(self):
count = self.sonar.frameCount
ten_perc = 0.1 * count
print_limit = 0
i = 0
while i < count and self.alive:
if self.pause_polar_loading:
time.sleep(0.1)
continue
if i > print_limit:
LogObject().print("Loading:", int(float(print_limit) / count * 100), "%")
print_limit += ten_perc
if self.buffer[i] is None:
value = self.sonar.getPolarFrame(i)
if self.alive:
self.buffer[i] = value
i += 1
def polarsDone(self):
if self.alive:
LogObject().print("Loading: 100 %")
self.polars_loaded = True
self.signals.polars_loaded_signal.emit()
def createMapping(self):
radius_limits = (self.sonar.windowStart, self.sonar.windowStart + self.sonar.windowLength)
height = fh.getSonarHeight()
beam_angle = 2 * self.sonar.firstBeamAngle/180*np.pi
return PolarTransform(self.sonar.DATA_SHAPE, height, radius_limits, beam_angle)
def mappingDone(self, result):
if self.alive:
self.polar_transform = result
self.signals.mapping_done_signal.emit()
self.displayFrame()
def displayFrame(self):
if self.last_displayed_ind != self.display_ind:
try:
polar = self.buffer[self.display_ind]
if polar is not None and self.polar_transform is not None:
frame = self.polar_transform.remap(polar)
self.signals.frame_available_signal.emit((self.display_ind, frame))
self.last_displayed_ind = self.display_ind
if self.is_playing:
self.display_ind += 1
except IndexError as e:
LogObject().print2(e, self.display_ind, "/", len(self.buffer)-1)
self.signals.playback_ended_signal.emit()
def clear(self):
self.alive = False
self.buffer = None
self.polar_transform = None
class WorkerSignals(QObject):
finished = pyqtSignal()
error = pyqtSignal(tuple)
result = pyqtSignal(object)
class Worker(QRunnable):
def __init__(self, fn, *args, **kwargs):
super().__init__()
self.fn = fn
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
@pyqtSlot()
def run(self):
# Retrieve args/kwargs here; and fire processing using them
try:
result = self.fn(*self.args, **self.kwargs)
except:
traceback.print_exc()
exctype, value = sys.exc_info()[:2]
self.signals.error.emit((exctype, value, traceback.format_exc()))
else:
self.signals.result.emit(result) # Return the result of the processing
finally:
self.signals.finished.emit() # Done
class TestFigure(QLabel):
def __init__(self, play_f, reload_f=None):
super().__init__()
self.figurePixmap = None
self.frame_ind = 0
self.delta_time = 1
self.fps = 1
self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
self.prev_shown = 0
self.toggle_play = play_f
self.reload_file = reload_f
self.setFocusPolicy(Qt.StrongFocus)
def displayImage(self, tuple):
if tuple is None:
self.clear()
return
self.frame_ind, image = tuple
LogObject().print("TF Frame:", self.frame_ind)
t = time.time()
self.delta_time = t - self.prev_shown
self.prev_shown = t
self.setUpdatesEnabled(False)
self.clear()
qformat = QImage.Format_Indexed8
if len(image.shape)==3:
if image.shape[2]==4:
qformat = QImage.Format_RGBA8888
else:
qformat = QImage.Format_RGB888
img = cv2.resize(image, (self.size().width(), self.size().height()))
img = QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat).rgbSwapped()
figurePixmap = QPixmap.fromImage(img)
self.setPixmap(figurePixmap.scaled(self.size(), Qt.KeepAspectRatio))
self.setAlignment(Qt.AlignCenter)
self.setUpdatesEnabled(True)
def resizeEvent(self, event):
if isinstance(self.figurePixmap, QPixmap):
self.setPixmap(self.figurePixmap.scaled(self.size(), Qt.KeepAspectRatio))
def paintEvent(self, event):
super().paintEvent(event)
painter = QPainter(self)
painter.setPen(Qt.red)
point = QPoint(10,20)
painter.drawText(point, str(self.frame_ind))
if self.delta_time != 0:
self.fps = 0.3 * (1.0 / self.delta_time) + 0.7 * self.fps
point = QPoint(10,50)
painter.drawText(point, "{:.1f}".format(self.fps))
def keyPressEvent(self, event):
super().keyPressEvent(event)
if event.key() == Qt.Key_Space:
self.toggle_play()
elif event.key() == Qt.Key_T and self.reload_file is not None:
self.reload_file()
event.accept()
if __name__ == "__main__":
def playback_test():
def loadFile():
playback_manager.openTestFile()
playback_manager.playback_thread.signals.mapping_done_signal.connect(lambda: playback_manager.play())
app = QApplication(sys.argv)
main_window = QMainWindow()
playback_manager = PlaybackManager(app, main_window)
figure = TestFigure(playback_manager.togglePlay, loadFile)
playback_manager.frame_available.connect(figure.displayImage)
main_window.setCentralWidget(figure)
loadFile()
main_window.show()
sys.exit(app.exec_())
def benchmark_loading():
app = QApplication(sys.argv)
main_window = QMainWindow()
playback_manager = PlaybackManager(app, main_window)
path = fh.getTestFilePath()
sonar = fh.FOpenSonarFile(path)
sonar.frameCount = min(1000, sonar.frameCount)
playback_thread = PlaybackThread(path, sonar, playback_manager.thread_pool)
playback_thread.loadPolarFrames()
playback_test()
#benchmark_loading()