/
main.py
441 lines (362 loc) · 17 KB
/
main.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, six, math
if six.PY2:
reload(sys)
sys.setdefaultencoding('UTF8')
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
currentDirPath = sys._MEIPASS
if os.name == 'nt':
import win32api
win32api.SetDllDirectory(sys._MEIPASS)
elif __file__:
currentDirPath = os.getcwd()
# currentDirPath = os.path.abspath(os.path.dirname(__file__) )
sampleDataPath = os.path.join(currentDirPath,"data")
userDir = os.path.expanduser('~')
from queue import Queue
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsItem, QGraphicsItemGroup, QGraphicsPixmapItem, QGraphicsEllipseItem, QFrame, QFileDialog, QPushButton
from PyQt5.QtGui import QPixmap, QImage, QPainter, QIcon, QCursor
from PyQt5.QtCore import QPoint, QPointF, QRectF, QEvent, Qt
import cv2
import numpy as np
import pandas as pd
import icon
from lib.python import misc
from lib.python.ui.ui_main_window_base import Ui_MainWindowBase
# from lib.python.ui.tracking_path import TrackingPath
from lib.python.ui.tracking_path_group import TrackingPathGroup
from lib.python.ui.hand_input_system import HandInputSystem
# Log file setting.
# import logging
# logging.basicConfig(filename='MainWindow.log', level=logging.DEBUG)
# Log output setting.
# If handler = StreamHandler(), log will output into StandardOutput.
from logging import getLogger, NullHandler, StreamHandler, DEBUG
logger = getLogger(__name__)
handler = NullHandler() if True else StreamHandler()
handler.setLevel(DEBUG)
logger.setLevel(DEBUG)
logger.addHandler(handler)
class Ui_MainWindow(QtWidgets.QMainWindow, Ui_MainWindowBase):
def __init__(self):
super(Ui_MainWindow, self).__init__()
self.setupUi(self)
self.videoPlaybackInit()
self.imgInit()
self.menuInit()
self.df = None
self.trackingPathGroup = None
self.drawingFlag = False
self.handInputSystem = None
self.handInputSystem = HandInputSystem()
self.handInputSystem.setRect(self.inputScene.sceneRect())
self.inputScene.addItem(self.handInputSystem)
self.handInputSystem.addNewDataFrame()
self.currentFrameNo = 0
self.colors = []
self.circleCheckBox.stateChanged.connect(self.polyLineCheckBoxStateChanged)
self.lineCheckBox.stateChanged.connect(self.polyLineCheckBoxStateChanged)
self.overlayCheckBox.stateChanged.connect(self.overlayCheckBoxStateChanged)
self.radiusSpinBox.valueChanged.connect(self.radiusSpinBoxValueChanged)
self.frameNoSpinBox.valueChanged.connect(self.frameNoSpinBoxValueChanged)
self.groupBox_2.hide()
self.inputGraphicsView.viewport().setCursor(QtCore.Qt.ArrowCursor)
#
self.optionViewButton.pressed.connect(self.optionViewButtonPressed)
self.zoomedGraphicsView.hide()
self.dataFrameWidget.dataFrameChanged.connect(self.dataFrameChanged)
self.dataFrameWidget.hide()
self.handInputSystem.setColor(self.dataFrameWidget.getColor())
#self.processDropedFile("/Users/ymnk/temp/Dast/2016/01/hoge.avi")
#self.processDropedFile("./a.csv")
def dataFrameChanged(self,addedFrameFlag,editingNo,color):
if addedFrameFlag:
self.handInputSystem.addNewDataFrame()
self.handInputSystem.setEditingNo(editingNo)
self.handInputSystem.setColor(color)
print(addedFrameFlag,color,editingNo)
def optionViewButtonPressed(self):
if self.groupBox_2.isVisible():
self.optionViewButton.setText("<")
self.groupBox_2.hide()
else:
self.optionViewButton.setText(">")
self.groupBox_2.show()
def overlayCheckBoxStateChanged(self, s):
if self.overlayCheckBox.isChecked():
self.frameBufferItemGroup.show()
else:
self.frameBufferItemGroup.hide()
self.updateInputGraphicsView()
def polyLineCheckBoxStateChanged(self, s):
overlayFrameNo = self.frameNoSpinBox.value()
min_value = max(self.currentFrameNo-overlayFrameNo,0)
current_pos = self.currentFrameNo - min_value
if self.handInputSystem is not None:
self.handInputSystem.setDrawItem(current_pos, self.circleCheckBox.isChecked())
self.handInputSystem.setDrawLine(self.lineCheckBox.isChecked())
self.updateInputGraphicsView()
def radiusSpinBoxValueChanged(self, value):
if self.handInputSystem is not None:
self.handInputSystem.setRadius(self.radiusSpinBox.value())
self.updateInputGraphicsView()
def frameNoSpinBoxValueChanged(self, value):
if self.handInputSystem is not None:
self.handInputSystem.setOverlayFrameNo(self.frameNoSpinBox.value())
self.updateInputGraphicsView()
def dragEnterEvent(self,event):
event.acceptProposedAction()
def dropEvent(self,event):
# event.setDropAction(QtCore.Qt.MoveAction)
mime = event.mimeData()
if mime.hasUrls():
urls = mime.urls()
if len(urls) > 0:
self.processDropedFile(urls[0].toLocalFile())
event.acceptProposedAction()
def processDropedFile(self,filePath):
root,ext = os.path.splitext(filePath)
if ext == ".filter":
# Read Filter
self.openFilterFile(filePath=filePath)
return
elif ext == ".csv":
self.openCSVFile(filePath=filePath)
elif self.openImageFile(filePath=filePath):
return
elif self.openVideoFile(filePath=filePath):
return
def videoPlaybackInit(self):
self.videoPlaybackWidget.hide()
self.videoPlaybackWidget.frameChanged.connect(self.setFrame, Qt.QueuedConnection)
def setFrame(self, frame, frameNo):
if frame is not None:
self.cv_img = frame
self.currentFrameNo = frameNo
self.updateInputGraphicsView()
if self.videoInitialFlag == True:
self.graphicsViewResized()
self.videoInitialFlag = False
self.evaluate()
def imgInit(self):
self.cv_img = cv2.imread(os.path.join(sampleDataPath,"color_filter_test.png"))
self.frameBuffer = Queue()
self.frameBufferItemGroup = QGraphicsItemGroup()
self.frameBufferItemGroup.hide()
self.inputPixmapRenderScene = QGraphicsScene()
self.inputPixmapRenderScene.addItem(self.frameBufferItemGroup)
self.inputScene = QGraphicsScene()
self.inputGraphicsView.setScene(self.inputScene)
self.inputGraphicsView.resizeEvent = self.graphicsViewResized
# self.inputScene.addItem(self.frameBufferItemGroup)
qimg = misc.cvMatToQImage(self.cv_img)
self.inputPixmap = QPixmap.fromImage(qimg)
self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
self.inputScene.addItem(self.inputPixmapItem)
self.inputGraphicsView.mousePressEvent = self.inputGraphicsViewMousePressEvent
self.inputGraphicsView.mouseMoveEvent = self.inputGraphicsViewMouseMoveEvent
self.inputGraphicsView.mouseReleaseEvent = self.inputGraphicsViewMouseReleaseEvent
self.inputGraphicsView.keyPressEvent = self.inputGraphicsViewKeyPressEvent
self.inputGraphicsView.keyReleaseEvent = self.inputGraphicsViewKeyReleaseEvent
self.inputGraphicsView.wheelEvent = self.inputGraphicsViewwheelEvent
#self.inputGraphicsView.focusInEvent = self.inputGraphicsViewfocusInEvent
self.inputGraphicsView.viewport().installEventFilter(self)
self.inputGraphicsView.setMouseTracking(True)
self.overlayScene = QGraphicsScene()
self.inputGraphicsView.setOverlayScene(self.overlayScene)
def inputGraphicsViewfocusInEvent(self,event):
#
QGraphicsView.focusInEvent(self.inputGraphicsView, event)
def inputGraphicsViewMousePressEvent(self, event):
if event.modifiers() == QtCore.Qt.ShiftModifier:
# Comment out to permit the view for sending the event to the child scene.
QGraphicsView.mousePressEvent(self.inputGraphicsView, event)
else:
self.drawingFlag = True
if not self.videoPlaybackWidget.isPlaying():
self.videoPlaybackWidget.playButtonClicked()
def inputGraphicsViewMouseMoveEvent(self, event):
if event.modifiers() == QtCore.Qt.ShiftModifier:
# Comment out to permit the view for sending the event to the child scene.
QGraphicsView.mouseMoveEvent(self.inputGraphicsView, event)
elif self.drawingFlag == True:
pass
#self.videoPlaybackWidget.moveNextButtonClicked()
#self.handInputSystem.inputMouseMoveEvent(mousePosition,self.currentFrameNo)
#print(self.currentFrameNo)
#self.positionStack.append(mousePosition)
#self.handInputSystem.inputMouseMoveEvent(mousePosition)
def inputGraphicsViewMouseReleaseEvent(self, event):
if self.drawingFlag == True:
self.drawingFlag = False
self.videoPlaybackWidget.playButtonClicked()
self.handInputSystem.inputMouseReleaseEvent()
self.handInputSystem.setPoints()
# Comment out to permit the view for sending the event to the child scene.
QGraphicsView.mouseReleaseEvent(self.inputGraphicsView, event)
self.inputGraphicsView.viewport().setCursor(QtCore.Qt.ArrowCursor)
def inputGraphicsViewKeyPressEvent(self,event):
mousePosition = QCursor().pos()
mousePosition = self.inputGraphicsView.mapFromGlobal(mousePosition)
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
if key == QtCore.Qt.Key_Space:
self.videoPlaybackWidget.playButtonClicked()
elif key == QtCore.Qt.Key_A:
self.videoPlaybackWidget.movePrevButtonClicked()
elif key == QtCore.Qt.Key_D:
self.videoPlaybackWidget.moveNextButtonClicked()
elif key == QtCore.Qt.Key_Down:
self.inputGraphicsViewScaleDown()
elif key == QtCore.Qt.Key_Up:
self.inputGraphicsViewScaleUp()
pass
elif key == QtCore.Qt.Key_R:
self.graphicsViewResized()
elif key == QtCore.Qt.Key_P:
pass
#self.handInputSystem.nextDataFrame()
elif key == QtCore.Qt.Key_O:
pass
#self.handInputSystem.previousDataFrame()
elif key == QtCore.Qt.Key_J:
frameNo = self.handInputSystem.getLastInputedFrameIndex()
self.videoPlaybackWidget.moveToFrame(frameNo)
elif key == QtCore.Qt.Key_S:
self.handInputSystem.saveCSV("./a.csv")
QGraphicsView.keyPressEvent(self.inputGraphicsView, event)
def inputGraphicsViewKeyReleaseEvent(self,event):
QGraphicsView.keyReleaseEvent(self.inputGraphicsView, event)
def inputGraphicsViewwheelEvent(self,event):
scaleFactor = 1.15
if event.delta() > 0:
# Zoom in
self.inputGraphicsView.scale(scaleFactor, scaleFactor)
else:
# Zooming out
self.inputGraphicsView.scale(1.0 / scaleFactor, 1.0 / scaleFactor)
QGraphicsView.wheelEvent(self.inputGraphicsView, event)
def inputGraphicsViewScaleDown(self):
scaleFactor = 1.15
self.inputGraphicsView.scale(1.0 / scaleFactor, 1.0 / scaleFactor)
def inputGraphicsViewScaleUp(self):
scaleFactor = 1.15
self.inputGraphicsView.scale(scaleFactor, scaleFactor)
def menuInit(self):
self.actionSaveCSVFile.triggered.connect(self.saveCSVFile)
self.actionOpenCSVFile.triggered.connect(self.openCSVFile)
def openVideoFile(self, activated=False, filePath = None):
if filePath is None:
filePath, _ = QFileDialog.getOpenFileName(None, 'Open Video File', userDir)
if len(filePath) is not 0:
self.filePath = filePath
ret = self.videoPlaybackWidget.openVideo(filePath)
if ret == False:
return False
self.videoInitialFlag = True
self.videoPlaybackWidget.show()
self.dataFrameWidget.show()
# self.evaluate()
return True
else:
return False
def openImageFile(self, activated=False, filePath = None):
if filePath == None:
filePath, _ = QFileDialog.getOpenFileName(None, 'Open Image File', userDir)
if len(filePath) is not 0:
self.filePath = filePath
img = cv2.imread(filePath)
if img is None:
return False
self.cv_img = img
self.videoPlaybackWidget.hide()
self.updateInputGraphicsView()
self.evaluate()
return True
else:
return False
def openCSVFile(self, activated=False, filePath=None):
if filePath is None:
filePath, _ = QFileDialog.getOpenFileName(None, 'Open CSV File', userDir, 'CSV files (*.csv)')
if len(filePath) is not 0:
self.df = pd.read_csv(filePath, index_col=0)
if self.handInputSystem is not None:
self.inputScene.removeItem(self.handInputSystem)
self.handInputSystem = HandInputSystem()
self.handInputSystem.setRect(self.inputScene.sceneRect())
self.inputScene.addItem(self.handInputSystem)
self.handInputSystem.setDataFrame(self.df)
self.handInputSystem.setPoints()
self.dataFrameWidget.clear()
self.dataFrameWidget.dataFrameNo = self.handInputSystem.dataFrameNo
self.dataFrameWidget.editingNo = 0
for item in range(self.handInputSystem.dataFrameNo+1):
color = self.handInputSystem.itemList[item].getColor()
print(item,color)
self.dataFrameWidget.colorList.append(color)
self.dataFrameWidget.setUniqueIDLabel()
self.evaluate()
def saveCSVFile(self, activated=False, filePath = None):
#if self.df is not None:
if self.handInputSystem.isDataFrame():
filePath, _ = QFileDialog.getSaveFileName(None, 'Save CSV File', userDir, "CSV files (*.csv)")
if len(filePath) is not 0:
logger.debug("Saving CSV file: {0}".format(filePath))
self.handInputSystem.saveCSV(filePath)
def updateInputGraphicsView(self):
# print("update")
# self.inputScene.clear()
self.inputScene.removeItem(self.inputPixmapItem)
qimg = misc.cvMatToQImage(self.cv_img)
self.inputPixmap = QPixmap.fromImage(qimg)
p = QPainter(self.inputPixmap)
sourceRect = self.inputPixmapRenderScene.sceneRect()
self.inputPixmapRenderScene.render(p, QRectF(sourceRect), QRectF(sourceRect), QtCore.Qt.IgnoreAspectRatio)
self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap)
rect = QtCore.QRectF(self.inputPixmap.rect())
self.inputScene.setSceneRect(rect)
self.inputScene.addItem(self.inputPixmapItem)
self.inputGraphicsView.viewport().update()
# self.graphicsViewResized()
def eventFilter(self, obj, event):
if obj is self.inputGraphicsView.viewport() and event.type()==QEvent.Wheel:
return True
else:
return False
def graphicsViewResized(self, event=None):
# print("resize")
# print(self.inputScene)
self.inputGraphicsView.fitInView(QtCore.QRectF(self.inputPixmap.rect()), QtCore.Qt.KeepAspectRatio)
def evaluate(self):
if not self.videoPlaybackWidget.isOpened():
return
qimg = misc.cvMatToQImage(self.cv_img)
pixmapItem = QGraphicsPixmapItem(QPixmap.fromImage(qimg))
pixmapItem.setOpacity(0.2)
self.frameBuffer.put(pixmapItem)
self.frameBufferItemGroup.addToGroup(pixmapItem)
if self.frameBuffer.qsize() > 10:
item = self.frameBuffer.get()
self.frameBufferItemGroup.removeFromGroup(item)
"""
if self.trackingPathGroup is not None:
self.trackingPathGroup.setPoints(self.currentFrameNo)
"""
if self.handInputSystem is not None:
self.handInputSystem.setPoints(self.currentFrameNo)
if self.drawingFlag is True:
mousePosition = QCursor().pos()
mousePosition = self.inputGraphicsView.mapFromGlobal(mousePosition)
mousePosition = self.inputGraphicsView.mapToScene(mousePosition)
pos = [mousePosition.x(),mousePosition.y()]
self.handInputSystem.appendPosition(pos,self.currentFrameNo)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = Ui_MainWindow()
MainWindow.setWindowIcon(QIcon(':/icon/icon.ico'))
MainWindow.setWindowTitle('UMATracker-commando')
MainWindow.show()
sys.exit(app.exec_())