-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathtileGAN_client.py
1552 lines (1287 loc) · 50.6 KB
/
tileGAN_client.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
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import QObject, QPoint, QPointF, QFile, QSize, QSizeF, QRect, QRectF, QMimeData, Signal, Slot
from PIL import Image
import qdarkstyle
from multiprocessing.managers import BaseManager
import numpy as np
from pathlib import Path
import ctypes
import time
import colorsys
import os
from enum import Enum
USE_DARK_THEME = True
if USE_DARK_THEME:
os.environ['QT_API'] = 'pyqt'
iconFolder = 'icons/dark'
styleColor = (20, 140, 210) #'148cd2'
else:
iconFolder = 'icons/light'
styleColor = (138, 198, 64) #'8ac546' #green
#this is necessary in order to display the correct taskbar icon
myappid = 'application.tileGAN' # arbitrary string
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
class Mode(Enum):
NONE = 0,
MOVE = 1,
RESIZETL = 2,
RESIZET = 3,
RESIZETR = 4,
RESIZER = 5,
RESIZEBR = 6,
RESIZEB = 7,
RESIZEBL = 8,
RESIZEL = 9
class FloatViewer(QWidget):
""" Widget that can be moved and resized by user"""
menu = None
mode = Mode.NONE
position = None
focusIn = Signal(bool)
focusOut = Signal(bool)
newGeometry = Signal(QRect)
def __init__(self, parent, p, preserveAspectRatio=False):
super().__init__(parent=parent)
self.menu = QMenu(parent=self, title='menu')
self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
self.setVisible(True)
self.setAutoFillBackground(False)
self.setMouseTracking(True)
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.setFocus()
self.move(p)
self.imageViewerLabel = QLabel()
self.pixmap = None
self.aspectRatio = 1
self.childWidget = None
self.vLayout = QVBoxLayout(self)
self.setChildWidget(self.imageViewerLabel)
self._inFocus = True
self._showMenu = False
self._isEditing = True
self._preserveAspectRatio = preserveAspectRatio
self.installEventFilter(parent)
def hide(self):
self.setVisible(False)
def show(self):
self.setVisible(True)
def toggle(self):
self.setVisible(not self.isVisible())
def setImage(self, pixmap):
self.pixmap = pixmap
self.aspectRatio = self.pixmap.height()/self.pixmap.width()
self.imageViewerLabel.setPixmap(self.pixmap.scaledToHeight(128))
self.adjustSize()
def resizeImage(self):
pass
def setChildWidget(self, cWidget):
if cWidget:
self.childWidget = cWidget
self.childWidget.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True)
self.childWidget.setParent(self)
self.childWidget.releaseMouse()
self.vLayout.addWidget(cWidget)
self.vLayout.setContentsMargins(0, 0, 0, 0)
self.adjustSize()
def popupShow(self, pt: QPoint):
if self.menu.isEmpty:
return
global_ = self.mapToGlobal(pt)
self._showMenu = True
self.menu.exec(global_)
self._showMenu = False
def focusInEvent(self, a0: QtGui.QFocusEvent):
self._inFocus = True
p = self.parentWidget()
p.installEventFilter(self)
p.repaint()
self.focusIn.emit(True)
def focusOutEvent(self, a0: QtGui.QFocusEvent):
if not self._isEditing:
return
if self._showMenu:
return
self.mode = Mode.NONE
self.focusOut.emit(False)
self._inFocus = False
def paintEvent(self, e: QtGui.QPaintEvent):
pass
def mousePressEvent(self, e: QtGui.QMouseEvent):
self.position = QPoint(e.globalX() - self.geometry().x(), e.globalY() - self.geometry().y())
if not self._isEditing:
return
if not self._inFocus:
return
if not e.buttons() and QtCore.Qt.LeftButton:
self.setCursorShape(e.pos())
return
if e.button() == QtCore.Qt.RightButton:
self.popupShow(e.pos())
e.accept()
def setCursorShape(self, pos: QPoint):
diff = 3
bottom = abs(pos.y() - self.y() - self.height()) < diff
left = abs(pos.x() - self.x()) < diff
right = abs(pos.x() - self.x() - self.width()) < diff
top = abs(pos.y() - self.y()) < diff
if not (bottom or left or right or top):
self.setCursor(QCursor(QtCore.Qt.SizeAllCursor))
self.mode = Mode.MOVE
return
if bottom and left:
self.mode = Mode.RESIZEBL
self.setCursor(QCursor(QtCore.Qt.SizeBDiagCursor))
return
elif bottom and right:
self.mode = Mode.RESIZEBR
self.setCursor(QCursor(QtCore.Qt.SizeFDiagCursor))
return
elif top and left:
self.mode = Mode.RESIZETL
self.setCursor(QCursor(QtCore.Qt.SizeFDiagCursor))
return
elif top and right:
self.mode = Mode.RESIZETR
self.setCursor(QCursor(QtCore.Qt.SizeBDiagCursor))
return
if not self._preserveAspectRatio:
if left:
self.setCursor(QCursor(QtCore.Qt.SizeHorCursor))
self.mode = Mode.RESIZEL
elif right:
self.setCursor(QCursor(QtCore.Qt.SizeHorCursor))
self.mode = Mode.RESIZER
elif top: # Top
self.setCursor(QCursor(QtCore.Qt.SizeVerCursor))
self.mode = Mode.RESIZET
elif bottom: # Bottom
self.setCursor(QCursor(QtCore.Qt.SizeVerCursor))
self.mode = Mode.RESIZEB
def mouseReleaseEvent(self, e: QtGui.QMouseEvent):
QWidget.mouseReleaseEvent(self, e)
def mouseMoveEvent(self, e: QtGui.QMouseEvent):
QWidget.mouseMoveEvent(self, e)
if not self._isEditing or not self._inFocus:
return
if not e.buttons() and QtCore.Qt.LeftButton:
p = QPoint(e.x() + self.geometry().x(), e.y() + self.geometry().y())
self.setCursorShape(p)
return
#move widget
if (self.mode == Mode.MOVE or self.mode == Mode.NONE) and e.buttons() and QtCore.Qt.LeftButton:
toMove = e.globalPos() - self.position
if toMove.x() < 0: return
if toMove.y() < 0: return
if toMove.x() > self.parentWidget().width() - self.width(): return
self.move(toMove)
self.newGeometry.emit(self.geometry())
self.parentWidget().repaint()
return
#resize widget
if (self.mode != Mode.MOVE) and e.buttons() and QtCore.Qt.LeftButton:
deltaL = e.globalX() - self.position.x() - self.geometry().x()
deltaT = e.globalY() - self.position.y() - self.geometry().y()
deltaPos = e.globalPos() - self.position
if self.mode == Mode.RESIZETL: # TopLeft
self.resize(self.geometry().width() - deltaL, self.geometry().height() - deltaT)
self.move(deltaPos.x(), deltaPos.y())
elif self.mode == Mode.RESIZETR: # TopRight
self.resize(e.x(), self.geometry().height() - deltaT)
self.move(self.x(), deltaPos.y())
elif self.mode == Mode.RESIZEBL: # BottomLeft
self.resize(self.geometry().width() - deltaL, e.y())
self.move(deltaPos.x(), self.y())
elif self.mode == Mode.RESIZEB: # Bottom
self.resize(self.width(), e.y())
elif self.mode == Mode.RESIZEL: # Left
self.resize(self.geometry().width() - deltaL, self.height())
self.move(deltaPos.x(), self.y())
elif self.mode == Mode.RESIZET: # Top
self.resize(self.width(), self.geometry().height() - deltaT)
self.move(self.x(), deltaPos.y())
elif self.mode == Mode.RESIZER: # Right
self.resize(e.x(), self.height())
elif self.mode == Mode.RESIZEBR: # BottomRight
self.resize(e.x(), e.y())
self.parentWidget().repaint()
self.newGeometry.emit(self.geometry())
class GetDimensionsDialog(QDialog):
""" Dialog window for requesting a width and height input. Can be configured to keep aspect ratio."""
def __init__(self, h, w, min=1, max=100, constrain=False, parent=None):
super(GetDimensionsDialog, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)
## set default values
self.h = h
self.w = w
self.hL = QLabel("height:")
self.hInput = QSpinBox(self)
self.hInput.setMinimum(min)
self.hInput.setMaximum(max)
self.hInput.setValue(self.h)
self.wL = QLabel("width:")
self.wInput = QSpinBox(self)
self.wInput.setMinimum(min)
self.wInput.setMaximum(max)
self.wInput.setValue(self.w)
if constrain:
self.aspectRatio = h/w
self.hInput.valueChanged.connect(self.constrainW)
self.wInput.valueChanged.connect(self.constrainH)
self.OKBtn = QPushButton("OK")
self.OKBtn.clicked.connect(self.accept)
## Set layout, add buttons
layout = QGridLayout()
layout.setColumnStretch(1, 1)
layout.setColumnMinimumWidth(1, 250)
layout.addWidget(self.hL, 0, 0)
layout.addWidget(self.hInput, 0, 1)
layout.addWidget(self.wL, 1, 0)
layout.addWidget(self.wInput, 1, 1)
layout.addWidget(self.OKBtn, 2, 1)
self.setLayout(layout)
self.setWindowTitle("Select grid dimensions")
def values(self):
return self.hInput.value(), self.wInput.value()
def constrainW(self):
self.wInput.blockSignals(True)
self.wInput.setValue(self.hInput.value() / self.aspectRatio )
self.wInput.blockSignals(False)
def constrainH(self):
self.hInput.blockSignals(True)
self.hInput.setValue(self.wInput.value() * self.aspectRatio )
self.hInput.blockSignals(False)
@staticmethod
def getValues(h=1, w=1, min=1, max=100, constrain=False, parent=None):
dialog = GetDimensionsDialog(h, w, min, max, constrain, parent)
result = dialog.exec_()
h, w = dialog.values()
return h, w, result == QDialog.Accepted
class GetLevelDialog(QDialog):
""" Dialog window for requesting a level and latent size input."""
def __init__(self, m, l, parent=None):
super(GetLevelDialog, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)
## Default values
self.mL = QLabel("merge level:")
self.mInput = QSpinBox(self)
self.mInput.setMinimum(2)
self.mInput.setMaximum(9)
self.mInput.setValue(m)
self.lL = QLabel("latent size:")
self.lInput = QSpinBox(self)
self.lInput.setMinimum(1)
self.lInput.setMaximum(512)
self.lInput.setValue(l)
self.OKBtn = QPushButton("OK")
self.OKBtn.clicked.connect(self.accept)
## Set layout, add buttons
layout = QGridLayout()
layout.setColumnStretch(1, 1)
layout.setColumnMinimumWidth(1, 250)
layout.addWidget(self.mL, 0, 0)
layout.addWidget(self.mInput, 0, 1)
layout.addWidget(self.lL, 1, 0)
layout.addWidget(self.lInput, 1, 1)
layout.addWidget(self.OKBtn, 2, 1)
self.setLayout(layout)
self.setWindowTitle("Select merge level")
def values(self):
return self.mInput.value(), self.lInput.value()
@staticmethod
def getValues(m=2, l=1, parent=None):
dialog = GetLevelDialog(m, l, parent)
result = dialog.exec_()
m, l = dialog.values()
return m, l, result == QDialog.Accepted
class GetDatasetDialog(QDialog):
""" Dialog window for requesting a dataset selection from a drop-down box."""
def __init__(self, datasets, dataset, parent=None):
super(GetDatasetDialog, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)
## Default values
self.dL = QLabel("Choose dataset:")
self.dInput = QComboBox(self)
for d in datasets:
self.dInput.addItem(d)
self.dInput.setCurrentIndex(self.dInput.findText(dataset))
self.OKBtn = QPushButton("OK")
self.OKBtn.clicked.connect(self.accept)
## Set layout, add buttons
layout = QGridLayout()
layout.setColumnStretch(1, 1)
layout.setColumnMinimumWidth(1, 250)
layout.addWidget(self.dL, 0, 0)
layout.addWidget(self.dInput, 0, 1)
layout.addWidget(self.OKBtn, 1, 1)
self.setLayout(layout)
self.setWindowTitle("Select dataset")
def value(self):
return self.dInput.currentText()
@staticmethod
def getValue(ds=None, d='', parent=None):
dialog = GetDatasetDialog(ds, d, parent)
result = dialog.exec_()
return dialog.value(), result == QDialog.Accepted
class ImageViewer(QtWidgets.QGraphicsView):
""" Main class for the image viewer widget."""
imageClicked = Signal(QtCore.QPoint)
undoCountUpdated = Signal(int)
guidanceUpdated = Signal(bool)
imageUpdated = Signal(bool)
mouseDrop = Signal()
textEdited = Signal(str)
def __init__(self, parent):
super(ImageViewer, self).__init__(parent)
self.setAcceptDrops(True)
self._zoom = 0
self._showGrid = False
self._empty = True
self._emptyUnmerged = True
self._emptyClusters = True
self.gridSize = QSize(0, 0)
self.latentSize = 1
self.mergeLevel = 2
self.pad = 1
self.dataset = ''
self.imageShape = QSize(0, 0)
self.defaultGuidanceMap = None
self.guidanceMap = None
self._scene = QGraphicsScene(self)
self._image = QGraphicsPixmapItem()
self._imageClusters = QGraphicsPixmapItem()
self._imageClusters.setVisible(False)
self._imageUnmerged = QGraphicsPixmapItem()
self._imageUnmerged.setVisible(False)
self._latentIndicator = QGraphicsPixmapItem()
self._latentIndicator.setVisible(False)
self._showLatentIndicator = True
self._scene.addItem(self._image)
self._scene.addItem(self._imageClusters)
self._scene.addItem(self._imageUnmerged)
self._scene.addItem(self._latentIndicator)
self.setScene(self._scene)
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
self.setFrameShape(QtWidgets.QFrame.NoFrame)
self.latent_dragEvent = False
self.dragPixmaps = None
self.drag = None
self.wheelSelection = 0
self.latentCluster = None
self.sampledLatentPos = None
self.sampledLatent = None
self.useSimilarLatents = False
self.mouseClickPosition = None
self.leftMouseButtonDown = False
self.middleMouseButtonDown = False
self._panStart = QPoint(0, 0)
#show tutorial on startup
tutorialPath = 'tileGAN_firstSteps.jpg'
self.updateImage(QtGui.QPixmap(tutorialPath), fitToView=True, updateUI=False)
#-----------------------------------------------------------------------------------------------------------------------------------------
# HANDLING OF INHERITED EVENTS
#-----------------------------------------------------------------------------------------------------------------------------------------
def dragEnterEvent(self, event):
event.accept()
return
def dragMoveEvent(self, event):
event.accept()
return
def dropEvent(self, event):
event.accept()
event.setDropAction(QtCore.Qt.MoveAction)
self.mouseDrop.emit()
if self._image.isUnderMouse() and self.latent_dragEvent:
print('<ImageViewer> latent drop event in ImageViewer')
modifiers = QtGui.QGuiApplication.keyboardModifiers()
self.dropLatent(self.latentCluster, event.pos(), modifiers)
self.latent_dragEvent = False
self.drag = None
self.leftMouseButtonDown = False
def enterEvent(self, event):
if self.latent_dragEvent:
return
if self.hasImage():
self.updateIndicatorSize()
if self._showLatentIndicator:
self._latentIndicator.show()
def leaveEvent(self, event):
if self.hasImage():
self._latentIndicator.hide()
def mouseMoveEvent(self, event):
if self.middleMouseButtonDown:
# panning behaviour
delta = self._panStart - event.pos()
self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() + delta.x())
self.verticalScrollBar().setValue(self.verticalScrollBar().value() + delta.y())
self._panStart = event.pos()
event.accept()
return
if self.hasImage():
event.accept()
self.updateIndicatorPos(event.pos())
super(ImageViewer, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self.middleMouseButtonDown = False
self.latent_dragEvent = False
if self._image.isUnderMouse():
#processing dragging
if self.mouseClickPosition is not None and (event.pos() - self.mouseClickPosition).manhattanLength() > QApplication.startDragDistance():
if not self.leftMouseButtonDown or self.sampledLatent is None:
super(ImageViewer, self).mousePressEvent(event)
return
gridCoords1 = self.getGridCoords(self.mouseClickPosition)
gridCoords2 = self.getGridCoords(event.pos())
startX = np.amin([gridCoords1.x(), gridCoords2.x()])
startY = np.amin([gridCoords1.y(), gridCoords2.y()])
endX = np.amax([gridCoords1.x(), gridCoords2.x()])
endY = np.amax([gridCoords1.y(), gridCoords2.y()])
sourceX = self.sampledLatentPos.x()
sourceY = self.sampledLatentPos.y()
height = endY - startY
width = endX - startX
if height > 0 and width > 0:
self.replaceLatentRegion(startX, startY, width, height, sourceX, sourceY)
#processing click: only do this if not dragging
elif event.button() & QtCore.Qt.LeftButton:
print('<ImageViewer> mouseReleaseEvent at {}'.format(self.getPixelCoords(event.pos())))
modifiers = QtGui.QGuiApplication.keyboardModifiers()
if self.latentCluster is not None:
self.dropLatent(self.latentCluster, event.pos(), modifiers)
self.imageClicked.emit(QtCore.QPoint(event.pos()))
self.leftMouseButtonDown = False
super(ImageViewer, self).mousePressEvent(event)
def mousePressEvent(self, event):
if self._image.isUnderMouse():
if event.button() & QtCore.Qt.RightButton:
print('<ImageViewer> right mouse button clicked!')
self.sampleLatentAtPos(event.pos())
modifiers = QtGui.QGuiApplication.keyboardModifiers()
if modifiers == QtCore.Qt.ShiftModifier:
self.useSimilarLatents = True
else:
self.useSimilarLatents = False
elif event.button() & QtCore.Qt.MiddleButton:
print('<ImageViewer> middle mouse button clicked!')
self.middleMouseButtonDown = True
self._panStart = event.pos()
elif event.button() & QtCore.Qt.LeftButton:
self.leftMouseButtonDown = True
self.mouseClickPosition = event.pos()
print('<ImageViewer> left mouse button clicked at {}!'.format(self.mouseClickPosition))
def wheelEvent(self, event):
#zoom behaviour
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
if self.hasImage():
if event.angleDelta().y() > 0:
factor = 1.25
self._zoom += 1
else:
factor = 0.8
self._zoom -= 1
if self._zoom > 0:
self.scale(factor, factor)
self.updateIndicatorSize()
elif self._zoom == 0:
self.fitInView()
else:
self._zoom = 0
def resizeEvent(self, event):
self.fitInView()
# -----------------------------------------------------------------------------------------------------------------------------------------
def setDrag(self, drag):
self.drag = drag
def updateIndicatorSize(self, stroke=3, offset=2, crossSize=10):
"""
draw a box and crosshair under mouse cursor as rectangle of size latentSize
"""
multiplier = 1 #TODO optional: scale indicator with zoom level
stroke *= multiplier
offset *= multiplier
crossSize *= multiplier
halfStroke = stroke / 2
rect = self.getImageDims()
latentSize = self.latentSize * rect.width() / self.gridSize.width()
halfSize = latentSize / 2
crossSize = min(crossSize, int(halfSize - 3))
pixmap = QPixmap(QSize(int(latentSize + stroke + offset), int(latentSize + stroke + offset)))
#fill rectangle with transparent color
pixmap.fill(QColor(0,0,0,0)) #transparent
painter = QPainter(pixmap)
r = QRectF(QPoint(), QSizeF(latentSize, latentSize))
r.adjust(offset+halfStroke, offset+halfStroke, -halfStroke, -halfStroke)
#draw shadow under rectangle
pen = QPen(QColor(50, 50, 50, 100), stroke) #shadow
painter.setPen(pen)
painter.drawRect(r)
if crossSize > 4:
painter.drawLine(QPointF(offset+halfSize, offset+halfSize-crossSize), QPointF(offset+halfSize, offset+halfSize+crossSize))
painter.drawLine(QPointF(offset+halfSize-crossSize, offset+halfSize), QPointF(offset+halfSize+crossSize, offset+halfSize))
r.adjust(-offset, -offset, -offset, -offset)
pen = QPen(QColor(styleColor[0], styleColor[1], styleColor[2], 200), stroke)
painter.setPen(pen)
painter.drawRect(r)
if crossSize > 4:
painter.drawLine(QPointF(halfSize, halfSize - crossSize), QPointF(halfSize, halfSize + crossSize))
painter.drawLine(QPointF(halfSize - crossSize, halfSize), QPointF(halfSize + crossSize, halfSize))
painter.end()
self._latentIndicator.setPixmap(pixmap)
def updateIndicatorPos(self, eventPos):
"""
move indicator cursor to correct position under mouse
"""
rect = self.getImageDims()
gridSize = rect.width() / self.gridSize.width()
latentSize = self.latentSize * gridSize
centerOffset = latentSize // 2
scenePos = QGraphicsView.mapToScene(self, eventPos)
scenePos -= QPointF(centerOffset, centerOffset) #center latentIndicator around mouse
roundPos = QPoint(int(gridSize * round(scenePos.x()/gridSize)), int(gridSize * round(scenePos.y()/gridSize)))
roundPos.setX(int(max(-centerOffset, min(roundPos.x(), rect.width() - ( latentSize - centerOffset )))))
roundPos.setY(int(max(-centerOffset, min(roundPos.y(), rect.height() - ( latentSize - centerOffset )))))
self._latentIndicator.setPos(roundPos)
def hasImage(self):
return not self._empty
def getImageDims(self):
return QRectF(self._image.pixmap().rect())
def fitInView(self, scale=True):
rect = self.getImageDims()
if not rect.isNull():
self.setSceneRect(rect)
unity = self.transform().mapRect(QRectF(0, 0, 1, 1))
self.scale(1 / unity.width(), 1 / unity.height())
viewrect = self.viewport().rect()
scenerect = self.transform().mapRect(rect)
factor = min(viewrect.width() / scenerect.width(),
viewrect.height() / scenerect.height())
self.scale(factor, factor)
if self.hasImage():
self.updateIndicatorSize()
self._zoom = 0
def toggleGrid(self):
"""
toggle the foreground grid that indicates the latent grid spacing
"""
if not self.hasImage():
return
self._showGrid = not self._showGrid
self._scene.update()
def toggleLatentIndicator(self, state):
"""
toggle the crosshair that indicates the latent size
"""
self._showLatentIndicator = state
def dragStarted(self, latentCluster):
"""
start a drag operation in imageViewer
"""
print('<ImageViewer> drag started')
self.latent_dragEvent = True
self.latentCluster = latentCluster
def activateLatentCluster(self, latentCluster):
self.latentCluster = latentCluster
def getPixelCoords(self, pos):
floatPos = QGraphicsView.mapToScene(self, pos)
return QPoint(np.rint(floatPos.x()), np.rint(floatPos.y()))
def roundToGlobalGridCoords(self, pos):
"""
return a global coordinate for a latent grid position
"""
roundedGridPos = self.getGridCoords(pos)
imageRect = self.getImageDims()
pixelPos = QPointF(roundedGridPos.x() * imageRect.width() / self.gridSize.width(), roundedGridPos.y() * imageRect.height() / self.gridSize.height())
return QGraphicsView.mapToGlobal(self, QGraphicsView.mapFromScene(self, pixelPos))
def getGridCoords(self, pos):
"""
return a grid coordinate for a global position
"""
imageRect = self.getImageDims()
pixelCoords = self.getPixelCoords(pos)
gridX = np.rint(self.gridSize.width() * pixelCoords.x() / imageRect.width())
gridY = np.rint(self.gridSize.height() * pixelCoords.y() / imageRect.height())
return QPoint(gridX, gridY)
def getCurrentLatentSize(self):
"""
return the size in pixels of a latent at current zoom level
"""
rect = self.getImageDims()
scenerect = self.transform().mapRect(rect)
latentSize = self.latentSize * scenerect.width() / self.gridSize.width() #(self.latentSize *
return latentSize
def dropLatent(self, latentCluster, pos, keyModifiers):
gridCoords = self.getGridCoords(pos)
alpha = 0.1
if keyModifiers == QtCore.Qt.ShiftModifier:
print('<ImageViewer> perturbing latent at ({}, {}) with class {}'.format(gridCoords.x(), gridCoords.y(), latentCluster))
sourceX = self.sampledLatentPos.x()
sourceY = self.sampledLatentPos.y()
output, undoCount = np.asarray(tf_manager.perturbLatent(gridCoords.x(), gridCoords.y(), sourceX, sourceY, alpha)._getvalue())
else:
print('<ImageViewer> dropped latent of class {} at ({}, {})'.format(latentCluster, gridCoords.x(), gridCoords.y()))
output, undoCount = np.asarray(tf_manager.putLatent(gridCoords.x(), gridCoords.y(), latentCluster)._getvalue())
self.undoCountUpdated.emit(undoCount)
self.updateImage(output)
def replaceLatentRegion(self, startX, startY, width, height, sampleX, sampleY):#, x_target, y_target):
mode = 'similar' if self.useSimilarLatents else 'identical'
#mode = 'cluster' #if self.useSimilarLatents else 'identical'
print('<ImageViewer> replaceLatentRegion at ({}, {}) of size {}x{} from ({}, {}) with {}'.format(startX, startY, width, height, sampleX, sampleY, mode))
output, undoCount = np.asarray(tf_manager.pasteLatents(self.sampledLatent, startX, startY, width, height, sampleX, sampleY, mode)._getvalue())
self.undoCountUpdated.emit(undoCount)
self.updateImage(output)
def undo(self):
output, undoCount = np.asarray(tf_manager.undo()._getvalue())
print('<ImageViewer> undo (new undo count = {})'.format(undoCount))
self.undoCountUpdated.emit(undoCount)
self.updateImage(output)
def toggleMerging(self, showMerging):
"""
toggle view between merged latents and unmerged grid
"""
if not self.hasImage():
return
if not showMerging and self._emptyUnmerged:
output = np.asarray(tf_manager.getUnmergedOutput()._getvalue())
pixmap = self.pixmapFromArray(output)
self._imageUnmerged.setPixmap(pixmap)
self._emptyUnmerged = False
self._imageUnmerged.setVisible(not showMerging)
def toggleClusters(self, showClusters):
"""
toggle view between merged latents and clusters of each latent
"""
if not self.hasImage():
return
if showClusters and self._emptyClusters:
print('<ImageViewer> toggle clusters')
output = np.asarray(tf_manager.getClusterOutput()._getvalue())
rect = self.getImageDims()
upsampledOutput = output.repeat(rect.height()//output.shape[0], axis=0).repeat(rect.width()//output.shape[1], axis=1)
pixmap = self.pixmapFromArray(upsampledOutput)
self._imageClusters.setPixmap(pixmap)
self._emptyClusters = False
self._imageClusters.setVisible(showClusters)
def toggleGuidanceMap(self):
"""
hide or show floating guidance viewer widget as a layover on top of image viewer
"""
self.guidanceViewer.toggle()
def refresh(self):
"""
force an update of the texture from manager
"""
print('<ImageViewer> refresh')
output, gridShape = np.asarray(tf_manager.getOutput()._getvalue())
self.updateGridShape(np.asarray(gridShape))
self.updateImage(output)
def improveResults(self):
print('<ImageViewer> improve')
output = np.asarray(tf_manager.improveLatents()._getvalue())
self.updateImage(output)
def randomize(self):
"""
generate a randomized latent grid
"""
self.defaultGuidanceMap = None
self.guidanceMap = None
self.guidanceUpdated.emit(False)
w = self.gridSize.width() // self.latentSize
h = self.gridSize.height() // self.latentSize
if w < 1 and h < 1:
w = 5
h = 3
h, w, ok = GetDimensionsDialog.getValues(h=max(h, 1), w=max(w, 1))
if not ok: #Dialog was terminated
return
print('<ImageViewer> randomizing {}x{} grid'.format(h, w))
output, gridShape, undoCount = tf_manager.randomizeGrid(h, w)._getvalue()
self.undoCountUpdated.emit(undoCount)
self.updateGridShape(np.asarray(gridShape))
self.updateImage(np.asarray(output), fitToView=True)
def deadLeaves(self):
"""
generate a randomized latent grid with larger coherent regions using "dead leaves" algorithm
"""
self.defaultGuidanceMap = None
self.guidanceMap = None
self.guidanceUpdated.emit(False)
w = self.gridSize.width() // self.latentSize
h = self.gridSize.height() // self.latentSize
h, w, ok = GetDimensionsDialog.getValues(h=max(h, 1), w=max(w, 1))
if not ok: #Dialog was terminated
return
print('randomizing {}x{} grid'.format(h, w))
output, gridShape, undoCount = tf_manager.deadLeaves(h, w)._getvalue()
self.undoCountUpdated.emit(undoCount)
self.updateGridShape(np.asarray(gridShape))
self.updateImage(np.asarray(output), fitToView=True)
def setMergeLevel(self):
"""
adjust latent merge level
"""
level, latentSize, ok = GetLevelDialog.getValues(m=self.mergeLevel, l=self.latentSize)
#check parameter validity
if latentSize > 2 ** level:
latentSize = 2 ** level
msg = QMessageBox()
msg.setWindowTitle("Latent settings warning")
msg.setIcon(QMessageBox.Warning)
msg.setText("Latent size cannot be larger than 2^level.\n Latent size for level {} reset to {}".format(level, latentSize))
msg.setStandardButtons(QMessageBox.Ok)
msg.exec_()
if not ok or (level == self.mergeLevel and latentSize == self.latentSize): #Dialog was terminated or settings stayed the same
return
self.mergeLevel = level
self.latentSize = latentSize
print('<ImageViewer> updating new merge level to {}, latentSize {}'.format(self.mergeLevel, self.latentSize))
tf_manager.setMergeLevel(self.mergeLevel, self.latentSize)
output, gridShape = np.asarray(tf_manager.getOutput()._getvalue())
self.updateGridShape(np.asarray(gridShape))
self.updateImage(output, fitToView=True)
def resizeGuidanceMap(self, noUpdate=False):
"""
rescale the guidance image to generate a different result size. guidance image is stored in original resolution and always resized from original image.
"""
guidanceImg = Image.fromarray(self.defaultGuidanceMap)
if noUpdate:
w = guidanceImg.width
h = guidanceImg.height
else:
if self.guidanceMap is not None:
h = self.guidanceMap.shape[0]
w = self.guidanceMap.shape[1]
else:
h = self.defaultGuidanceMap.shape[0]
w = self.defaultGuidanceMap.shape[1]
h, w, ok = GetDimensionsDialog.getValues(h=h, w=w, max=10000, constrain=True)
print('h {} w {} ok {}'.format(h, w, ok))
if not ok: #Dialog was terminated
return False
self.guidanceMap = np.asarray(guidanceImg.resize((w, h)))
if not noUpdate:
print('updating now!')
self.update()
else:
self.guidanceUpdated.emit(True)
return True
def update(self):
output, descriptorGrid, gridShape, undoCount = np.asarray(tf_manager.getUpsampled(self.guidanceMap)._getvalue())
self.updateImage(output, fitToView=True)
self.undoCountUpdated.emit(undoCount)
self.updateGridShape(gridShape)
def processImage(self, fname):
"""
load image from file, convert image, request desired guidance map size and set as guidance image
"""
pilImg = Image.open(fname)
self.defaultGuidanceMap = np.asarray(pilImg.convert("RGB"))
success = self.resizeGuidanceMap(noUpdate=True)
if not success: #Dialog was terminated
return
# TODO don't allow arbitrarily big images
self.guidanceViewer.setImage(self.pixmapFromArray(self.defaultGuidanceMap))
output, descriptorGrid, gridShape, undoCount = np.asarray(tf_manager.getUpsampled(self.guidanceMap)._getvalue())
self.undoCountUpdated.emit(undoCount)
self.updateGridShape(gridShape)
self.updateImage(output, fitToView=True)
def updateGridShape(self, gridShape):
self.gridSize = QSize(gridShape[1], gridShape[0])
self.latentSize = gridShape[2]
self.mergeLevel = gridShape[3]
def drawForeground(self, painter, rect):
"""
override drawForeground method to paint latent grid cells
"""
if self._showGrid:
rect = self.getImageDims()
#draw all grid cells
penNarrow = QPen(QColor(100, 100, 100, 150), 2)
penNarrow.setStyle(QtCore.Qt.CustomDashLine)
penNarrow.setDashPattern([1, 2])
penBold = QPen(QColor(styleColor[0], styleColor[1], styleColor[2], 150), 3)
penBold.setStyle(QtCore.Qt.CustomDashLine)
penBold.setDashPattern([1, 2])
painter.setPen(penNarrow)
d = rect.width() / self.gridSize.width()
for y in range(1, self.gridSize.height()):
if y % self.latentSize == 0: #bold lines at more important grid positions
painter.setPen(penBold)
else:
painter.setPen(penNarrow)
painter.drawLine(QPoint(0, int(y * d)), QPoint(int(rect.width()), int(y * d)))
for x in range(1, self.gridSize.width()):
if x % self.latentSize == 0:
painter.setPen(penBold)
else:
painter.setPen(penNarrow)
painter.drawLine(QPoint(int(x*d), 0), QPoint(int(x*d), int(rect.height())))
def pixmapFromArray(self, array):
"""
convert numpy array to QPixmap. Memory needs to be copied to avoid mem issues.
"""
print(array.shape)
if array.shape[0] == 3:
array = np.rollaxis(array, 0, 3)
self.imageShape = QSize(array.shape[1], array.shape[0])
cp = array.copy()
image = QImage(cp, array.shape[1], array.shape[0], QImage.Format_RGB888)
return QPixmap(image)
def updateImage(self, image=None, fitToView=False, updateUI=True):
"""
update result image in image viewer and trigger all appropriate settings
"""