-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.py
More file actions
1538 lines (1273 loc) · 58.9 KB
/
interface.py
File metadata and controls
1538 lines (1273 loc) · 58.9 KB
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
from cProfile import label
import sys,os
from datetime import datetime
import time
from functools import partial
import time
from matplotlib import widgets
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import qimage2ndarray
from PyQt5 import uic
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QStringListModel,Qt
import kornia
from options.test_options import TestOptions
from infer import infer
import resource_rc
import argparse
from collections import deque
def flood_fill(img, out, x_0, y_0, color, threshold=0):
h,w,c = img.shape
def in_boundary(x,y,h,w):
if x >= 0 and x < w and y >= 0 and y < h:
return True
else:
return False
source_value = img[y_0,x_0].copy()
target_value = np.array([color.red(),color.green(),color.blue(),255])
visited = set()
visited.add((x_0,y_0))
candidate = deque([(x_0,y_0)])
out[y_0,x_0] = target_value
while len(candidate) > 0:
x,y = candidate.popleft()
for (xx, yy) in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if not (xx,yy) in visited and in_boundary(xx,yy,h,w):
visited.add((xx,yy))
if (abs(img[yy,xx].astype(np.int16)-source_value.astype(np.int16)) <= threshold).all():
out[yy,xx] = target_value
candidate.append((xx,yy))
return out
class Form(QMainWindow):
displaySize = 300
pickerActive = False
'''
4 MODE for Inference
1) Depth alone
2) Depth + Segmentation Guide
3) Depth + Segmentation Guide (pure SPADE)
4) Refinement
'''
fileName = None
img = None
disp = None
modeType = {"Depth":"depth", "Semantic Guided Depth":"segDepth", "Segmap":"segMap", "Refine":"refine"}
mode = "depth"
model = None
labelModel = None
labelImage = None
params = {}
figureWidget = None
max_history = 3
prev_guides=deque(maxlen=max_history)
userstudyTask = None
def __init__(self):
super(Form, self).__init__()
self.opt = TestOptions().parse(); self.opt.lambda_feat = 1.0; self.opt.lambda_seg = 1.0
self.dirName = os.path.dirname(__file__)
self.ui = uic.loadUi("./mainwindow_aligned2.ui", self)
self.ui.setWindowTitle("Interactive Single Image Depth Extractor")
#connect ui objects with functions
self.ui.loadButton.clicked.connect(lambda: self.loadImage('image'))
self.ui.processButton.clicked.connect(self.processImage)
self.ui.strokeLoadBtn.clicked.connect(lambda: self.loadImage('stroke'))
self.ui.saveButton.clicked.connect(lambda: self.saveImage('depth'))
self.ui.plotButton.clicked.connect(self.plotImage)
self.ui.strokeSaveBtn.clicked.connect(lambda: self.saveImage("stroke"))
self.ui.valueSlider.valueChanged.connect(self.changeValue)
self.ui.sizeSlider.valueChanged.connect(self.changeSize)
self.ui.clearButton.clicked.connect(self.eraseAll)
self.ui.strokeButton.clicked.connect(self.activateStroke)
self.ui.eraseButton.clicked.connect(self.activateEraser)
self.ui.fillButton.clicked.connect(self.activateFill)
self.ui.ckptCB.currentTextChanged.connect(self.refreshModel)
self.ui.optCB.currentTextChanged.connect(self.updateOptionLE)
self.ui.optLE.returnPressed.connect(self.updateOption)
self.ui.searchLE.returnPressed.connect(self.updateOptionCB)
self.ui.showStrokeCB.stateChanged.connect(self.toggleGuideImage)
self.ui.showDepthCB.stateChanged.connect(self.toggleDepthImage)
self.ui.showColormapCB.stateChanged.connect(self.toggleColormap)
self.ui.showOverlayCB.stateChanged.connect(self.toggleOverlay)
self.ui.valueBox.mouseReleaseEvent = partial(self.activatePicker)
# Key Shortcuts
self.undo_SC = QShortcut(QtGui.QKeySequence('Ctrl+Z'), self)
self.undo_SC.activated.connect(self.undoStroke)
# Size options
self.opt.infer_size = 384
self.opt.fit_max = False
self.last_x, self.last_y = None, None
self.pen_color = QtGui.QColor('#000000')
self.pen_size = int(self.ui.sizeLabel.text())
self.initialize()
self.ui.show()
self.params['option'] = self.opt
self.processTask = TaskThread(params=self.params)
self.processTask.status = 'launch'
self.processTask.timeSignal.connect(self.initProgress)
self.processTask.start()
# self.processTask.notifyProgress.connect(self.onProgress)
def initialize(self):
self.msg = QMessageBox()
self.ui.progressBar.setValue(0)
self.ui.statusBar.showMessage("Status: Load Image for Depth Extraction")
self.ui.valueSlider.setRange(0,100)
self.ui.valueSlider.setSingleStep(10)
self.ui.sizeSlider.setRange(2,20)
self.ui.sizeSlider.setSingleStep(1)
self.currentColor = self.ui.valueSlider.value() / 100.0 * 255
length = self.ui.valueBox.width()
# self.colorPixmap = QtGui.QPixmap(length,length)
# self.colorPixmap.fill(QtGui.QColor(self.currentColor,self.currentColor,self.currentColor))
# self.ui.valueBox.setPixmap(self.colorPixmap)
self.ui.valueBox.setAlignment(Qt.AlignCenter | Qt.AlignCenter)
self.brushPixmap = QtGui.QPixmap(self.pen_size,self.pen_size)
currentColor = int(self.currentColor*255)
self.brushPixmap.fill(QtGui.QColor(currentColor,currentColor,currentColor))
self.ui.valueBox.setPixmap(self.brushPixmap)
#initialization for graphics
self.ui.imageDisplay.setStyleSheet('QLabel {background-color: #2b2b2b;}')
self.ui.imageBox.setStyleSheet('QGroupBox {background-color: #2b2b2b;}')
self.ui.depthDisplay.setStyleSheet('QLabel {background-color: #2b2b2b;}')
self.ui.depthBox.setStyleSheet('QGroupBox {background-color: #2b2b2b;}')
self.displaySize = (self.ui.imageDisplay.size().width(),
self.ui.imageDisplay.size().height())
self.displayBoxSize = (self.ui.imageBox.size().width(),
self.ui.imageBox.size().height())
self.updateMode()
self.initializeOption()
#initialize segmentation modules
self.label_classes = np.load("label.npy", allow_pickle=True).item()
self.label_classes['unknown'] = 255
def resizeEvent(self, event):
self.displayBoxSize = (self.ui.imageBox.size().width(),
self.ui.imageBox.size().height())
self.displaySize = (self.displayBoxSize[0]-10, self.displayBoxSize[1]-10)
w, h = self.displaySize
self.ui.imageDisplay.resize(w,h)
self.ui.depthDisplay.resize(w,h)
self.resizeImages()
QtWidgets.QMainWindow.resizeEvent(self, event)
def resizeImages(self):
def resizeByScale(w,h,ww,hh,img):
ratio1, ratio2 = w/h, ww/hh
if ratio1 > ratio2:
return img.scaledToHeight(h)
else:
return img.scaledToWidth(w)
if self.fileName is None:
return
w, h = self.displaySize
hh, ww = self.img.shape[0], self.img.shape[1]
if self.fileName is not None:
img = QtGui.QImage(self.fileName)
img2 = resizeByScale(w,h,ww,hh,img)
self.image = QtGui.QPixmap.fromImage(img2)
if self.guide is not None:
self.guide = resizeByScale(w,h,ww,hh,self.guide)
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
else:
self.ui.imageDisplay.setPixmap(self.image)
if self.disp is not None:
viewDisp = self.ui.depthDisplay.pixmap()
viewDisp2 = resizeByScale(w,h,ww,hh,viewDisp)
self.ui.depthDisplay.setPixmap(viewDisp2)
def initializeOption(self):
import inspect
attributes = inspect.getmembers(self.opt, lambda a:not(inspect.isroutine(a)))
self.optionDict = {}
for a in attributes:
if not (a[0].startswith('__') and a[0].endswith('__')):
self.optionDict[a[0]] = a[1]
optionList = [str(key) for key in self.optionDict.keys()]
self.ui.optCB.addItems(optionList)
self.ui.optCB.setCurrentText("input_ch")
self.ui.optLE.setText(str(self.optionDict[self.ui.optCB.currentText()]))
self.ui.optViewer.setText(str(self.optionDict[self.ui.optCB.currentText()]))
self.ui.searchLE.setCompleter(QCompleter(optionList))
def updateOptionCB(self):
optionText = self.ui.searchLE.text()
if optionText in self.optionDict:
self.ui.optCB.setCurrentText(optionText)
def updateOptionLE(self):
self.ui.optLE.setText(str(self.optionDict[self.ui.optCB.currentText()]))
self.ui.optViewer.setText(str(self.optionDict[self.ui.optCB.currentText()]))
def updateOption(self):
key = self.ui.optCB.currentText()
value = self.ui.optLE.text()
prevValue = self.optionDict[key]
def is_float(element):
try:
float(element)
return True
except ValueError:
return False
if is_float(prevValue) and not isinstance(prevValue, bool):
if not is_float(value):
self.popMessage("Option Input", "Wrong input! Input must be ({})".format(type(prevValue)))
self.optLE.setText(str(prevValue))
else:
if isinstance(prevValue, int):
self.optionDict[key] = int(value)
elif isinstance(prevValue, float):
self.optionDict[key] = float(value)
else:
if value.isnumeric():
self.popMessage("Option Input", "Wrong input")
self.optLE.setText(str(prevValue))
else:
if isinstance(prevValue, bool):
if value in ["True", "False"]:
self.optionDict[key] = True if value == "True" else False
else:
self.popMessage("Option Input", "Wrong input! Input must be ({})".format(type(prevValue)))
self.optLE.setText(str(prevValue))
else:
self.optionDict[key] = value
if self.ui.optViewer.text() != self.optionDict[key]:
self.ui.optViewer.setText(str(value))
'''Update opt'''
self.opt.__dict__.update(self.optionDict)
def updateIndex(self):
key = self.ui.indexCB.currentText()
value = self.label_classes[key]
self.ui.indexLE.setText(str(value))
def updateLabel(self):
if self.labelImage is None:
if self.img is None:
self.popMessage("Update Label", "No image to refer to!")
else:
self.labelImage = np.ones((self.img.shape[0],self.img.shape[1])).astype(np.uint8)
labelImage = np.asarray(self.labelImage)
mask = cv2.resize(self.mask,(labelImage.shape[1],labelImage.shape[0]),interpolation=cv2.INTER_NEAREST)
print(np.count_nonzero(mask))
labelImage[mask!=0] = int(self.ui.indexLE.text())
self.labelImage = Image.fromarray(labelImage)
self.ui.showLabelCB.setChecked(True)
def updateDepth(self):
if self.disp is None:
self.popMessage("Update Depth", "No depth map!")
return
mask = cv2.resize(self.mask,(self.disp.shape[1],self.disp.shape[0]),interpolation=cv2.INTER_NEAREST)
self.disp[mask!=0] = self.ui.valueSlider.value() / 100.0 * 10
self.toggleColormap()
def krPath_imread(self, filePath) :
stream = open(filePath.encode("utf-8") , "rb")
bytes = bytearray(stream.read())
numpyArray = np.asarray(bytes, dtype=np.uint8)
return cv2.imdecode(numpyArray , cv2.IMREAD_UNCHANGED)
def loadImage(self, imageType):
if self.fileName is None:
fileName = QFileDialog.getOpenFileName(self, 'Open file', self.dirName + '../InferenceData/')[0]
else:
dirName, baseName = os.path.split(self.fileName)
fileName = QFileDialog.getOpenFileName(self, 'Open file', dirName)[0]
# fileName = QFileDialog.getOpenFileName(self, 'Open file', "R:/DCM_cropped/images_withGT")[0]
if imageType == "image":
if '.png' not in fileName and '.jpg' not in fileName: return
self.ui.lineEdit.setText(fileName)
elif imageType == "stroke":
if '.png' not in fileName: return
self.ui.statusBar.showMessage("Status: {} Loaded".format(imageType.capitalize()))
if imageType == "image":
self.img = self.krPath_imread(fileName)
img = QtGui.QImage(fileName)
if img.width() > img.height():
img2 = img.scaledToWidth(self.displaySize[0])
else:
img2 = img.scaledToHeight(self.displaySize[1])
# Display image
if imageType == "image":
self.image = QtGui.QPixmap.fromImage(img2)
self.ui.imageDisplay.setPixmap(self.image)
self.fileName = fileName # Save filename for later inference
# Create guide image
self.guide = QtGui.QPixmap(img2.width(), img2.height())
self.guide.fill(QtGui.QColor(0,0,0,0))
# self.prev_guide = self.pixmap2numpy(self.guide)
self.prev_guides = deque(maxlen=self.max_history)
# Autoload label if exists
head, tail = os.path.split(self.fileName)
self.segFilename = glob.glob(os.path.splitext(os.path.join(head,'seg_' + tail))[0]+".*")
self.segFilename = []
print(self.segFilename, len(self.segFilename))
if len(self.segFilename) == 0:
self.segFilename = ''
self.labelImage = Image.fromarray(
np.ones((self.img.shape[0],self.img.shape[1])).astype(np.uint8)*255)
else:
self.segFilename = self.segFilename[0]
self.labelImage = Image.open(self.segFilename)
# Update loaded stroke/guide to the image
elif imageType == "stroke":
self.guide = QtGui.QPixmap.fromImage(img2)
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
# Re-initialize graphics
self.ui.depthDisplay.clear()
self.ui.progressBar.setValue(0)
# Set infered data to None
self.midas_depth = None
def loadLabel(self):
if self.fileName is None:
filename = QFileDialog.getOpenFileName(self, 'Open file', self.dirName + '../InferenceData/')[0]
else:
dirName, baseName = os.path.split(self.fileName)
filename = QFileDialog.getOpenFileName(self, 'Open file', dirName)[0]
self.ui.labelLE.setText(str(filename))
self.segFilename = filename
def processImage(self):
if self.ui.imageDisplay.pixmap() is None:
self.popMessage("Process Image", "No image to process! Please load an image")
return
# check whehter to use stroke or not
if self.ui.noStrokeCB.isChecked():
guide = np.zeros((self.image.height(), self.image.width(), 4),dtype=np.uint8) # H x W x 4
else:
guide = self.pixmap2numpy(self.guide)
if self.mode == 'refine':
guide -= self.prev_guide
self.prev_guide = self.pixmap2numpy(self.guide)
guide_alpha = guide[:,:,-1]
guide_input = guide[:,:,:3]
self.ckpt = self.ui.ckptCB.currentText()
self.params['option'] = self.opt
self.params['label_type'] = "no_label"
self.processTask = TaskThread(self.fileName,
self.segFilename,
guide_input,
guide_alpha,
self.mode,
self.ckpt,
False,
self.params)
self.processTask.load_label_model(self.labelModel)
self.processTask.label = self.labelImage
if not self.model is None:
self.processTask.load_model(self.model)
if not self.midas_depth is None:
self.processTask.midas_depth = self.midas_depth
self.processTask.timeSignal.connect(self.onProgress)
if self.userstudyTask is not None:
self.userstudyTask.pause()
self.processTask.start()
def initProgress(self, position):
if position == 100:
self.processTask.stop()
return
def onProgress(self, position):
if position != -1:
self.ui.progressBar.setValue(position)
else:
disp = self.disp/10*255
self.processTask.saveImage("D:/"+self.ui.usernameLE.text()+".png",disp)
self.ui.statusBar.showMessage("Status: Estimating Depth")
if position == 100:
self.disp = self.processTask.disp
if self.disp is None:
QtWidgets.QMessageBox.information(self, "ERROR", "Load the image")
return
self.processTask.stop()
# self.processTask.resumeTimer()
# self.processTask.start()
self.model = self.processTask.model
self.labelImage = self.processTask.label
if self.midas_depth is None:
self.midas_depth = self.processTask.midas_depth
else:
self.midas_depth = torch.Tensor(self.disp).unsqueeze(0).unsqueeze(0)
''' Resize depth image to orginal size '''
print("Disp shape to image shape ", self.img.shape)
self.disp = cv2.resize(self.disp, (self.img.shape[1], self.img.shape[0]),cv2.INTER_NEAREST)
cv2.imwrite('result.png',self.disp)
''' Resize depth image to viewing display size '''
viewImage = self.ui.imageDisplay.pixmap()
viewDisp = cv2.resize(self.disp, (viewImage.width(),viewImage.height()))
# viewDisp = np.transpose(self.disp, (1,0))
# viewDisp = cv2.resize(viewDisp, (viewImage.width(),viewImage.height())).astype(np.uint8)
viewDisp = ((viewDisp/10.0)*255).astype(np.uint8)
# viewDisp = ((viewDisp-viewDisp.min())/(viewDisp.max()-viewDisp.min()) * 255).astype(np.uint8)
if self.ui.showColormapCB.isChecked():
inferno = plt.get_cmap('inferno')
viewDisp = inferno(viewDisp/255.0)*255
disp_ = qimage2ndarray.array2qimage(viewDisp)
else:
disp_ = QtGui.QImage(viewDisp.data, \
viewImage.width(),
viewImage.height(),
viewDisp.strides[0],
QtGui.QImage.Format_Indexed8)
''' Display depth '''
self.ui.depthDisplay.setPixmap(QtGui.QPixmap.fromImage(disp_))
self.ui.statusBar.showMessage("Status: Depth Displayed!")
if self.userstudyTask is not None:
self.userstudyTask.resume()
self.userstudyTask.start()
def saveImage(self, saveType):
if saveType == "depth" and self.ui.depthDisplay.pixmap() is None:
self.popMessage("Save Image", "No disparity image to save!")
return
elif saveType == "stroke" and self.guide == None:
self.popMessage("Save Image", "No stroke to save!")
return
elif saveType == "label" and self.guide == None:
self.popMessage("Save Image", "No label to save!")
return
saveName = QFileDialog.getSaveFileName(self, 'Save file', self.dirName)[0]
if ".png" in saveName:
if saveType == 'depth':
disp = self.disp/10*255
cv2.imwrite(saveName, disp.astype("uint8"))
elif saveType == 'stroke':
img = self.guide
img.save(saveName,'PNG')
elif saveType == 'label':
img = self.labelImage
img.save(saveName,'PNG')
elif ".npy" in saveName and saveType == 'depth':
np.save(saveName, self.disp)
else:
self.popMessage("saveImage","Wrong Format!")
self.ui.statusBar.showMessage("Status: {} Image Saved".format(saveType.capitalize()))
def plotImage(self):
if self.figureWidget is None:
self.figureWidget = FigureWidget()
if not self.fileName is None and not self.disp is None:
img = np.array(Image.open(self.fileName))
h,w,c = img.shape
ratio = 384 / max(w,h)
self.figureWidget.plot_pyqtgraph(img, self.disp, ratio)
self.figureWidget.show()
def toggleLabelImage(self):
if self.ui.showLabelCB.isChecked():
if self.labelImage is None:
self.ui.showLabelCB.toggle()
self.popMessage("Error", "No label to display!")
return
labelImage = self.labelImage.toqimage()
labelImage = labelImage.scaledToWidth(self.image.width())
self.ui.imageDisplay.setPixmap(QtGui.QPixmap.fromImage(labelImage))
else:
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
def toggleGuideImage(self):
if not self.ui.showStrokeCB.isChecked():
if self.guide is None:
self.ui.showStrokeCB.toggle()
self.popMessage("Error", "No stroke to display")
return
self.ui.imageDisplay.setPixmap(self.image)
else:
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
def toggleDepthImage(self):
if self.ui.showDepthCB.isChecked():
if self.disp is None:
self.popMessage("Error", "No label to display!")
return
dispImage = self.ui.depthDisplay.pixmap()
results = self.join_pixmap(dispImage, self.guide)
self.ui.imageDisplay.setPixmap(results)
else:
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
def toggleColormap(self):
if self.disp is None:
return
viewImage = self.ui.imageDisplay.pixmap()
viewDisp = cv2.resize(self.disp, (viewImage.width(),viewImage.height()))
viewDisp = ((viewDisp-viewDisp.min())/(viewDisp.max()-viewDisp.min()) * 255).astype(np.uint8)
if self.ui.showColormapCB.isChecked():
inferno = plt.get_cmap('inferno')
viewDisp = inferno(viewDisp/255.0)*255
plt.imsave("colormap.png",viewDisp/255)
disp_ = qimage2ndarray.array2qimage(viewDisp)
else:
disp_ = QtGui.QImage(viewDisp.data, \
viewImage.width(),
viewImage.height(),
viewDisp.strides[0],
QtGui.QImage.Format_Indexed8)
''' Display depth '''
self.ui.depthDisplay.setPixmap(QtGui.QPixmap.fromImage(disp_))
def toggleOverlay(self):
if self.image is None:
return
if self.ui.showOverlayCB.isChecked():
viewImage = self.ui.imageDisplay.pixmap()
dispImage = self.ui.depthDisplay.pixmap()
result = self.join_pixmap(dispImage,viewImage,mode=QtGui.QPainter.CompositionMode_Overlay)
self.ui.depthDisplay.setPixmap(result)
else:
self.toggleColormap()
def pixmap2numpy(self, pixmap):
qimg = pixmap.toImage()
image = qimage2ndarray.rgb_view(qimg)
alpha = np.expand_dims(qimage2ndarray.alpha_view(qimg),2)
image = np.concatenate((image,alpha),axis=2)
return image
def changeValue(self):
size = self.ui.valueSlider.value() / 100.0
self.ui.valueLabel.setText(str(size))
color = int(size*255)
self.pen_color = QtGui.QColor(color,color,color, 255)
self.updateValueBox(color)
def changeSize(self):
size = self.ui.sizeSlider.value()
self.ui.sizeLabel.setText(str(size))
self.pen_size = size
self.brushPixmap = QtGui.QPixmap(self.pen_size,self.pen_size)
self.brushPixmap.fill(self.pen_color)
self.ui.valueBox.setPixmap(self.brushPixmap)
def updateSlider(self, value):
self.ui.valueSlider.setValue(value)
def updateValueBox(self, color):
self.brushPixmap.fill(QtGui.QColor(color,color,color))
self.ui.valueBox.setPixmap(self.brushPixmap)
def mousePressEvent(self, e):
# Check if any image is loaded
if self.ui.imageDisplay.pixmap() is None:
return
# Check if the click happens within display boxes
isImageDisplay = True
if self.inBoundary(e.pos(), self.ui.imageBox):
# If current mouse pointer is out of image box
localPos = self.ui.imageBox.mapFromParent(e.pos())
localPos = self.ui.imageDisplay.mapFromParent(localPos)
# if it is a stroke mode
if not self.pickerActive:
self.prev_guides.append(self.guide)
elif self.inBoundary(e.pos(), self.ui.depthBox) and self.pickerActive \
and self.ui.depthDisplay.pixmap() is not None:
# If current mouse pointer is out of depth box and color picker mode isn't active
localPos = self.ui.depthBox.mapFromParent(e.pos())
localPos = self.ui.depthDisplay.mapFromParent(localPos)
isImageDisplay = False
else:
self.last_x = None
self.last_y = None
return
img_size = self.ui.imageDisplay.pixmap().size()
x = int(localPos.x() - (self.displaySize[0]-img_size.width())/2)
y = int(localPos.y() - (self.displaySize[1]-img_size.height())/2)
#mouse is pressed while shift key is pressed
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ShiftModifier:
print("shift pressed")
stroke = QtGui.QPixmap(self.guide.width(), self.guide.height())
stroke.fill(QtGui.QColor(0,0,0,0))
painter = QtGui.QPainter(stroke)
p = painter.pen()
p.setWidth(self.pen_size)
p.setColor(self.pen_color)
painter.setPen(p)
painter.drawLine(self.last_x, self.last_y, x, y)
painter.end()
self.update()
# if eraser is checked, change the mode for clearing out the original guide
# if not, composite current stroke to guide
if self.ui.eraseButton.isChecked():
mode = QtGui.QPainter.CompositionMode_DestinationOut
else:
mode = QtGui.QPainter.CompositionMode_SourceOver
self.guide = self.join_pixmap(self.guide, stroke, mode=mode)
# Composite guide with loaded rgb image for visualization
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
#log
self.log('mousePress','line')
# Update the origin for next time.
self.last_x = x
self.last_y = y
if self.last_x is None:
self.last_x = x
self.last_y = y
if self.pickerActive: #color picker is currently active
if isImageDisplay:
value = self.guide.toImage().pixelColor(x,y).red()
else:
value = self.ui.depthDisplay.pixmap().toImage().pixelColor(x,y).red()
self.updateSlider(int(value/255*100))
self.updateValueBox(value)
return
def inBoundary(self, pos, constraint):
if type(constraint) == list:
# Constraint is a list of boundary
x_min, x_max, y_min, y_max = constraint
else:
# constraint is an object
x_min, y_min = constraint.x(), constraint.y()
x_max, y_max = x_min + constraint.width(), y_min + constraint.height()
if pos.x() > x_min and pos.x() < x_max \
and pos.y() > y_min and pos.y() < y_max:
return True
else:
return False
def mouseMoveEvent(self, e):
if e.buttons() == QtCore.Qt.NoButton:
return
# Check if any image is loaded
if self.ui.imageDisplay.pixmap() is None:
return
# Check if the click happens within display boxes
isImageDisplay = True
if self.inBoundary(e.pos(), self.ui.imageBox):
# If current mouse pointer is out of image box
localPos = self.ui.imageBox.mapFromParent(e.pos())
localPos = self.ui.imageDisplay.mapFromParent(localPos)
elif self.inBoundary(e.pos(), self.ui.depthBox) and self.pickerActive \
and self.ui.depthDisplay.pixmap() is not None:
# If current mouse pointer is out of depth box and color picker mode isn't active
localPos = self.ui.depthBox.mapFromParent(e.pos())
localPos = self.ui.depthDisplay.mapFromParent(localPos)
isImageDisplay = False
else:
return
img_size = self.ui.imageDisplay.pixmap().size()
x = int(localPos.x() - (self.displaySize[0]-img_size.width())/2)
y = int(localPos.y() - (self.displaySize[1]-img_size.height())/2)
if self.last_x is None:
self.last_x = x
self.last_y = y
return
if self.pickerActive: #color picker is currently active
if isImageDisplay:
value = self.guide.toImage().pixelColor(x,y).red()
else:
value = self.ui.depthDisplay.pixmap().toImage().pixelColor(x,y).red()
self.updateSlider(int(value/255*100))
self.updateValueBox(value)
return
elif self.ui.fillButton.isChecked():
return
# Create current stroke layer
stroke = QtGui.QPixmap(self.guide.width(), self.guide.height())
stroke.fill(QtGui.QColor(0,0,0,0))
painter = QtGui.QPainter(stroke)
p = painter.pen()
p.setWidth(self.pen_size)
p.setColor(self.pen_color)
painter.setPen(p)
painter.drawLine(self.last_x, self.last_y, x, y)
painter.end()
self.update()
# if eraser is checked, change the mode for clearing out the original guide
# if not, composite current stroke to guide
if self.ui.eraseButton.isChecked():
mode = QtGui.QPainter.CompositionMode_DestinationOut
else:
mode = QtGui.QPainter.CompositionMode_SourceOver
self.guide = self.join_pixmap(self.guide, stroke, mode=mode)
# Composite guide with loaded rgb image for visualization
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
# Update the origin for next time.
self.last_x = x
self.last_y = y
def changeThreshold(self):
if self.ui.selectButton.isChecked():
self.segmentArea(self.last_select_x,self.last_select_y,self.ui.thresholdSB.value())
def segmentArea(self,x,y, threshold):
disp = self.pixmap2numpy(self.ui.depthDisplay.pixmap())
mask = np.zeros((disp.shape[0],disp.shape[1],4))
mask = flood_fill(disp,mask,int(x),int(y),QtGui.QColor('#FF0000'),threshold=threshold)
results = self.join_pixmap(self.image, QtGui.QPixmap.fromImage(Image.fromarray(mask.astype(np.uint8)).toqimage()))
self.ui.imageDisplay.setPixmap(results)
self.mask = mask[:,:,0] # R channel == 1
def mouseReleaseEvent(self, e):
if self.ui.strokeButton.isChecked():
self.log('mouseRelease','stroke')
elif self.ui.eraseButton.isChecked():
self.log('mouseRelease','erase')
if self.pickerActive and not (self.last_x is None and self.last_y is None):
self.pickerActive = False
# QApplication.restoreOverrideCursor()
QApplication.setOverrideCursor(Qt.ArrowCursor)
self.ui.strokeButton.setChecked(True)
self.activateStroke()
#log
self.log('mouseRelease','picker')
if self.ui.fillButton.isChecked() and not (self.last_x is None and self.last_y is None):
guide = self.pixmap2numpy(self.guide)
if self.userstudyTask is not None:
self.userstudyTask.pause()
guide = flood_fill(guide,guide.copy(),int(self.last_x),int(self.last_y),self.pen_color)
self.guide = QtGui.QPixmap.fromImage(Image.fromarray(guide).toqimage())
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
#log
if self.userstudyTask is not None:
self.userstudyTask.resume()
self.userstudyTask.start()
self.log('mouseRelease','fill')
# self.last_x = None
# self.last_y = None
if self.inBoundary(e.pos(), self.ui.imageBox) and not self.pickerActive:
self.processImage()
# def keyPressEvent(self, e):
# if e.key() == Qt.Key_Escape:
# self.close()
# elif e.key() == Qt.Key_Z and e.modifiers() == Qt:
# self.loadImage()
# elif e.key() == Qt.Key_N:
# self.showNormal()
def join_pixmap(self, p1, p2, mode=QtGui.QPainter.CompositionMode_SourceOver):
result = QtGui.QPixmap(p1)
result.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(result)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.drawPixmap(result.rect(), p1, p1.rect())
painter.setCompositionMode(mode)
painter.drawPixmap(result.rect(), p2, p2.rect())
painter.end()
return result
def undoStroke(self):
if len(self.prev_guides) == 0:
QtWidgets.QMessageBox.information(self, "Undo", "No more history to undo!")
return
self.prev_guide = self.prev_guides.pop()
results = self.join_pixmap(self.image, self.prev_guide)
self.ui.imageDisplay.setPixmap(results)
self.guide = self.prev_guide
self.processImage()
def eraseAll(self):
if self.ui.imageDisplay.pixmap() is None:
self.popMessage("Erase All", "Nothing to clear!")
return
self.prev_guides.append(self.guide)
self.guide = QtGui.QPixmap(self.guide.width(), self.guide.height())
self.guide.fill(QtGui.QColor(0,0,0,0))
# Update image
results = self.join_pixmap(self.image, self.guide)
self.ui.imageDisplay.setPixmap(results)
self.processImage()
print(self.prev_guide, self.guide)
print("Erase All Strokes")
def activateStroke(self):
self.ui.eraseButton.setChecked(False)
size = self.ui.valueSlider.value() / 100.0
color = size*255
self.pen_color = QtGui.QColor(color,color,color, 255)
def activateEraser(self):
self.ui.strokeButton.setChecked(False)
def activateFill(self):
self.ui.strokeButton.setChecked(False)
self.ui.eraseButton.setChecked(False)
size = self.ui.valueSlider.value() / 100.0
color = size*255
self.pen_color = QtGui.QColor(color,color,color, 255)
def activateSelect(self):
if self.ui.selectButton.isChecked():
self.ui.imageDisplay.setPixmap(self.image)
else: #deactivate
self.ui.imageDisplay.setPixmap(self.join_pixmap(self.image, self.guide))
self.ui.showLabelCB.setChecked(False)
def activatePicker(self, event):
if self.ui.imageDisplay.pixmap() is None:
self.popMessage("Active Picker", "No image to pick value! Please load an image")
return
self.ui.strokeButton.setChecked(False)
self.ui.eraseButton.setChecked(False)
self.pickerActive = True
QApplication.setOverrideCursor(Qt.PointingHandCursor)
self.ui.statusBar.showMessage("Status: Pick a Disparity Value")
def popMessage(self, title, message):
self.msg.setWindowTitle(title)
self.msg.setText(message)
self.msg.exec_()
def updateMode(self):
self.ui.ckptCB.clear()
self.mode = "segDepth"
ckptList = sorted([os.path.basename(x) for x in glob.glob("./ckpt/"+self.mode+"/*.pth")])
self.ui.ckptCB.addItems(ckptList)
self.model = None
def refreshModel(self):
self.model = None
'''userstudy functions'''
def toggleLogging(self):
if self.ui.userLogCB.isChecked():
self.ui.usernameLE.setEnabled(True)
self.ui.userStartButton.setEnabled(True)
self.ui.userDoneButton.setEnabled(True)
else:
self.ui.usernameLE.setEnabled(False)
self.ui.userStartButton.setEnabled(False)
self.ui.userDoneButton.setEnabled(False)
def startLogging(self):
print("(Start Logging)")
path = "D:/Dropbox/01_Work/VML/03_Research/03_Seg2Depth/99_experiment/02_userstudy/02_usability/01_result/M1_ours/"
name = self.ui.usernameLE.text()
self.logDirname = os.path.join(path,name,os.path.basename(self.fileName).split(".")[0])
print(self.logDirname)
if not os.path.exists(self.logDirname):
print("make dirs!")
os.makedirs(self.logDirname)
self.userstudyTask = UserStudyThread(os.path.join(self.logDirname, "log.txt"))
self.userstudyTask.timeSignal.connect(self.logOnProgress)
self.userstudyTask.start()
def stopLogging(self):
self.userstudyTask.stop()
disp = self.disp/10*255
dtime = datetime.now().strftime('%H%M%S')
savename = os.path.join(self.logDirname,dtime +'_final.png')
cv2.imwrite('D:/Dropbox/test.png', disp.astype("uint8"))
self.popMessage("Logging", "Loggig Stopped!")
print("(Stop Logging) Userstudy Stopped!")
self.userstudyTask.quit()
self.userstudyTask = None
def logOnProgress(self, position):
if position == 50:
if self.disp is not None:
disp = self.disp/10*255
dtime = datetime.now().strftime('%H%M%S')
savename = os.path.join(self.logDirname,dtime +'.png')
cv2.imwrite(savename, disp.astype("uint8"))
def log(self,eventType,action='stroke'):
if self.userstudyTask is None:
return
print("!!!!!!!!!!!!",eventType, action)