-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathjustpyplot.py
More file actions
1862 lines (1579 loc) · 62.7 KB
/
Copy pathjustpyplot.py
File metadata and controls
1862 lines (1579 loc) · 62.7 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
# Copyright (c) 2023 bedbad
import numpy as np
from typing import Tuple, Optional
import functools
import importlib
from justpyplot.textrender import vectorized_text
__all__ = [
'plot', # Main plotting function
'blend', # Core blending function for numpy arrays
'blend2PIL', # Specialized blending for Jupyter/PIL output
'plot_at', # Plot directly onto existing array
'plot1_at', # Plot 1D array onto existing array
]
# Attempt to import optional modules
def is_module_available(module_name):
try:
importlib.import_module(module_name)
return True
except ImportError:
return False
cv2_available = is_module_available("cv2")
perf_timer_available = is_module_available("perf_timer")
PIL_available = is_module_available("PIL")
if cv2_available:
import cv2
if perf_timer_available:
from perf_timer import PerfTimer
perf_timers = {
'_veclinesperf': PerfTimer('vectorized lines render'),
'_plotperf': PerfTimer('full plot rendering')
}
else:
perf_timers = {}
def debug_performance(perf_name: str):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if perf_name in perf_timers:
with perf_timers[perf_name]:
result = func(*args, **kwargs)
return result
else:
return func(*args, **kwargs)
return wrapper
return decorator
def adjust_values(values, grid_shape):
"""
Adjusts the values to fill the grid box maximally.
Parameters:
values (ndarray): The input array of values.
grid_shape (tuple): The shape of the grid box.
Returns:
ndarray: The adjusted values.
ndarray: The bounds of the values.
ndarray: The scaling factor.
ndarray: The median degree of the values.
"""
# Calculate the bounds for both rows of the array values
bounds = np.array([np.min(values, axis=1), np.max(values, axis=1)])
# Calculate the range of the values
value_range = bounds[1] - bounds[0]
value_range[value_range == 0] = 1
# Calculate the scaling factor
scale = np.array(grid_shape) / value_range
# Adjust the values to fill the grid box maximally
adjusted_values = (values - bounds[0, :, np.newaxis]) * scale[:, np.newaxis]
# Calculate the median degree for values in both rows and round to the nearest whole number
median_degree = np.round(np.median(values, axis=1)).astype(int)
return adjusted_values, bounds, scale, median_degree
def adjust_values_maxlen(values, grid_shape, max_len):
"""
Adjusts the values array to a maximum length and scales it to fit a grid box.
Parameters:
values (ndarray): The input array of values.
grid_shape (tuple): The shape of the grid box.
max_len (int): The maximum length of the values array.
Returns:
ndarray: The adjusted values array.
ndarray: The bounds of the values array.
ndarray: The scaling factor.
ndarray: The median degree of the values array.
"""
# Calculate the bounds for both rows of the array values
ybounds = np.array([np.min(values[1, :]), np.max(values[1, :])])
values = values[:, -max_len:]
xbounds = np.array([np.min(values[0]), np.max(values[0])])
bounds = np.stack([xbounds, ybounds], axis=1)
# Calculate the range of the values
value_range = np.array([xbounds[1] - xbounds[0], ybounds[1] - ybounds[0]])
median_degree = np.array([0, 0])
if value_range[0] == 0:
value_range[0] = values[0]
median_degree[0] = 0
if value_range[1] == 0:
value_range[1] = values[1]
median_degree[1] = 0
if value_range[0] and value_range[1]:
median_degree = np.round(np.log10(np.median(np.abs(values), axis=1))).astype(
int
)
# Calculate the scaling factor
scale = np.array(grid_shape[::-1]) / value_range
# Adjust the values to fill the grid box maximally
adjusted_values = (values - bounds[0, :, np.newaxis]) * (scale[:, np.newaxis])
# Calculate the median degree for values in both rows and round to the nearest whole number
return adjusted_values, bounds, scale, median_degree
def vectorized_line(y0, x0, y1, x1, canvas_size, thickness):
"""
Generate a boolean mask representing a vectorized line on a canvas.
Parameters:
y0 (int): The y-coordinate of the starting point of the line.
x0 (int): The x-coordinate of the starting point of the line.
y1 (int): The y-coordinate of the ending point of the line.
x1 (int): The x-coordinate of the ending point of the line.
canvas_size (tuple): The size of the canvas as a tuple (height, width).
thickness (int): The thickness of the line.
Returns:
numpy.ndarray: A boolean mask representing the line on the canvas.
"""
# Create an array of distances
num_points = max(np.max(abs(x1 - x0)), np.max(abs(y1 - y0))) + 1
t = np.linspace(0, 1, num_points)
# Create 2D arrays for x and y coordinates
x = (x0 + np.outer(t, (x1 - x0))).astype(int)
y = (y0 + np.outer(t, (y1 - y0))).astype(int)
# Create a boolean mask with the size of the canvas and an additional dimension for t
mask = np.zeros(canvas_size, dtype=bool)
# Set the corresponding positions to True
mask[y.ravel(), x.ravel()] = True
return mask
@debug_performance('_veclinesperf')
def vectorized_lines(y0, x0, y1, x1, img_array, clr=(0, 0, 255)):
"""
Draw vectorized lines on an image array.
Parameters:
y0 (array-like): Starting y-coordinates of the lines.
x0 (array-like): Starting x-coordinates of the lines.
y1 (array-like): Ending y-coordinates of the lines.
x1 (array-like): Ending x-coordinates of the lines.
img_array (ndarray): Image array on which the lines will be drawn.
clr (tuple, optional): RGB color tuple for the lines. Defaults to (0, 0, 255).
Returns:
ndarray: Image array with the lines drawn.
"""
# Create an array of distances
num_points = max(np.max(abs(x1 - x0)), np.max(abs(y1 - y0))) + 1
t = np.linspace(0, 1, num_points)
# Create 2D arrays for x and y coordinates
x = (x0 + np.outer(t, (x1 - x0))).astype(int)
y = (y0 + np.outer(t, (y1 - y0))).astype(int)
# Set the corresponding positions to clr
img_array[y.ravel(), x.ravel()] = clr
return img_array
@debug_performance('_veclinesperf')
def vectorized_lines_with_thickness(
y0, x0, y1, x1, img_array, thickness, clr=(0, 0, 255)
):
"""
Draw multiple lines with specified thickness on an image array.
This function uses vectorized operations to draw lines between pairs of points
defined by corresponding elements in the x0, y0 (start points) and x1, y1 (end points)
arrays. It modifies the input image array in-place by setting the color of the pixels
along the lines to the specified color.
Parameters:
y0 (np.ndarray): An array of y-coordinates for the start points of the lines.
x0 (np.ndarray): An array of x-coordinates for the start points of the lines.
y1 (np.ndarray): An array of y-coordinates for the end points of the lines.
x1 (np.ndarray): An array of x-coordinates for the end points of the lines.
img_array (np.ndarray): The image array on which to draw the lines. This array will be modified in-place.
thickness (int): The thickness of the lines to be drawn.
clr (tuple): A tuple of three integers representing the color of the lines in BGR (blue, green, red) format.
Returns:
np.ndarray: The modified image array with the lines drawn on it.
Example:
>>> img = np.zeros((100, 100, 3), dtype=np.uint8)
>>> y0 = np.array([10, 20])
>>> x0 = np.array([10, 20])
>>> y1 = np.array([80, 80])
>>> x1 = np.array([80, 30])
>>> vectorized_lines_with_thickness(y0, x0, y1, x1, img, 3, (255, 0, 0))
"""
# Create an array of distances
num_points = max(np.max(abs(x1 - x0)), np.max(abs(y1 - y0))) + 1
t = np.linspace(0, 1, num_points)
# Create 2D arrays for x and y coordinates
x = (x0 + np.outer(t, (x1 - x0))).astype(int)
y = (y0 + np.outer(t, (y1 - y0))).astype(int)
# Create the shift indices
shift_indices = np.arange(-thickness // 2, thickness // 2 + 1)
# Ensure that the shift is broadcastable by adding a new axis to y1 and y0
y1 = y1[:, np.newaxis]
y0 = y0[:, np.newaxis]
x1 = x1[:, np.newaxis]
x0 = x0[:, np.newaxis]
# Create the shifted coordinates
x_shifted = x[..., np.newaxis] + shift_indices * np.sign(x1 - x0)
y_shifted = y[..., np.newaxis] + shift_indices * np.sign(y1 - y0)
# Clip the shifted coordinates to the image boundaries
x_shifted = np.clip(x_shifted, 0, img_array.shape[1] - 1)
y_shifted = np.clip(y_shifted, 0, img_array.shape[0] - 1)
# Flatten the arrays to set the color in the image array
img_array[y_shifted.ravel(), x_shifted.ravel()] = clr
return img_array
def plot2_at(
img_array: np.ndarray,
values: np.array,
offset: Tuple[int, int],
title: str = 'Measuring',
size: Tuple[int, int] = (300, 300),
point_color: Tuple[int, int, int, int] = (0, 0, 255),
r=2,
nticks: int = 16,
grid_color: Tuple[int, int, int, int] = (128, 128, 128),
precision: int = 4,
default_font_size: float = 0.5,
default_font_size_small: float = 0.4,
label_color: Tuple[int, int, int, int] = (0, 0, 255),
scatter=True,
thickness=2,
line_color: Tuple[int, int, int, int] = (0, 0, 255),
max_len: int = 100,
) -> np.ndarray:
"""Plot into a NumPy image array.
Plots given array of `values`, adapting
the plot scale and size to fit the input data.
Plots fast - no single loop in the code, even if you want to connect points with
line segments, measured 20-100x faster then matplotlib.
Useful for overlaying real-time plots on images and video frames.
Args:
img_array: NumPy ndarray to draw the plot on, likely a video frame
values: NumPy 1D array of values to plot over time
title: Plot title string
offset: (x, y) offset tuple for the top-left of plot
size: (width, height) tuple for plot size in pixels
clr: (R, G, B) tuple for plot color
pxdelta: Grid size in pixels
precision: Floating point precision for y-axis labels
default_font_size: Font size for title
default_font_size_small: Font size for axis labels
opacity: Opacity value 0-1 for plot elements
max_len: Maximum history length for values array
Returns:
img_array: Image array with overlaid adaptive plot
Example:
frame = cv2.imread('frame.jpg')
values = sensor_data[-100:]
frame = draw_adaptive_plot(frame, values)
"""
font_size = default_font_size
font_size_small = default_font_size_small
font = cv2.FONT_HERSHEY_SIMPLEX
text_size_title = cv2.getTextSize(title, font, font_size, 1)[0]
margin_ver = int(text_size_title[1] * 2.0)
axlablen = cv2.getTextSize('A' * precision, font, font_size_small, 1)[0][0]
margin_hor = int(axlablen * 1.5)
grid_topleft = np.array((margin_ver, margin_hor))
grid_botright = np.array(size) - grid_topleft
gsize = grid_botright - grid_topleft
gsize2 = gsize - (gsize % nticks)
iota = (gsize - gsize2) / 2
gsize = gsize2
grid_topleft = (grid_topleft + iota).astype(int)
grid_botright = (grid_botright - iota).astype(int)
pxdelta = (gsize // nticks).astype(int)
gh, gw = tuple(gsize)
adjusted_values, bounds, scale, median_degree = adjust_values_maxlen(
values, gsize, max_len=max_len
)
pxdelta = (gsize // nticks).astype(int)
# Adjust the title to include the multiplier
# Draw grid and rectangle with opacity
gtl_img = grid_topleft + offset
gbr_img = grid_botright + offset
title += f', 10^{int(median_degree[1])}'
text_x_title = int(
gtl_img[1] + gw / 2 - cv2.getTextSize(title, font, font_size, 1)[0][0] / 2
)
text_y_title = gtl_img[0] - int(text_size_title[1] * 1.5)
img_array[
gtl_img[0] : gbr_img[0] + 1 : pxdelta[0], gtl_img[1] : gbr_img[1] + 1, :
] = grid_color
img_array[
gtl_img[0] : gbr_img[0] + 1, gtl_img[1] : gbr_img[1] + 1 : pxdelta[1], :
] = grid_color
# Render points
# Create an array of indices
x = gtl_img[1] + (adjusted_values[0, ...]).astype(int)
y = gbr_img[0] - (adjusted_values[1, ...]).astype(int)
# Create a mask for valid indices
valid_mask = (
(gtl_img[0] <= y) & (y <= gbr_img[0]) & (gtl_img[1] <= x) & (x <= gbr_img[1])
)
valsx = x[valid_mask]
valsy = y[valid_mask]
# Create a grid of offsets
x_offset = np.arange(-r, r + 1)
y_offset = np.arange(-r, r + 1)
xx, yy = np.meshgrid(x_offset, y_offset)
# Apply offsets to the original x and y coordinates
xx = xx.ravel() + valsx[:, None]
yy = yy.ravel() + valsy[:, None]
# Flatten the arrays
xx = xx.ravel()
yy = yy.ravel()
# Assign color to the corresponding pixels and the surrounding pixels
img_array[yy, xx] = point_color
if not scatter and values.shape[1] >= 2:
# Create pairs of adjacent points
with _veclinesperf:
img_array = vectorized_lines_with_thickness(
y[:-1],
x[:-1],
y[1:],
x[1:],
img_array,
clr=line_color,
thickness=thickness,
)
# rendering text
n = gsize[0] // (2 * pxdelta[0])
tick_color = label_color
yscale = bounds[1, 1] - bounds[0, 1]
for i in range(n + 1):
# Scale the tick label by the multiplier
tickval = bounds[0, 1] + (yscale / n) * i
dotp = precision - len(str(tickval).split('.')[0])
val = '{:.{}f}'.format(tickval, dotp)
text_size, _ = cv2.getTextSize(val, font, font_size_small, 1)
text_width, text_height = text_size
text_x = offset[1] + pxdelta[1] // 2 # Adjust position to the left of the grid
text_y = gbr_img[0] - i * 2 * pxdelta[0] + text_height // 2
cv2.putText(
img_array, val, (text_x, text_y), font, font_size_small, tick_color, 1
)
# Draw title with opacity
cv2.putText(
img_array, title, (text_x_title, text_y_title), font, font_size, label_color, 1
)
return img_array
@debug_performance('_plotperf')
def plot2(
values: np.array,
title: str = 'Measuring',
size: Tuple[int, int] = (300, 300),
point_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
r=2,
nticks: int = 16,
grid_color: Tuple[int, int, int, int] = (128, 128, 128, 255),
precision: int = 4,
default_font_size: float = 0.5,
default_font_size_small: float = 0.4,
label_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
scatter=True,
thickness=2,
line_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
max_len: int = 100,
) -> np.array:
"""Plot into a NumPy image array.
Plots given array of `values`, adapting
the plot scale and size to fit the input data.
Plots fast - no single loop in the code, even if you want to connect points with
line segments, measured 20-100x faster then matplotlib.
Useful for overlaying real-time plots on images and video frames.
Args:
img_array: NumPy ndarray to draw the plot on, likely a video frame
values: NumPy 1D array of values to plot over time
title: Plot title string
offset: (x, y) offset tuple for the top-left of plot
size: (width, height) tuple for plot size in pixels
clr: (R, G, B) tuple for plot color
pxdelta: Grid size in pixels
precision: Floating point precision for y-axis labels
default_font_size: Font size for title
default_font_size_small: Font size for axis labels
opacity: Opacity value 0-1 for plot elements
max_len: Maximum history length for values array
Returns:
img_array: Image array with overlaid adaptive plot
Example:
frame = cv2.imread('frame.jpg')
values = sensor_data[-100:]
frame = draw_adaptive_plot(frame, values)
"""
font_size = default_font_size
font_size_small = default_font_size_small
font = cv2.FONT_HERSHEY_SIMPLEX
text_size_title = cv2.getTextSize(title, font, font_size, 1)[0]
text_y_title = int(text_size_title[1] * 1.5)
margin_ver = int(text_y_title + text_size_title[1] * 0.5)
axlablen = cv2.getTextSize('A' * precision, font, font_size_small, 1)[0][0]
margin_hor = int(axlablen * 1.5)
grid_topleft = np.array((margin_ver, margin_hor))
grid_botright = np.array(size) - grid_topleft
gsize = grid_botright - grid_topleft
gsize2 = gsize - (gsize % nticks)
iota = (gsize - gsize2) / 2
gsize = gsize2
grid_topleft = (grid_topleft + iota).astype(int)
grid_botright = (grid_botright - iota).astype(int)
pxdelta = (gsize // nticks).astype(int)
gh, gw = tuple(gsize)
adjusted_values, bounds, scale, median_degree = adjust_values_maxlen(
values, gsize, max_len=max_len
)
title += f', 10^{int(median_degree[1])}'
text_x_title = int(
grid_topleft[1] + gw / 2 - cv2.getTextSize(title, font, font_size, 1)[0][0] / 2
)
pxdelta = (gsize // nticks).astype(int)
img_array = np.zeros((*size, 4), np.uint8)
# Adjust the title to include the multiplier
# Draw grid and rectangle with opacity
img_array[
grid_topleft[0] : grid_botright[0] + 1 : pxdelta[0],
grid_topleft[1] : grid_botright[1] + 1,
:,
] = grid_color
img_array[
grid_topleft[0] : grid_botright[0] + 1,
grid_topleft[1] : grid_botright[1] + 1 : pxdelta[1],
:,
] = grid_color
# Render points
# Create an array of indices
x = grid_topleft[1] + (adjusted_values[0, ...]).astype(int)
y = grid_botright[0] - (adjusted_values[1, ...]).astype(int)
# Create a mask for valid indices
valid_mask = (
(grid_topleft[0] <= y)
& (y <= grid_botright[0])
& (grid_topleft[1] <= x)
& (x <= grid_botright[1])
)
valsx = x[valid_mask]
valsy = y[valid_mask]
# Create a grid of offsets
x_offset = np.arange(-r, r + 1)
y_offset = np.arange(-r, r + 1)
xx, yy = np.meshgrid(x_offset, y_offset)
# Apply offsets to the original x and y coordinates
xx = xx.ravel() + valsx[:, None]
yy = yy.ravel() + valsy[:, None]
# Flatten the arrays
xx = xx.ravel()
yy = yy.ravel()
# Assign color to the corresponding pixels and the surrounding pixels
img_array[yy, xx] = point_color
if not scatter and values.shape[1] >= 2:
# Create pairs of adjacent points
with _veclinesperf:
img_array = vectorized_lines_with_thickness(
y[:-1],
x[:-1],
y[1:],
x[1:],
img_array,
clr=line_color,
thickness=thickness,
)
# rendering text
n = gsize[0] // (2 * pxdelta[0])
tick_color = label_color
yscale = bounds[1, 1] - bounds[0, 1]
for i in range(n + 1):
# Scale the tick label by the multiplier
tickval = bounds[0, 1] + (yscale / n) * i
dotp = precision - len(str(tickval).split('.')[0])
val = '{:.{}f}'.format(tickval, dotp)
text_size, _ = cv2.getTextSize(val, font, font_size_small, 1)
text_width, text_height = text_size
text_x = pxdelta[1] // 2 # Adjust position to the left of the grid
text_y = grid_botright[0] - i * 2 * pxdelta[0] + text_height // 2
cv2.putText(
img_array, val, (text_x, text_y), font, font_size_small, tick_color, 1
)
# Draw title with opacity
cv2.putText(
img_array, title, (text_x_title, text_y_title), font, font_size, label_color, 1
)
return img_array
@debug_performance('_plotperf')
def plot1_cv(
values: np.array,
title: str = 'Measuring',
size: Tuple[int, int] = (300, 300),
point_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
r=2,
nticks: int = 16,
grid_color: Tuple[int, int, int, int] = (128, 128, 128, 255),
precision: int = 2,
default_font_size: float = 0.5,
default_font_size_small: float = 0.4,
label_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
scatter=True,
thickness=2,
line_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
max_len: int = 100,
) -> np.array:
"""Plot into a NumPy image array.
Plots given array of `values`, adapting
the plot scale and size to fit the input data.
Plots fast - no single loop in the code, even if you want to connect points with
line segments, measured 20-100x faster then matplotlib.
Useful for overlaying real-time plots on images and video frames.
Args:
img_array: NumPy ndarray to draw the plot on, likely a video frame
values: NumPy 1D array of values to plot over time
title: Plot title string
offset: (x, y) offset tuple for the top-left of plot
size: (width, height) tuple for plot size in pixels
clr: (R, G, B) tuple for plot color
pxdelta: Grid size in pixels
precision: Floating point precision for y-axis labels
default_font_size: Font size for title
default_font_size_small: Font size for axis labels
opacity: Opacity value 0-1 for plot elements
max_len: Maximum history length for values array
Returns:
img_array: Image array with overlaid adaptive plot
Example:
frame = cv2.imread('frame.jpg')
values = sensor_data[-100:]
frame = draw_adaptive_plot(frame, values)
"""
min_val = np.min(values)
max_val = np.max(values)
if max_len > 0:
values = values[-max_len:]
# Calculate adjustment factor and shift
if max_val - min_val == 0:
if min_val == 0:
scale = 1.0
shift = -0.5
power = 1
adjust_factor = 1
else:
scale = min_val / 2
power = np.floor(np.log10(min_val))
adjust_factor = 1
shift = -scale
else:
scale = max_val - min_val
power = np.ceil(np.log10((np.abs(min_val) + np.abs(max_val)) / 2))
shift = -min_val
# Determine the multiplier to scale the tick values above 1.0
multiplier = 10**-power
title += f', 10^{int(power)}'
# Set the paramerics
# height = size[1]
# width = size[0]
font_size = default_font_size
font_size_small = default_font_size_small
font = cv2.FONT_HERSHEY_SIMPLEX
text_size_title = cv2.getTextSize(title, font, font_size, 1)[0]
text_y_title = int(text_size_title[1] * 1.5)
margin_ver = int(text_y_title + text_size_title[1] * 0.5)
axlablen = cv2.getTextSize('A' * precision, font, font_size_small, 1)[0][0]
margin_hor = int(axlablen * 1.5)
grid_topleft = np.array((margin_ver, margin_hor))
grid_botright = np.array(size) - grid_topleft
gsize = grid_botright - grid_topleft
gsize2 = gsize - (gsize % nticks)
iota = (gsize - gsize2) / 2
grid_topleft = (grid_topleft + iota).astype(int)
grid_botright = (grid_botright - iota).astype(int)
pxdelta = (gsize // nticks).astype(int)
gsize = gsize2
gh, gw = tuple(gsize)
text_x_title = int(grid_topleft[1] + gw / 2 - text_size_title[0] / 2)
pxdelta = (gsize // nticks).astype(int)
img_array = np.zeros((*size, 4), np.uint8)
# Adjust the title to include the multiplier
adjust_factor = gsize[0] / scale
# Adjust values
adjusted_values = (values + shift) * adjust_factor
# top_left = (0, 0)
# bottom_right = (height, width)
# Draw grid and rectangle with opacity
img_array[
grid_topleft[0] : grid_botright[0] + 1 : pxdelta[0],
grid_topleft[1] : grid_botright[1] + 1,
:,
] = grid_color
img_array[
grid_topleft[0] : grid_botright[0] + 1,
grid_topleft[1] : grid_botright[1] + 1 : pxdelta[1],
:,
] = grid_color
# Render points
# Create an array of indices
i = np.arange(len(adjusted_values))
x = grid_botright[1] - ((i + 1) * gw // len(adjusted_values))
y = grid_botright[0] - (adjusted_values).astype(int)
# Create a mask for valid indices
valid_mask = (
(grid_topleft[0] <= y)
& (y <= grid_botright[0])
& (grid_topleft[1] <= x)
& (x <= grid_botright[1])
)
valsx = x[valid_mask]
valsy = y[valid_mask]
# Create a grid of offsets
x_offset = np.arange(-r, r + 1)
y_offset = np.arange(-r, r + 1)
xx, yy = np.meshgrid(x_offset, y_offset)
# Apply offsets to the original x and y coordinates
xx = xx.ravel() + valsx[:, None]
yy = yy.ravel() + valsy[:, None]
# Flatten the arrays
xx = xx.ravel()
yy = yy.ravel()
# Assign color to the corresponding pixels and the surrounding pixels
img_array[yy, xx] = point_color
if not scatter and values.shape[0] >= 2:
# Create pairs of adjacent points
with _veclinesperf:
img_array = vectorized_lines_with_thickness(
y[:-1],
x[:-1],
y[1:],
x[1:],
img_array,
clr=line_color,
thickness=thickness,
)
# rendering text
n = gsize[0] // (2 * pxdelta[0])
tick_color = label_color
for i in range(n + 1):
# Scale the tick label by the multiplier
val = '{:.{}f}'.format((scale / n * i) * multiplier, precision)
text_size, _ = cv2.getTextSize(val, font, font_size_small, 1)
text_width, text_height = text_size
text_x = pxdelta[1] // 2 # Adjust position to the left of the grid
text_y = grid_botright[0] - i * 2 * pxdelta[0] + text_height // 2
cv2.putText(
img_array, val, (text_x, text_y), font, font_size_small, tick_color, 1
)
# Draw title with opacity
cv2.putText(
img_array, title, (text_x_title, text_y_title), font, font_size, label_color, 1
)
return img_array
@debug_performance('_plotperf')
def plot1(
values: np.array,
title: str = 'Measuring',
size: Tuple[int, int] = (300, 300),
point_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
r=2,
nticks: int = 16,
grid_color: Tuple[int, int, int, int] = (128, 128, 128, 255),
precision: int = 2,
default_font_size: float = 0.8,
default_font_size_small: float = 0.6,
label_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
scatter=True,
thickness=2,
line_color: Tuple[int, int, int, int] = (0, 0, 255, 255),
max_len: int = 100,
) -> np.array:
"""Draw a plot on a new NumPy image array using textrender for text rendering.
Creates a new NumPy ndarray and plots the given `values` on it,
adapting the plot scale and size to fit the input data.
Plots fast - no single loop in the code, even if you want to connect points with
line segments, measured 20-100x faster then matplotlib.
Useful for creating standalone plot images.
Args:
values: NumPy 1D array of values to plot over time
title: Plot title string
size: (width, height) tuple for plot size in pixels
point_color: (R, G, B, A) tuple for plot color
r: Radius of points
nticks: Number of ticks on the y-axis
grid_color: (R, G, B, A) tuple for grid color
precision: Floating point precision for y-axis labels
default_font_size: Font size for title
default_font_size_small: Font size for axis labels
label_color: (R, G, B, A) tuple for label color
scatter: If True, plot points without connecting lines
thickness: Thickness of connecting lines
line_color: (R, G, B, A) tuple for line color
max_len: Maximum history length for values array
Returns:
img_array: New image array with plot
Example:
values = sensor_data[-100:]
plot_img = plot1(values, title="Sensor Data")
"""
if max_len > 0:
values = values[-max_len:]
min_val = np.min(values)
max_val = np.max(values)
# Calculate adjustment factor and shift
if max_val - min_val == 0:
if min_val == 0:
scale = 1.0
shift = -0.5
power = 1
adjust_factor = 1
else:
scale = min_val / 2
power = np.floor(np.log10(min_val))
adjust_factor = 1
shift = -scale
else:
scale = max_val - min_val
power = np.ceil(np.log10((np.abs(min_val) + np.abs(max_val)) / 2))
shift = -min_val
multiplier = 10**-power
title += f', 10^{int(power)}'
# Estimate text sizes and positions
font_size = default_font_size # Adjust this factor as needed
font_size_small = default_font_size_small # Adjust this factor as needed
# Estimate margins and grid size
margin_ver = int(size[1] * 0.1) # 10% of height for vertical margin
margin_hor = int(size[0] * 0.15) # 15% of width for horizontal margin
grid_topleft = np.array((margin_hor, margin_ver))
grid_botright = np.array(size) - grid_topleft
gsize = grid_botright - grid_topleft
# Adjust grid size to be divisible by nticks
gsize2 = gsize - (gsize % nticks)
iota = (gsize - gsize2) / 2
grid_topleft = (grid_topleft + iota).astype(int)
grid_botright = (grid_botright - iota).astype(int)
gsize = gsize2
pxdelta = (gsize // nticks).astype(int)
# Create image array
img_array = np.zeros((*size, 4), np.uint8)
adjust_factor = gsize[0] / scale
adjusted_values = (values + shift) * adjust_factor
# Draw grid and rectangle with opacity
img_array[
grid_topleft[0] : grid_botright[0] + 1 : pxdelta[0],
grid_topleft[1] : grid_botright[1] + 1,
:,
] = grid_color
img_array[
grid_topleft[0] : grid_botright[0] + 1,
grid_topleft[1] : grid_botright[1] + 1 : pxdelta[1],
:,
] = grid_color
# Render points
i = np.arange(len(adjusted_values))
x = grid_botright[1] - ((i + 1) * gsize[1] // len(adjusted_values))
y = grid_botright[0] - (adjusted_values).astype(int)
valid_mask = (
(grid_topleft[0] <= y)
& (y <= grid_botright[0])
& (grid_topleft[1] <= x)
& (x <= grid_botright[1])
)
valsx = x[valid_mask]
valsy = y[valid_mask]
x_offset = np.arange(-r, r + 1)
y_offset = np.arange(-r, r + 1)
xx, yy = np.meshgrid(x_offset, y_offset)
xx = xx.ravel() + valsx[:, None]
yy = yy.ravel() + valsy[:, None]
xx = xx.ravel()
yy = yy.ravel()
img_array[yy, xx] = point_color
if not scatter and values.shape[0] >= 2:
with _veclinesperf:
img_array = vectorized_lines_with_thickness(
y[:-1],
x[:-1],
y[1:],
x[1:],
img_array,
clr=line_color,
thickness=thickness,
)
# Render y-axis labels
tick_color = label_color[:3] # Remove alpha channel for vectorized_text
for i in range(nticks + 1):
val = '{:.{}f}'.format((scale / nticks * i) * multiplier, precision)
l = len(val)
dx = int(l * 5 * font_size_small * 2)
text_x = grid_topleft[1] - dx # Approximate text width
text_y = grid_botright[0] - i * pxdelta[0] - 5 * int(font_size_small) # Adjust for text height
img_array = vectorized_text(
img_array, val, (text_x, text_y), color=tick_color, font_size=font_size_small
)
# Draw title
title_color = label_color[:3] # Remove alpha channel for vectorized_text
text_x_title = grid_topleft[1] + (grid_botright[1] - grid_topleft[1]) // 2 - len(title) * 5 * int(font_size * 2) // 2 # Approximate text width
text_y_title = grid_topleft[0] - int(font_size * 5*2)
img_array = vectorized_text(
img_array, title, (text_x_title, text_y_title), color=title_color, font_size=font_size
)
return img_array
def blend(*arrays)->np.ndarray:
"""
Blends multiple NumPy arrays in the order they are provided.
Parameters:
*arrays: Variable length argument list of NumPy arrays to be blended.
Returns:
np.ndarray: The blended image if all arrays have the same dimensions,
otherwise returns the first array.
"""
if not arrays:
raise ValueError("At least one array must be provided")
# Use the first array as the base
base_array = arrays[0]
# Check if all arrays have the same shape
for array in arrays:
if array.shape != base_array.shape:
return base_array
# Blend arrays by overlaying them in order
blended_array = base_array.copy()
for array in arrays[1:]:
alpha = array[..., 3] / 255.0 # Assuming the last channel is alpha
blended_array[..., :3] = (1 - alpha[..., None]) * blended_array[..., :3] + alpha[..., None] * array[..., :3]
return blended_array
def blend_at(
dst_img: np.ndarray, paste_img: np.ndarray, offset: Tuple[int, int]
) -> np.ndarray:
# pasting image fits
assert dst_img.ndim == paste_img.ndim and np.all(
offset + paste_img.shape[0:2] <= dst_img.shape[0:2]
)
# it is rgba and proper type
assert paste_img.shape[2] == 4 and paste_img.dtype == np.uint8
alpha = paste_img[..., 3][..., None].astype(np.float32) / 255.0
img = paste_img[..., 0:3]
sz = img.shape[0:2]
y0 = offset[0]
y1 = y0 + sz[0]
x0 = offset[1]
x1 = x0 + sz[1]
dst_img[y0:y1, x0:x1] = dst_img[y0:y1, x0:x1] * (1 - alpha) + img * alpha
return dst_img
@debug_performance('_plotperf')
def plot1_atcv(
img_array: np.ndarray,
values: np.ndarray,
title: str = 'Measuring',
offset: Tuple[int, int] = (50, 50),
size: Tuple[int, int] = (300, 270),
point_color: Tuple[int, int, int, int] = (0, 0, 255),
r=2,
pxdelta: int = 15,
grid_color: Tuple[int, int, int, int] = (128, 128, 128),
precision: int = 2,
default_font_size: float = 0.75,
default_font_size_small: float = 0.5,
label_color: Tuple[int, int, int, int] = (0, 0, 255),
scatter=False,
thickness=2,
line_color: Tuple[int, int, int, int] = (0, 0, 255),
max_len: int = 100,