-
-
Notifications
You must be signed in to change notification settings - Fork 213
/
cvui.py
2787 lines (2273 loc) · 93 KB
/
cvui.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
"""
A (very) simple UI lib built on top of OpenCV drawing primitives.
Version: 2.7
Use of cvui revolves around calling cvui.init() to initialize the lib,
rendering cvui components to a np.ndarray (that you handle yourself) and
finally showing that np.ndarray on the screen using cvui.imshow(), which
is cvui's version of cv2.imshow(). Alternatively you can use cv2.imshow()
to show things, but in such case you must call cvui.update() yourself
before calling cv.imshow().
E.g.:
import numpy as np
import cv2
import cvui
WINDOW_NAME = 'CVUI Hello World!'
frame = np.zeros((200, 500, 3), np.uint8)
cvui.init(WINDOW_NAME)
while (True):
# Fill the frame with a nice color
frame[:] = (49, 52, 49)
cvui.text(frame, x, y, 'Hello world!')
cvui.imshow(WINDOW_NAME, frame)
if cv2.waitKey(20) == 27:
break
Read the full documentation at https://dovyski.github.io/cvui/
Copyright (c) 2018 Fernando Bevilacqua <dovyski@gmail.com>
Licensed under the MIT license.
"""
import cv2
import numpy as np
import sys
def main():
# TODO: make something here?
return 0
if __name__ == '__main__':
main()
# Lib version
VERSION = '2.7'
# Constants regarding component interactions
ROW = 0
COLUMN = 1
DOWN = 2
CLICK = 3
OVER = 4
OUT = 5
UP = 6
IS_DOWN = 7
# Constants regarding mouse buttons
LEFT_BUTTON = 0
MIDDLE_BUTTON = 1
RIGHT_BUTTON = 2
# Constants regarding components
TRACKBAR_HIDE_SEGMENT_LABELS = 1
TRACKBAR_HIDE_STEP_SCALE = 2
TRACKBAR_DISCRETE = 4
TRACKBAR_HIDE_MIN_MAX_LABELS = 8
TRACKBAR_HIDE_VALUE_LABEL = 16
TRACKBAR_HIDE_LABELS = 32
# Internal things
_IS_PY2 = sys.version_info.major == 2
CVUI_ANTIALISED = cv2.LINE_AA
CVUI_FILLED = -1
# Represent a 2D point.
class Point:
def __init__(self, theX = 0, theY = 0):
self.x = theX
self.y = theY
def inside(self, theRect):
return theRect.contains(self)
# Represent a rectangle.
class Rect:
def __init__(self, theX = 0, theY = 0, theWidth = 0, theHeight = 0):
self.x = theX
self.y = theY
self.width = theWidth
self.height = theHeight
def contains(self, thePoint):
return thePoint.x >= self.x and thePoint.x <= (self.x + self.width) and thePoint.y >= self.y and thePoint.y <= (self.y + self.height)
def area(self):
return self.width * self.height
# Represent the size of something, i.e. width and height.
# It is essentially a simplified version of Rect where x and y are zero.
class Size(Rect):
def __init__(self, theWidth = 0, theHeight = 0):
self.x = 0
self.y = 0
self.width = theWidth
self.height = theHeight
# Describe a block structure used by cvui to handle `begin*()` and `end*()` calls.
class Block:
def __init__(self):
self.where = None # where the block should be rendered to.
self.rect = Rect() # the size and position of the block.
self.fill = Rect() # the filled area occuppied by the block as it gets modified by its inner components.
self.anchor = Point() # the point where the next component of the block should be rendered.
self.padding = 0 # padding among components within this block.
self.type = ROW # type of the block, e.g. ROW or COLUMN.
self.reset()
def reset(self):
self.rect.x = 0
self.rect.y = 0
self.rect.width = 0
self.rect.height = 0
self.fill = self.rect
self.fill.width = 0
self.fill.height = 0
self.anchor.x = 0
self.anchor.y = 0
self.padding = 0
# Describe a component label, including info about a shortcut.
# If a label contains "Re&start", then:
# - hasShortcut will be true
# - shortcut will be 's'
# - textBeforeShortcut will be "Re"
# - textAfterShortcut will be "tart"
class Label:
def __init__(self):
self.hasShortcut = False
self.shortcut = ''
self.textBeforeShortcut = ''
self.textAfterShortcut = ''
# Describe a mouse button
class MouseButton:
def __init__(self):
self.justReleased = False # if the mouse button was released, i.e. click event.
self.justPressed = False # if the mouse button was just pressed, i.e. true for a frame when a button is down.
self.pressed = False # if the mouse button is pressed or not.
def reset(self):
self.justPressed = False
self.justReleased = False
self.pressed = False
# Describe the information of the mouse cursor
class Mouse:
def __init__(self):
self.buttons = { # status of each button. Use cvui.{RIGHT,LEFT,MIDDLE}_BUTTON to access the buttons.
LEFT_BUTTON: MouseButton(),
MIDDLE_BUTTON: MouseButton(),
RIGHT_BUTTON: MouseButton()
}
self.anyButton = MouseButton() # represent the behavior of all mouse buttons combined
self.position = Point(0, 0) # x and y coordinates of the mouse at the moment.
# Describe a (window) context.
class Context:
def __init__(self):
self.windowName = '' # name of the window related to this context.
self.mouse = Mouse() # the mouse cursor related to this context.
# Describe the inner parts of the trackbar component.
class TrackbarParams:
def __init__(self, theMin = 0., theMax = 25., theStep = 1., theSegments = 0, theLabelFormat = '%.0Lf', theOptions = 0):
self.min = theMin
self.max = theMax
self.step = theStep
self.segments = theSegments
self.options = theOptions
self.labelFormat = theLabelFormat
# This class contains all stuff that cvui uses internally to render
# and control interaction with components.
class Internal:
def __init__(self):
self.defaultContext = ''
self.currentContext = ''
self.contexts = {} # indexed by the window name.
self.buffer = []
self.lastKeyPressed = -1 # TODO: collect it per window
self.delayWaitKey = -1
self.screen = Block()
self.stack = [Block() for i in range(100)] # TODO: make it dynamic
self.stackCount = -1
self.trackbarMarginX = 14
self._render = Render()
self._render._internal = self
def isMouseButton(self, theButton, theQuery):
aRet = False
if theQuery == CLICK or theQuery == UP:
aRet = theButton.justReleased
elif theQuery == DOWN:
aRet = theButton.justPressed
elif theQuery == IS_DOWN:
aRet = theButton.pressed
return aRet
def mouseW(self, theWindowName = ''):
"""
Return the last position of the mouse.
\param theWindowName name of the window whose mouse cursor will be used. If nothing is informed (default), the function will return the position of the mouse cursor for the default window (the one informed in `cvui::init()`).
\return a point containing the position of the mouse cursor in the speficied window.
"""
return self.getContext(theWindowName).mouse.position
def mouseQ(self, theQuery):
"""
Query the mouse for events, e.g. "is any button down now?". Available queries are:
* `cvui::DOWN`: any mouse button was pressed. `cvui::mouse()` returns `true` for a single frame only.
* `cvui::UP`: any mouse button was released. `cvui::mouse()` returns `true` for a single frame only.
* `cvui::CLICK`: any mouse button was clicked (went down then up, no matter the amount of frames in between). `cvui::mouse()` returns `true` for a single frame only.
* `cvui::IS_DOWN`: any mouse button is currently pressed. `cvui::mouse()` returns `true` for as long as the button is down/pressed.
It is easier to think of this function as the answer to a questions. For instance, asking if any mouse button went down:
```
if (cvui::mouse(cvui::DOWN)) {
// Any mouse button just went down.
}
```
The window whose mouse will be queried depends on the context. If `cvui::mouse(query)` is being called after
`cvui::context()`, the window informed in the context will be queried. If no context is available, the default
window (informed in `cvui::init()`) will be used.
Parameters
----------
theQuery: int
Integer describing the intended mouse query. Available queries are `cvui::DOWN`, `cvui::UP`, `cvui::CLICK`, and `cvui::IS_DOWN`.
\sa mouse(const cv::String&)
\sa mouse(const cv::String&, int)
\sa mouse(const cv::String&, int, int)
\sa mouse(int, int)
"""
return self.mouseWQ('', theQuery)
def mouseWQ(self, theWindowName, theQuery):
"""
Query the mouse for events in a particular window. This function behave exactly like `cvui::mouse(int theQuery)`
with the difference that queries are targeted at a particular window.
\param theWindowName name of the window that will be queried.
\param theQuery an integer describing the intended mouse query. Available queries are `cvui::DOWN`, `cvui::UP`, `cvui::CLICK`, and `cvui::IS_DOWN`.
\sa mouse(const cv::String&)
\sa mouse(const cv::String&, int, int)
\sa mouse(int, int)
\sa mouse(int)
"""
aButton = self.getContext(theWindowName).mouse.anyButton
aRet = self.isMouseButton(aButton, theQuery)
return aRet
def mouseBQ(self, theButton, theQuery):
"""
Query the mouse for events in a particular button. This function behave exactly like `cvui::mouse(int theQuery)`,
with the difference that queries are targeted at a particular mouse button instead.
\param theButton an integer describing the mouse button to be queried. Possible values are `cvui::LEFT_BUTTON`, `cvui::MIDDLE_BUTTON` and `cvui::LEFT_BUTTON`.
\param theQuery an integer describing the intended mouse query. Available queries are `cvui::DOWN`, `cvui::UP`, `cvui::CLICK`, and `cvui::IS_DOWN`.
\sa mouse(const cv::String&)
\sa mouse(const cv::String&, int, int)
\sa mouse(int)
"""
return self.mouseWBQ('', theButton, theQuery)
def mouseWBQ(self, theWindowName, theButton, theQuery):
"""
Query the mouse for events in a particular button in a particular window. This function behave exactly
like `cvui::mouse(int theButton, int theQuery)`, with the difference that queries are targeted at
a particular mouse button in a particular window instead.
\param theWindowName name of the window that will be queried.
\param theButton an integer describing the mouse button to be queried. Possible values are `cvui::LEFT_BUTTON`, `cvui::MIDDLE_BUTTON` and `cvui::LEFT_BUTTON`.
\param theQuery an integer describing the intended mouse query. Available queries are `cvui::DOWN`, `cvui::UP`, `cvui::CLICK`, and `cvui::IS_DOWN`.
"""
if theButton != RIGHT_BUTTON and theButton != MIDDLE_BUTTON and theButton != LEFT_BUTTON:
__internal.error(6, 'Invalid mouse button. Are you using one of the available: cvui.{RIGHT,MIDDLE,LEFT}_BUTTON ?')
aButton = self.getContext(theWindowName).mouse.buttons[theButton]
aRet = self.isMouseButton(aButton, theQuery)
return aRet
def init(self, theWindowName, theDelayWaitKey):
self.defaultContext = theWindowName
self.currentContext = theWindowName
self.delayWaitKey = theDelayWaitKey
self.lastKeyPressed = -1
def bitsetHas(self, theBitset, theValue):
return (theBitset & theValue) != 0
def error(self, theId, theMessage):
print('[CVUI] Fatal error (code ', theId, '): ', theMessage)
cv2.waitKey(100000)
sys.exit(-1)
def getContext(self, theWindowName = ''):
if len(theWindowName) != 0:
# Get context in particular
return self.contexts[theWindowName]
elif len(self.currentContext) != 0:
# No window provided, return currently active context.
return self.contexts[self.currentContext]
elif len(self.defaultContext) != 0:
# We have no active context, so let's use the default one.
return self.contexts[self.defaultContext]
else:
# Apparently we have no window at all! <o>
# This should not happen. Probably cvui::init() was never called.
self.error(5, 'Unable to read context. Did you forget to call cvui.init()?')
def updateLayoutFlow(self, theBlock, theSize):
if theBlock.type == ROW:
aValue = theSize.width + theBlock.padding
theBlock.anchor.x += aValue
theBlock.fill.width += aValue
theBlock.fill.height = max(theSize.height, theBlock.fill.height)
elif theBlock.type == COLUMN:
aValue = theSize.height + theBlock.padding
theBlock.anchor.y += aValue
theBlock.fill.height += aValue
theBlock.fill.width = max(theSize.width, theBlock.fill.width)
def blockStackEmpty(self):
return self.stackCount == -1
def topBlock(self):
if self.stackCount < 0:
self.error(3, 'You are using a function that should be enclosed by begin*() and end*(), but you probably forgot to call begin*().')
return self.stack[self.stackCount]
def pushBlock(self):
self.stackCount += 1
return self.stack[self.stackCount]
def popBlock(self):
# Check if there is anything to be popped out from the stack.
if self.stackCount < 0:
self.error(1, 'Mismatch in the number of begin*()/end*() calls. You are calling one more than the other.')
aIndex = self.stackCount
self.stackCount -= 1
return self.stack[aIndex]
def createLabel(self, theLabel):
i = 0
aBefore = ''
aAfter = ''
aLabel = Label()
aLabel.hasShortcut = False
aLabel.shortcut = 0
aLabel.textBeforeShortcut = ''
aLabel.textAfterShortcut = ''
while i < len(theLabel):
c = theLabel[i]
if c == '&' and i < len(theLabel) - 1:
aLabel.hasShortcut = True
aLabel.shortcut = theLabel[i + 1]
i += 1
elif aLabel.hasShortcut == False:
aBefore += c
else:
aAfter += c
i += 1
aLabel.textBeforeShortcut = aBefore
aLabel.textAfterShortcut = aAfter
return aLabel
def text(self, theBlock, theX, theY, theText, theFontScale, theColor, theUpdateLayout):
aSizeInfo, aBaseline = cv2.getTextSize(theText, cv2.FONT_HERSHEY_SIMPLEX, theFontScale, 1)
aTextSize = Size(aSizeInfo[0], aSizeInfo[1])
aPos = Point(theX, theY + aTextSize.height)
self._render.text(theBlock, theText, aPos, theFontScale, theColor)
if theUpdateLayout:
# Add an extra pixel to the height to overcome OpenCV font size problems.
aTextSize.height += 1
self.updateLayoutFlow(theBlock, aTextSize)
def counter(self, theBlock, theX, theY, theValue, theStep, theFormat):
aContentArea = Rect(theX + 22, theY, 48, 22)
if self.buttonWH(theBlock, theX, theY, 22, 22, '-', False):
theValue[0] -= theStep
aText = theFormat % theValue[0]
self._render.counter(theBlock, aContentArea, aText)
if self.buttonWH(theBlock, aContentArea.x + aContentArea.width, theY, 22, 22, "+", False):
theValue[0] += theStep
# Update the layout flow
aSize = Size(22 * 2 + aContentArea.width, aContentArea.height)
self.updateLayoutFlow(theBlock, aSize)
return theValue[0]
def checkbox(self, theBlock, theX, theY, theLabel, theState, theColor):
aMouse = self.getContext().mouse
aRect = Rect(theX, theY, 15, 15)
aSizeInfo, aBaseline = cv2.getTextSize(theLabel, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)
aTextSize = Rect(0, 0, aSizeInfo[0], aSizeInfo[1])
aHitArea = Rect(theX, theY, aRect.width + aTextSize.width + 6, aRect.height)
aMouseIsOver = aHitArea.contains(aMouse.position)
if aMouseIsOver:
self._render.checkbox(theBlock, OVER, aRect)
if aMouse.anyButton.justReleased:
theState[0] = not theState[0]
else:
self._render.checkbox(theBlock, OUT, aRect)
self._render.checkboxLabel(theBlock, aRect, theLabel, aTextSize, theColor)
if theState[0]:
self._render.checkboxCheck(theBlock, aRect)
# Update the layout flow
aSize = Size(aHitArea.width, aHitArea.height)
self.updateLayoutFlow(theBlock, aSize)
return theState[0]
def clamp01(self, theValue):
theValue = 1. if theValue > 1. else theValue
theValue = 0. if theValue < 0. else theValue
return theValue
def trackbarForceValuesAsMultiplesOfSmallStep(self, theParams, theValue):
if self.bitsetHas(theParams.options, TRACKBAR_DISCRETE) and theParams.step != 0.:
k = float(theValue[0] - theParams.min) / theParams.step
k = round(k)
theValue[0] = theParams.min + theParams.step * k
def trackbarXPixelToValue(self, theParams, theBounding, thePixelX):
aRatio = float(thePixelX - (theBounding.x + self.trackbarMarginX)) / (theBounding.width - 2 * self.trackbarMarginX)
aRatio = self.clamp01(aRatio)
aValue = theParams.min + aRatio * (theParams.max - theParams.min)
return aValue
def trackbarValueToXPixel(self, theParams, theBounding, theValue):
aRatio = float(theValue - theParams.min) / (theParams.max - theParams.min)
aRatio = self.clamp01(aRatio)
aPixelsX = theBounding.x + self.trackbarMarginX + aRatio * (theBounding.width - 2 * self.trackbarMarginX)
return int(aPixelsX)
def iarea(self, theX, theY, theWidth, theHeight):
aMouse = self.getContext().mouse
# By default, return that the mouse is out of the interaction area.
aRet = OUT
# Check if the mouse is over the interaction area.
aMouseIsOver = Rect(theX, theY, theWidth, theHeight).contains(aMouse.position)
if aMouseIsOver:
if aMouse.anyButton.pressed:
aRet = DOWN
else:
aRet = OVER
# Tell if the button was clicked or not
if aMouseIsOver and aMouse.anyButton.justReleased:
aRet = CLICK
return aRet
def buttonWH(self, theBlock, theX, theY, theWidth, theHeight, theLabel, theUpdateLayout):
# Calculate the space that the label will fill
aSizeInfo, aBaseline = cv2.getTextSize(theLabel, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)
aTextSize = Rect(0, 0, aSizeInfo[0], aSizeInfo[1])
# Make the button big enough to house the label
aRect = Rect(theX, theY, theWidth, theHeight)
# Render the button according to mouse interaction, e.g. OVER, DOWN, OUT.
aStatus = self.iarea(theX, theY, aRect.width, aRect.height)
self._render.button(theBlock, aStatus, aRect, theLabel)
self._render.buttonLabel(theBlock, aStatus, aRect, theLabel, aTextSize)
# Update the layout flow according to button size
# if we were told to update.
if theUpdateLayout:
aSize = Size(theWidth, theHeight)
self.updateLayoutFlow(theBlock, aSize)
aWasShortcutPressed = False
# Handle keyboard shortcuts
if self.lastKeyPressed != -1:
aLabel = self.createLabel(theLabel)
if aLabel.hasShortcut and aLabel.shortcut.lower() == chr(self.lastKeyPressed).lower():
aWasShortcutPressed = True
# Return true if the button was clicked
return aStatus == CLICK or aWasShortcutPressed
def button(self, theBlock, theX, theY, theLabel):
# Calculate the space that the label will fill
aSizeInfo, aBaseline = cv2.getTextSize(theLabel, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)
aTextSize = Rect(0, 0, aSizeInfo[0], aSizeInfo[1])
# Create a button based on the size of the text
return self.buttonWH(theBlock, theX, theY, aTextSize.width + 30, aTextSize.height + 18, theLabel, True)
def buttonI(self, theBlock, theX, theY, theIdle, theOver, theDown, theUpdateLayout):
aIdleRows = theIdle.shape[0]
aIdleCols = theIdle.shape[1]
aRect = Rect(theX, theY, aIdleCols, aIdleRows)
aStatus = self.iarea(theX, theY, aRect.width, aRect.height)
if aStatus == OUT: self._render.image(theBlock, aRect, theIdle)
elif aStatus == OVER: self._render.image(theBlock, aRect, theOver)
elif aStatus == DOWN: self._render.image(theBlock, aRect, theDown)
# Update the layout flow according to button size
# if we were told to update.
if theUpdateLayout:
aSize = Size(aRect.width, aRect.height)
self.updateLayoutFlow(theBlock, aSize)
# Return true if the button was clicked
return aStatus == CLICK
def image(self, theBlock, theX, theY, theImage):
aImageRows = theImage.shape[0]
aImageCols = theImage.shape[1]
aRect = Rect(theX, theY, aImageCols, aImageRows)
# TODO: check for render outside the frame area
self._render.image(theBlock, aRect, theImage)
# Update the layout flow according to image size
aSize = Size(aImageCols, aImageRows)
self.updateLayoutFlow(theBlock, aSize)
def trackbar(self, theBlock, theX, theY, theWidth, theValue, theParams):
aMouse = self.getContext().mouse
aContentArea = Rect(theX, theY, theWidth, 45)
aMouseIsOver = aContentArea.contains(aMouse.position)
aValue = theValue[0]
self._render.trackbar(theBlock, OVER if aMouseIsOver else OUT, aContentArea, theValue[0], theParams)
if aMouse.anyButton.pressed and aMouseIsOver:
theValue[0] = self.trackbarXPixelToValue(theParams, aContentArea, aMouse.position.x)
if self.bitsetHas(theParams.options, TRACKBAR_DISCRETE):
self.trackbarForceValuesAsMultiplesOfSmallStep(theParams, theValue)
# Update the layout flow
# TODO: use aSize = aContentArea.size()?
self.updateLayoutFlow(theBlock, aContentArea)
return theValue[0] != aValue
def window(self, theBlock, theX, theY, theWidth, theHeight, theTitle):
aTitleBar = Rect(theX, theY, theWidth, 20)
aContent = Rect(theX, theY + aTitleBar.height, theWidth, theHeight - aTitleBar.height)
self._render.window(theBlock, aTitleBar, aContent, theTitle)
# Update the layout flow
aSize = Size(theWidth, theHeight)
self.updateLayoutFlow(theBlock, aSize)
def rect(self, theBlock, theX, theY, theWidth, theHeight, theBorderColor, theFillingColor):
aAnchor = Point(theX, theY);
aRect = Rect(theX, theY, theWidth, theHeight);
aRect.x = aAnchor.x + aRect.width if aRect.width < 0 else aAnchor.x
aRect.y = aAnchor.y + aRect.height if aRect.height < 0 else aAnchor.y
aRect.width = abs(aRect.width)
aRect.height = abs(aRect.height)
self._render.rect(theBlock, aRect, theBorderColor, theFillingColor)
# Update the layout flow
aSize = Size(aRect.width, aRect.height)
self.updateLayoutFlow(theBlock, aSize)
def sparkline(self, theBlock, theValues, theX, theY, theWidth, theHeight, theColor):
aRect = Rect(theX, theY, theWidth, theHeight)
aHowManyValues = len(theValues)
if (aHowManyValues >= 2):
aMin,aMax = self.findMinMax(theValues)
self._render.sparkline(theBlock, theValues, aRect, aMin, aMax, theColor)
else:
self.text(theBlock, theX, theY, 'No data.' if aHowManyValues == 0 else 'Insufficient data points.', 0.4, 0xCECECE, False)
# Update the layout flow
aSize = Size(theWidth, theHeight)
self.updateLayoutFlow(theBlock, aSize)
def hexToScalar(self, theColor):
aAlpha = (theColor >> 24) & 0xff
aRed = (theColor >> 16) & 0xff
aGreen = (theColor >> 8) & 0xff
aBlue = theColor & 0xff
return (aBlue, aGreen, aRed, aAlpha)
def isString(self, theObj):
return isinstance(theObj, basestring if _IS_PY2 else str)
def begin(self, theType, theWhere, theX, theY, theWidth, theHeight, thePadding):
aBlock = self.pushBlock()
aBlock.where = theWhere
aBlock.rect.x = theX
aBlock.rect.y = theY
aBlock.rect.width = theWidth
aBlock.rect.height = theHeight
aBlock.fill = aBlock.rect
aBlock.fill.width = 0
aBlock.fill.height = 0
aBlock.anchor.x = theX
aBlock.anchor.y = theY
aBlock.padding = thePadding
aBlock.type = theType
def end(self, theType):
aBlock = self.popBlock()
if aBlock.type != theType:
self.error(4, 'Calling wrong type of end*(). E.g. endColumn() instead of endRow(). Check if your begin*() calls are matched with their appropriate end*() calls.')
# If we still have blocks in the stack, we must update
# the current top with the dimensions that were filled by
# the newly popped block.
if self.blockStackEmpty() == False:
aTop = self.topBlock()
aSize = Size()
# If the block has rect.width < 0 or rect.heigth < 0, it means the
# user don't want to calculate the block's width/height. It's up to
# us do to the math. In that case, we use the block's fill rect to find
# out the occupied space. If the block's width/height is greater than
# zero, then the user is very specific about the desired size. In that
# case, we use the provided width/height, no matter what the fill rect
# actually is.
aSize.width = aBlock.fill.width if aBlock.rect.width < 0 else aBlock.rect.width
aSize.height = aBlock.fill.height if aBlock.rect.height < 0 else aBlock.rect.height
self.updateLayoutFlow(aTop, aSize)
# Find the min and max values of a vector
def findMinMax(self, theValues):
aMin = theValues[0]
aMax = theValues[0]
for aValue in theValues:
if aValue < aMin:
aMin = aValue
if aValue > aMax:
aMax = aValue
return (aMin, aMax)
# Class that contains all rendering methods.
class Render:
_internal = None
def rectangle(self, theWhere, theShape, theColor, theThickness = 1, theLineType = CVUI_ANTIALISED):
aStartPoint = (int(theShape.x), int(theShape.y))
aEndPoint = (int(theShape.x + theShape.width), int(theShape.y + theShape.height))
cv2.rectangle(theWhere, aStartPoint, aEndPoint, theColor, theThickness, theLineType)
def text(self, theBlock, theText, thePos, theFontScale, theColor):
aPosition = (int(thePos.x), int(thePos.y))
cv2.putText(theBlock.where, theText, aPosition, cv2.FONT_HERSHEY_SIMPLEX, theFontScale, self._internal.hexToScalar(theColor), 1, cv2.LINE_AA)
def counter(self, theBlock, theShape, theValue):
self.rectangle(theBlock.where, theShape, (0x29, 0x29, 0x29), CVUI_FILLED) # fill
self.rectangle(theBlock.where, theShape, (0x45, 0x45, 0x45)) # border
aSizeInfo, aBaseline = cv2.getTextSize(theValue, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)
aTextSize = Rect(0, 0, aSizeInfo[0], aSizeInfo[1])
aPos = Point(theShape.x + theShape.width / 2 - aTextSize.width / 2, theShape.y + aTextSize.height / 2 + theShape.height / 2)
cv2.putText(theBlock.where, theValue, (int(aPos.x), int(aPos.y)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0xCE, 0xCE, 0xCE), 1, CVUI_ANTIALISED)
def button(self, theBlock, theState, theShape, theLabel):
# Outline
self.rectangle(theBlock.where, theShape, (0x29, 0x29, 0x29))
# Border
theShape.x += 1
theShape.y +=1
theShape.width -= 2
theShape.height -= 2
self.rectangle(theBlock.where, theShape, (0x4A, 0x4A, 0x4A))
# Inside
theShape.x += 1
theShape.y +=1
theShape.width -= 2
theShape.height -= 2
self.rectangle(theBlock.where, theShape, (0x42, 0x42, 0x42) if theState == OUT else ((0x52, 0x52, 0x52) if theState == OVER else (0x32, 0x32, 0x32)), CVUI_FILLED)
def image(self, theBlock, theRect, theImage):
theBlock.where[theRect.y: theRect.y + theRect.height, theRect.x: theRect.x + theRect.width] = theImage
def putText(self, theBlock, theState, theColor, theText, thePosition):
aFontScale = 0.39 if theState == DOWN else 0.4
aTextSize = Rect()
if theText != '':
aPosition = (int(thePosition.x), int(thePosition.y))
cv2.putText(theBlock.where, theText, aPosition, cv2.FONT_HERSHEY_SIMPLEX, aFontScale, theColor, 1, CVUI_ANTIALISED)
aSizeInfo, aBaseline = cv2.getTextSize(theText, cv2.FONT_HERSHEY_SIMPLEX, aFontScale, 1)
aTextSize = Rect(0, 0, aSizeInfo[0], aSizeInfo[1])
return aTextSize.width
def putTextCentered(self, theBlock, thePosition, theText):
aFontScale = 0.3
aSizeInfo, aBaseline = cv2.getTextSize(theText, cv2.FONT_HERSHEY_SIMPLEX, aFontScale, 1)
aTextSize = Rect(0, 0, aSizeInfo[0], aSizeInfo[1])
aPositionDecentered = Point(thePosition.x - aTextSize.width / 2, thePosition.y)
cv2.putText(theBlock.where, theText, (int(aPositionDecentered.x), int(aPositionDecentered.y)), cv2.FONT_HERSHEY_SIMPLEX, aFontScale, (0xCE, 0xCE, 0xCE), 1, CVUI_ANTIALISED)
return aTextSize.width
def buttonLabel(self, theBlock, theState, theRect, theLabel, theTextSize):
aPos = Point(theRect.x + theRect.width / 2 - theTextSize.width / 2, theRect.y + theRect.height / 2 + theTextSize.height / 2)
aColor = (0xCE, 0xCE, 0xCE)
aLabel = self._internal.createLabel(theLabel)
if aLabel.hasShortcut == False:
self.putText(theBlock, theState, aColor, theLabel, aPos);
else:
aWidth = self.putText(theBlock, theState, aColor, aLabel.textBeforeShortcut, aPos)
aStart = aPos.x + aWidth
aPos.x += aWidth
aShortcut = ''
aShortcut += aLabel.shortcut
aWidth = self.putText(theBlock, theState, aColor, aShortcut, aPos)
aEnd = aStart + aWidth
aPos.x += aWidth
self.putText(theBlock, theState, aColor, aLabel.textAfterShortcut, aPos)
cv2.line(theBlock.where, (int(aStart), int(aPos.y + 3)), (int(aEnd), int(aPos.y + 3)), aColor, 1, CVUI_ANTIALISED)
def trackbarHandle(self, theBlock, theState, theShape, theValue, theParams, theWorkingArea):
aBarTopLeft = Point(theWorkingArea.x, theWorkingArea.y + theWorkingArea.height / 2)
aBarHeight = 7
# Draw the rectangle representing the handle
aPixelX = self._internal.trackbarValueToXPixel(theParams, theShape, theValue)
aIndicatorWidth = 3
aIndicatorHeight = 4
aPoint1 = Point(aPixelX - aIndicatorWidth, aBarTopLeft.y - aIndicatorHeight)
aPoint2 = Point(aPixelX + aIndicatorWidth, aBarTopLeft.y + aBarHeight + aIndicatorHeight)
aRect = Rect(aPoint1.x, aPoint1.y, aPoint2.x - aPoint1.x, aPoint2.y - aPoint1.y)
aFillColor = 0x525252 if theState == OVER else 0x424242
self.rect(theBlock, aRect, 0x212121, 0x212121)
aRect.x += 1
aRect.y += 1
aRect.width -= 2
aRect.height -= 2
self.rect(theBlock, aRect, 0x515151, aFillColor)
aShowLabel = self._internal.bitsetHas(theParams.options, TRACKBAR_HIDE_VALUE_LABEL) == False
# Draw the handle label
if aShowLabel:
aTextPos = Point(aPixelX, aPoint2.y + 11)
aText = theParams.labelFormat % theValue
self.putTextCentered(theBlock, aTextPos, aText)
def trackbarPath(self, theBlock, theState, theShape, theValue, theParams, theWorkingArea):
aBarHeight = 7
aBarTopLeft = Point(theWorkingArea.x, theWorkingArea.y + theWorkingArea.height / 2)
aRect = Rect(aBarTopLeft.x, aBarTopLeft.y, theWorkingArea.width, aBarHeight)
aBorderColor = 0x4e4e4e if theState == OVER else 0x3e3e3e
self.rect(theBlock, aRect, aBorderColor, 0x292929)
cv2.line(theBlock.where, (int(aRect.x + 1), int(aRect.y + aBarHeight - 2)), (int(aRect.x + aRect.width - 2), int(aRect.y + aBarHeight - 2)), (0x0e, 0x0e, 0x0e))
def trackbarSteps(self, theBlock, theState, theShape, theValue, theParams, theWorkingArea):
aBarTopLeft = Point(theWorkingArea.x, theWorkingArea.y + theWorkingArea.height / 2)
aColor = (0x51, 0x51, 0x51)
aDiscrete = self._internal.bitsetHas(theParams.options, TRACKBAR_DISCRETE)
aFixedStep = theParams.step if aDiscrete else (theParams.max - theParams.min) / 20
# TODO: check min, max and step to prevent infinite loop.
aValue = theParams.min
while aValue <= theParams.max:
aPixelX = int(self._internal.trackbarValueToXPixel(theParams, theShape, aValue))
aPoint1 = (aPixelX, int(aBarTopLeft.y))
aPoint2 = (aPixelX, int(aBarTopLeft.y - 3))
cv2.line(theBlock.where, aPoint1, aPoint2, aColor)
aValue += aFixedStep
def trackbarSegmentLabel(self, theBlock, theShape, theParams, theValue, theWorkingArea, theShowLabel):
aColor = (0x51, 0x51, 0x51)
aBarTopLeft = Point(theWorkingArea.x, theWorkingArea.y + theWorkingArea.height / 2)
aPixelX = int(self._internal.trackbarValueToXPixel(theParams, theShape, theValue))
aPoint1 = (aPixelX, int(aBarTopLeft.y))
aPoint2 = (aPixelX, int(aBarTopLeft.y - 8))
cv2.line(theBlock.where, aPoint1, aPoint2, aColor)
if theShowLabel:
aText = theParams.labelFormat % theValue
aTextPos = Point(aPixelX, aBarTopLeft.y - 11)
self.putTextCentered(theBlock, aTextPos, aText)
def trackbarSegments(self, theBlock, theState, theShape, theValue, theParams, theWorkingArea):
aSegments = 1 if theParams.segments < 1 else theParams.segments
aSegmentLength = float(theParams.max - theParams.min) / aSegments
aHasMinMaxLabels = self._internal.bitsetHas(theParams.options, TRACKBAR_HIDE_MIN_MAX_LABELS) == False
# Render the min value label
self.trackbarSegmentLabel(theBlock, theShape, theParams, theParams.min, theWorkingArea, aHasMinMaxLabels)
# Draw large steps and labels
aHasSegmentLabels = self._internal.bitsetHas(theParams.options, TRACKBAR_HIDE_SEGMENT_LABELS) == False
# TODO: check min, max and step to prevent infinite loop.
aValue = theParams.min
while aValue <= theParams.max:
self.trackbarSegmentLabel(theBlock, theShape, theParams, aValue, theWorkingArea, aHasSegmentLabels)
aValue += aSegmentLength
# Render the max value label
self.trackbarSegmentLabel(theBlock, theShape, theParams, theParams.max, theWorkingArea, aHasMinMaxLabels)
def trackbar(self, theBlock, theState, theShape, theValue, theParams):
aWorkingArea = Rect(theShape.x + self._internal.trackbarMarginX, theShape.y, theShape.width - 2 * self._internal.trackbarMarginX, theShape.height)
self.trackbarPath(theBlock, theState, theShape, theValue, theParams, aWorkingArea)
aHideAllLabels = self._internal.bitsetHas(theParams.options, TRACKBAR_HIDE_LABELS)
aShowSteps = self._internal.bitsetHas(theParams.options, TRACKBAR_HIDE_STEP_SCALE) == False
if aShowSteps and aHideAllLabels == False:
self.trackbarSteps(theBlock, theState, theShape, theValue, theParams, aWorkingArea)
if aHideAllLabels == False:
self.trackbarSegments(theBlock, theState, theShape, theValue, theParams, aWorkingArea)
self.trackbarHandle(theBlock, theState, theShape, theValue, theParams, aWorkingArea)
def checkbox(self, theBlock, theState, theShape):
# Outline
self.rectangle(theBlock.where, theShape, (0x63, 0x63, 0x63) if theState == OUT else (0x80, 0x80, 0x80))
# Border
theShape.x += 1
theShape.y+=1
theShape.width -= 2
theShape.height -= 2
self.rectangle(theBlock.where, theShape, (0x17, 0x17, 0x17))
# Inside
theShape.x += 1
theShape.y += 1
theShape.width -= 2
theShape.height -= 2
self.rectangle(theBlock.where, theShape, (0x29, 0x29, 0x29), CVUI_FILLED)
def checkboxLabel(self, theBlock, theRect, theLabel, theTextSize, theColor):
aPos = Point(theRect.x + theRect.width + 6, theRect.y + theTextSize.height + theRect.height / 2 - theTextSize.height / 2 - 1)
self.text(theBlock, theLabel, aPos, 0.4, theColor)
def checkboxCheck(self, theBlock, theShape):
theShape.x += 1
theShape.y += 1
theShape.width -= 2
theShape.height -= 2
self.rectangle(theBlock.where, theShape, (0xFF, 0xBF, 0x75), CVUI_FILLED)
def window(self, theBlock, theTitleBar, theContent, theTitle):
aTransparecy = False
aAlpha = 0.3
aOverlay = theBlock.where.copy()
# Render borders in the title bar
self.rectangle(theBlock.where, theTitleBar, (0x4A, 0x4A, 0x4A));
# Render the inside of the title bar
theTitleBar.x += 1
theTitleBar.y += 1
theTitleBar.width -= 2
theTitleBar.height -= 2
self.rectangle(theBlock.where, theTitleBar, (0x21, 0x21, 0x21), CVUI_FILLED);
# Render title text.
aPos = Point(theTitleBar.x + 5, theTitleBar.y + 12)
cv2.putText(theBlock.where, theTitle, (int(aPos.x), int(aPos.y)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0xCE, 0xCE, 0xCE), 1, CVUI_ANTIALISED)
# Render borders of the body
self.rectangle(theBlock.where, theContent, (0x4A, 0x4A, 0x4A))
# Render the body filling.
theContent.x += 1
theContent.y += 1
theContent.width -= 2
theContent.height -= 2
self.rectangle(aOverlay, theContent, (0x31, 0x31, 0x31), CVUI_FILLED)
if aTransparecy:
np.copyto(aOverlay, theBlock.where) # theBlock.where.copyTo(aOverlay);
self.rectangle(aOverlay, theContent, (0x31, 0x31, 0x31), CVUI_FILLED)
cv2.addWeighted(aOverlay, aAlpha, theBlock.where, 1.0 - aAlpha, 0.0, theBlock.where)
else:
self.rectangle(theBlock.where, theContent, (0x31, 0x31, 0x31), CVUI_FILLED)
def rect(self, theBlock, thePos, theBorderColor, theFillingColor):
aBorderColor = self._internal.hexToScalar(theBorderColor)
aFillingColor = self._internal.hexToScalar(theFillingColor)
aHasFilling = aFillingColor[3] != 0xff
if aHasFilling:
self.rectangle(theBlock.where, thePos, aFillingColor, CVUI_FILLED, CVUI_ANTIALISED)
# Render the border
self.rectangle(theBlock.where, thePos, aBorderColor)
def sparkline(self, theBlock, theValues, theRect, theMin, theMax, theColor):
aSize = len(theValues)
i = 0
delta = theMax - theMin
aScale = 1 if delta == 0 else delta
aGap = float(theRect.width) / aSize
aPosX = theRect.x
while i <= aSize - 2:
x = aPosX;