/
evision_mat.ex
2166 lines (1734 loc) · 60.1 KB
/
evision_mat.ex
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
defmodule Evision.Mat do
@moduledoc """
Evision Mat
"""
require Logger
import Kernel, except: [abs: 1, floor: 1, ceil: 1, round: 1]
@behaviour Access
@typedoc """
Types for `Evision.Mat`
#### Shorthand
- `:u8`
- `:u16`
- `:s16`
- `:s32`
- `:f32`
- `:f64`
- `:f16`
#### Tuple Form
- `{:u, 8}`
- `{:u, 16}`
- `{:s, 8}`
- `{:s, 16}`
- `{:s, 32}`
- `{:f, 32}`
- `{:f, 64}`
- `{:f, 16}`
"""
@type mat_type ::
{:u, 8 | 16}
| {:s, 8 | 16 | 32}
| {:f, 32 | 64 | 16}
| :u8
| :u16
| :s8
| :s16
| :s32
| :f32
| :f64
| :f16
@type mat_type_tuple_form ::
{:u, 8 | 16}
| {:s, 8 | 16 | 32}
| {:f, 32 | 64 | 16}
@typedoc """
Type that represents an `Evision.Mat` struct.
- **channels**: `int`.
The number of matrix channels.
- **dims**: `int`.
Matrix dimensionality.
- **type**: `mat_type`.
Type of the matrix elements, following `:nx`'s convention.
- **raw_type**: `int`.
The raw value returned from `int cv::Mat::type()`.
- **shape**: `tuple`.
The shape of the matrix.
- **ref**: `reference`.
The underlying erlang resource variable.
"""
@type t :: %__MODULE__{
channels: integer(),
dims: integer(),
type: mat_type(),
raw_type: integer(),
shape: tuple(),
ref: reference()
}
@enforce_keys [:channels, :dims, :type, :raw_type, :shape, :ref]
defstruct [:channels, :dims, :type, :raw_type, :shape, :ref]
alias __MODULE__, as: T
@typedoc """
The resulting ok-error tuple when a NIF function can return `Evision.Mat`.
"""
@type maybe_mat_out :: Evision.Mat.t() | {:error, String.t()}
@typedoc """
Input argument, `Evision.Mat`, `Nx.Tensor` or `#reference`.
- `Evision.Mat`, recommended to use.
- `Nx.Tensor`
Accepting this type so that it's easier to interact with a `Nx.Tensor`.
- `reference()`, not recommended.
Only some internal functions will pass the raw reference variables around.
"""
@type maybe_mat_in :: reference() | Evision.Mat.t() | Nx.Tensor.t()
@doc false
def __to_struct__(%{
:channels => channels,
:dims => dims,
:type => type,
:raw_type => raw_type,
:shape => shape,
:ref => ref
}) do
%T{
channels: channels,
dims: dims,
type: type,
raw_type: raw_type,
shape: shape,
ref: ref
}
end
def __to_struct__(ret) do
Evision.Internal.Structurise.to_struct(ret)
end
@doc false
@spec __from_struct__(Evision.Mat.t() | Nx.Tensor.t() | reference()) :: reference()
def __from_struct__(%T{ref: ref}) do
ref
end
def __from_struct__(%Nx.Tensor{} = tensor) do
Evision.Internal.Structurise.from_struct(tensor)
end
def __from_struct__(ref) when is_reference(ref) do
ref
end
@doc false
@spec __from_elixir_range__(Range.t(), Keyword.t()) :: {number(), number()}
def __from_elixir_range__(first..last//step, opts \\ []) do
swap_if_neg_step = opts[:swap_if_neg_step] || false
allowed_step_size = opts[:allowed_step_size]
if is_list(allowed_step_size) and !Enum.member?(allowed_step_size, step) do
raise "Invalid step size, only supports step size in #{inspect({allowed_step_size})} at the moment."
end
if swap_if_neg_step and step < 0 do
{last, first}
else
{first, last}
end
end
defp __handle_negative_range__(value, bound) when value < 0 do
value + bound
end
defp __handle_negative_range__(value, _bound), do: value
@doc false
def __standardise_range_list__(ranges, shape, inclusive_range) do
Enum.map(Enum.zip(ranges, Tuple.to_list(shape)), fn {r, dim} ->
case r do
:all ->
:all
{first, last} ->
# {_, _} is cv::Range
# hence we don't need to do anything to it
first = __handle_negative_range__(first, dim)
last = __handle_negative_range__(last, dim)
{first, last}
first..last//step ->
# first..last//step is Elixir.Range
# 0..0 should give [0] if `inclusive_range` is true
step =
if step == -1 and (last < 0 or first < 0) do
1
else
step
end
first = __handle_negative_range__(first, dim)
last = __handle_negative_range__(last, dim)
{first, last} = __from_elixir_range__(first..last//step, allowed_step_size: [1])
if inclusive_range do
# note that what we are going return is cv::Range
# which is [start, end)
{first, last + 1}
else
{first, last}
end
number when is_integer(number) ->
number = __handle_negative_range__(number, dim)
# cv::Range is [start, end)
# while Elixir.Range is [first, last]
if inclusive_range do
# [first, last), [0, 1) will give [0]
# note that what we are going return is cv::Range
# which is [start, end)
{number, number + 1}
else
# [first, last], [0, 0] will give []
{number, number}
end
unknown ->
raise "Cannot convert from `#{inspect(unknown)}` to a valid range."
end
end)
end
@doc """
Extracts a rectangular submatrix.
The submatrix data is copied.
#### Variant 1
##### Positional Arguments
- **mat**. `maybe_mat_in()`
The matrix.
- **rowRange**. `{int, int} | :all`.
Start and end row of the extracted submatrix. The upper boundary is not included.
- **colRange**. `{int, int} | :all`.
Start and end column of the extracted submatrix. The upper boundary is not included.
##### Return
Extracted submatrix (data is copied).
#### Variant 2
##### Positional Arguments
- **mat**. `maybe_mat_in()`
The matrix.
- **rowRange**. `Range.t(step: 1)`.
Start and end row of the extracted submatrix. The upper boundary is not included.
- **colRange**. `Range.t(step: 1)`.
Start and end column of the extracted submatrix. The upper boundary is not included.
##### Return
Extracted submatrix (data is copied).
"""
@spec roi(maybe_mat_in(), {integer(), integer()} | :all, {integer(), integer()} | :all) ::
maybe_mat_out()
def roi(mat, rowRange, colRange)
when (is_tuple(rowRange) or rowRange == :all) and (is_tuple(colRange) or colRange == :all) do
mat = __from_struct__(mat)
:evision_nif.mat_roi(mat: mat, rowRange: rowRange, colRange: colRange)
|> Evision.Internal.Structurise.to_struct()
end
@spec roi(maybe_mat_in(), Range.t(), Range.t()) :: maybe_mat_out()
def roi(mat, firstRow..lastRow//1, firstCol..lastCol//1) do
roi(mat, {firstRow, lastRow}, {firstCol, lastCol})
end
def roi(_, _.._//_, _.._//_) do
raise ArgumentError, "Evision.Mat.roi does not support step size other than 1."
end
@doc """
Extracts a rectangular submatrix.
#### Variant 1
##### Positional Arguments
- **mat**. `maybe_mat_in()`
The matrix.
- **rect**. `{int, int, int, int}`
The rect that specifies `{x, y, width, height}`.
##### Return
Extracted submatrix specified as a rectangle. (data is copied)
#### Variant 2
##### Positional Arguments
- **mat**. `maybe_mat_in()`
The matrix.
- **ranges**. `[{int, int} | :all]`
Array of selected ranges along each array dimension.
##### Return
Extracted submatrix. (data is copied)
"""
@spec roi(maybe_mat_in(), {integer(), integer(), integer(), integer()}) :: maybe_mat_out()
def roi(mat, rect = {_, _, _, _}) when is_tuple(rect) do
mat = __from_struct__(mat)
:evision_nif.mat_roi(mat: mat, rect: rect)
|> Evision.Internal.Structurise.to_struct()
end
@spec roi(maybe_mat_in(), [{integer(), integer()} | Range.t() | :all]) :: maybe_mat_out()
def roi(mat, ranges) when is_list(ranges) do
shape = mat.shape
mat = __from_struct__(mat)
ranges = __standardise_range_list__(ranges, shape, true)
:evision_nif.mat_roi(mat: mat, ranges: ranges)
|> Evision.Internal.Structurise.to_struct()
end
@spec update_roi(maybe_mat_in(), [{integer(), integer()} | Range.t() | :all], maybe_mat_in()) ::
maybe_mat_out()
def update_roi(mat, ranges, with_mat) do
{mat, bring_back} =
if mat.dims != tuple_size(mat.shape) do
{Evision.Mat.channel_as_last_dim(mat), true}
else
{mat, false}
end
with_mat =
if with_mat.dims != tuple_size(with_mat.shape) do
Evision.Mat.channel_as_last_dim(with_mat)
else
with_mat
end
ranges = __standardise_range_list__(ranges, mat.shape, true)
ranges =
if tuple_size(mat.shape) > Enum.count(ranges) do
extend =
for i <- Enum.count(ranges)..(tuple_size(mat.shape) - 1), reduce: [] do
acc ->
[{0, elem(mat.shape, i)} | acc]
end
ranges ++ Enum.reverse(extend)
else
ranges
end
with_mat = __from_struct__(with_mat)
mat = __from_struct__(mat)
res =
Evision.Internal.Structurise.to_struct(
:evision_nif.mat_update_roi(mat: mat, ranges: ranges, with_mat: with_mat)
)
if bring_back do
Evision.Mat.last_dim_as_channel(res)
else
res
end
end
@doc """
Display inline image in terminal for iTerm2 users.
This function will check the value of `:display_inline_image_iterm2` in the application config.
If is `true`, then it will detect if current session is running in `iTerm2` (by checking the environment variable `LC_TERMINAL`).
If both are `true`, we next check if the image is a 2D image, also if its size is within the limits.
The maximum size can be set in the application config, for example,
```elixir
config :evision, display_inline_image_iterm2: true
config :evision, display_inline_image_max_size: {8192, 8192}
```
If it passes all the checks, then it will be displayed as an inline image in iTerm2.
"""
@spec quicklook(Nx.Tensor.t()) :: Nx.Tensor.t()
def quicklook(%Nx.Tensor{} = tensor) do
case Evision.Mat.from_nx_2d(tensor) do
%Evision.Mat{} = mat ->
quicklook(mat)
end
tensor
end
@spec quicklook(Evision.Mat.t()) :: Evision.Mat.t()
def quicklook(%Evision.Mat{dims: dims, channels: c, shape: shape} = mat) do
if Application.get_env(:evision, :display_inline_image_max_size) == :error do
Application.put_env(:evision, :display_inline_image_max_size, {8192, 8192},
persistent: true
)
end
is_2d_image =
(dims == 2 and Enum.member?([1, 3, 4], c)) or
(c == 1 and tuple_size(shape) == 3 and elem(shape, 2) == 1)
with {:is_2d, true} <- {:is_2d, is_2d_image},
{:display_image_if_in_iterm2, {:ok, true}} <-
{:display_image_if_in_iterm2,
Application.fetch_env(:evision, :display_inline_image_iterm2)},
{:is_iterm2, true} <- {:is_iterm2, System.get_env("LC_TERMINAL") == "iTerm2"},
{:get_maximum_size, {h, w}} <-
{:get_maximum_size, Application.get_env(:evision, :display_inline_image_max_size)},
{:within_maximum_size, true} <-
{:within_maximum_size,
((0 < h and elem(shape, 0) < h) or h == :infinity) and
((0 < w and elem(shape, 1) < w) or w == :infinity)} do
{osc, st} =
if String.starts_with?(System.get_env("TERM"), "screen") do
{"\ePtmux;\e\e", "\a\e\\\r\n"}
else
{"\e", "\e\\\r\n"}
end
binary = Evision.imencode(".png", mat)
b64 = Base.encode64(binary)
bin_size = byte_size(binary)
IO.puts([
"#{osc}]1337;File=size=#{bin_size};inline=1:",
b64,
st
])
end
mat
end
@spec quicklook(term()) :: term()
def quicklook(any) do
any
end
@default_kino_render_image_encoding Application.compile_env(
:evision,
:kino_render_image_encoding,
:png
)
@doc """
Get preferred image encoding when rendering in Kino.
Default value is `Application.compile_env(:evision, :kino_render_image_encoding, :png)`.
"""
@spec kino_render_image_encoding() :: term()
def kino_render_image_encoding() do
Process.get(:evision_kino_render_image_encoding, @default_kino_render_image_encoding)
end
@doc """
Set preferred image encoding when rendering in Kino.
Only valid when `:kino` >= 0.7 and using in livebook
##### Positional Arguments
- **encoding**. `:png | :jpeg`.
When rendering a 2D image with Kino in Livebook
the image will first be encoded into either :png or :jpeg
- `:png` usually has better quality because it is lossless compression,
however, it uses more bandwidth to transfer
- `:jpeg` require less bandwidth to pass from the backend to the livebook frontend,
but it is lossy compression
"""
@spec set_kino_render_image_encoding(:png | :jpeg | term()) :: term()
def set_kino_render_image_encoding(encoding) when encoding in [:png, :jpeg] do
Process.put(:evision_kino_render_image_encoding, encoding)
end
def set_kino_render_image_encoding(encoding) do
raise RuntimeError, """
Unknown image encoding `#{inspect(encoding)}`. Supported encoding are either :png or :jpeg.
"""
end
@default_kino_render_image_max_size Application.compile_env(
:evision,
:kino_render_image_max_size,
{8192, 8192}
)
@doc """
Get the maximum allowed image size to render in Kino.
Default value is `Application.compile_env(:evision, :kino_render_image_max_size, {8192, 8192})`.
"""
@spec kino_render_image_max_size() :: term()
def kino_render_image_max_size() do
Process.get(:evision_kino_render_image_max_size, @default_kino_render_image_max_size)
end
@doc """
Set the maximum allowed image size to render in Kino.
Only valid when `:kino` >= 0.7 and using in livebook
##### Positional Arguments
- **size**. `{height, width}`.
"""
@spec set_kino_render_image_max_size({pos_integer(), pos_integer()}) :: term()
def set_kino_render_image_max_size({height, width})
when is_integer(height) and height > 0 and is_integer(width) and width > 0 do
Process.put(:evision_kino_render_image_max_size, {height, width})
end
def set_kino_render_image_max_size(size) do
raise RuntimeError, """
Invalid value for setting image max size `#{inspect(size)}`, expecting a 2-tuple with positive integers, `{height, width}`.
"""
end
@kino_render_tab_order Enum.uniq(
Application.compile_env(:evision, :kino_render_tab_order, [
:image,
:raw,
:numerical
])
)
@doc """
Get preferred order of Kino.Layout tabs for `Evision.Mat` in Livebook.
Default value is `Enum.uniq(Application.compile_env(:evision, :kino_render_tab_order, [:image, :raw, :numerical]))`.
"""
@spec kino_render_tab_order() :: term()
def kino_render_tab_order() do
Process.get(:evision_kino_render_tab_order, @kino_render_tab_order)
end
@supported_kino_render_tab_order [:image, :raw, :numerical]
@doc """
Set preferred order of Kino.Layout tabs for `Evision.Mat` in Livebook.
Only valid when `:kino` >= 0.7 and using in Livebook.
##### Positional Arguments
- **order**: `[atom()]`
Default order is `[:image, :raw, :numerical]`, and the corresponding tabs will be:
Image | Raw | Numerical
Note that the `:image` tab will not show if the `Evision.Mat` is not a 2D image.
Also, it's possible to specify any combination (any subset) of these tabs,
including the empty one, `[]`, and in that case, the output content in the livebook
cell will be the same as `:raw` but without any tabs.
Simply put, `[]` means to only do the basic inspect and not use Kino.Layout.tabs
**It's worth noting that `[] != nil`, because `nil` is default return value when `kino_render_tab_order`**
**is not configured -- hence evision will use the default order, `[:image, :raw, :numerical]` in such case**
When only specifying one type, i.e., `[:image]`, `[:raw]` or `[:numerical]`, only one tab will be shown.
Furthermore, when `kino_render_tab_order` is configured to `[:image]` and when the `Evision.Mat` is not a 2D image,
it will automatically fallback to `:raw`.
Simply put, `[:image]` in this case (when only specifying one type) means:
displaying the `Evision.Mat` as an image whenever possible, and fallback to `:raw`
if it's not a 2D image
"""
@spec set_kino_render_tab_order([atom()] | term()) :: term()
def set_kino_render_tab_order(order) when is_list(order) do
render_types =
Enum.map(order, fn t ->
supported? = Enum.member?(@supported_kino_render_tab_order, t)
if !supported? do
Logger.warning("""
Unknown type `#{inspect(t)}` found in `config :evision, kino_render_tab_order`.
Supported types are `#{inspect(@supported_kino_render_tab_order)}` and their combinations.
""")
nil
else
t
end
end)
|> Enum.reject(fn a -> a == nil end)
Process.put(:evision_kino_render_tab_order, render_types)
end
def set_kino_render_tab_order(types) do
raise RuntimeError, """
Unknown types `#{inspect(types)}`. Supported types are `#{inspect(@supported_kino_render_tab_order)}` and their combinations.
"""
end
if Code.ensure_loaded?(Kino.Render) do
defimpl Kino.Render do
require Logger
defp is_2d_image(%Evision.Mat{dims: 2}), do: true
defp is_2d_image(%Evision.Mat{channels: 1, shape: {_h, _w, 1}}) do
true
end
defp is_2d_image(_), do: false
defp within_maximum_size(mat) do
{max_height, max_width} = Evision.Mat.kino_render_image_max_size()
case Evision.Mat.shape(mat) do
{h, w} ->
h <= max_height and w <= max_width
{h, w, _c} ->
h <= max_height and w <= max_width
_ ->
false
end
end
def to_livebook(mat) when is_struct(mat, Evision.Mat) do
render_types = Evision.Mat.kino_render_tab_order()
Enum.map(render_types, fn
:raw ->
{"Raw", Kino.Inspect.new(mat)}
:numerical ->
{"Numerical", Kino.Inspect.new(Evision.Mat.to_nx(mat))}
:image ->
{ext, format} =
case Evision.Mat.kino_render_image_encoding() do
:jpg ->
{".jpg", :jpeg}
:jpeg ->
{".jpeg", :jpeg}
:png ->
{".png", :png}
unknown ->
raise RuntimeError, "Cannot render image with encoding `#{inspect(unknown)}`"
end
with true <- is_2d_image(mat),
true <- within_maximum_size(mat),
encoded <- Evision.imencode(ext, mat),
true <- is_binary(encoded) do
{"Image", Kino.Image.new(encoded, format)}
else
_ ->
nil
end
end)
|> Enum.reject(fn a -> a == nil end)
|> to_livebook_tabs(render_types, mat)
end
defp to_livebook_tabs([], [:image], mat) do
Kino.Layout.tabs([{"Raw", Kino.Inspect.new(mat)}])
|> Kino.Render.to_livebook()
end
defp to_livebook_tabs(_tabs, [], mat) do
Kino.Inspect.new(mat)
|> Kino.Render.to_livebook()
end
defp to_livebook_tabs(tabs, _types, _mat) do
Kino.Layout.tabs(tabs)
|> Kino.Render.to_livebook()
end
end
end
@doc false
def __generate_complete_range__(dims, maybe_incomplete) when is_list(maybe_incomplete) do
indices_given = Enum.count(maybe_incomplete)
if indices_given <= dims do
maybe_incomplete ++ List.duplicate(:all, dims - indices_given)
else
if indices_given == dims + 1 do
maybe_incomplete
else
{:error,
"too many indices, got #{indices_given} index ranges, while the matrix.dims is #{dims}"}
end
end
end
@impl Access
@doc """
Access.fetch implementation for Evision.Mat.
```elixir
iex> img = Evision.imread("test/qr_detector_test.png")
%Evision.Mat{
channels: 3,
dims: 2,
type: {:u, 8},
raw_type: 16,
shape: {300, 300, 3},
ref: #Reference<0.809884129.802291734.78316>
}
# Same behaviour as Nx.
# Also, img[0] gives the same result as img[[0]]
# For this example, they are both equvilent of img[[0, :all, :all]]
iex> img[[0]]
%Evision.Mat{
channels: 3,
dims: 2,
type: {:u, 8},
raw_type: 16,
shape: {1, 300, 3},
ref: #Reference<0.809884129.802291731.77296>
}
# same as img[[0..100, 50..200, :all]]
# however, currently we only support ranges with step size 1
#
# **IMPORTANT NOTE**
#
# also, please note that we are using Elixir.Range here
# and Elixir.Range is **inclusive**, i.e, [start, end]
# while cv::Range `{integer(), integer()}` is `[start, end)`
# the difference can be observed in the `shape` field
iex> img[[0..100, 50..200]]
%Evision.Mat{
channels: 3,
dims: 2,
type: {:u, 8},
raw_type: 16,
shape: {101, 151, 3},
ref: #Reference<0.809884129.802291731.77297>
}
iex> img[[{0, 100}, {50, 200}]]
%Evision.Mat{
channels: 3,
dims: 2,
type: {:u, 8},
raw_type: 16,
shape: {100, 150, 3},
ref: #Reference<0.809884129.802291731.77297>
}
# for this example, the result is the same as `Evision.extractChannel(img, 0)`
iex> img[[:all, :all, 0]]
%Evision.Mat{
channels: 1,
dims: 2,
type: {:u, 8},
raw_type: 0,
shape: {300, 300},
ref: #Reference<0.809884129.802291731.77298>
}
iex> img[[:all, :all, 0..1]]
%Evision.Mat{
channels: 2,
dims: 2,
type: {:u, 8},
raw_type: 8,
shape: {300, 300, 2},
ref: #Reference<0.809884129.802291731.77299>
}
# when index is out of bounds
iex> img[[:all, :all, 42]]
{:error, "index 42 is out of bounds for axis 2 with size 3"}
# it works the same way for any dimensional Evision.Mat
iex> mat = Evision.Mat.ones({10, 10, 10, 10, 10}, :u8)
iex> mat[[1..7, :all, 2..6, 3..9, :all]]
%Evision.Mat{
channels: 1,
dims: 5,
type: {:u, 8},
raw_type: 0,
shape: {7, 10, 5, 7, 10},
ref: #Reference<0.3015448455.3766878228.259075>
}
```
"""
@spec fetch(Evision.Mat.t(), list() | integer()) :: {:ok, maybe_mat_out() | nil}
def fetch(mat, key) when is_list(key) do
ranges = __generate_complete_range__(mat.dims, key)
ranges = __standardise_range_list__(ranges, mat.shape, true)
{:ok, roi(mat, ranges)}
end
def fetch(mat, key) when is_integer(key) do
# cv::Range is [start, end)
fetch(mat, [{key, key + 1}])
end
def fetch(_mat, _key) do
{:ok, nil}
end
@impl Access
@doc """
Access.get_and_update/3 implementation for Evision.Mat
```elixir
iex> mat = Evision.Mat.zeros({5, 5}, :u8)
iex> Evision.Mat.to_nx(mat)
#Nx.Tensor<
u8[5][5]
Evision.Backend
[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
>
iex> {old, new} = Evision.Mat.get_and_update(mat, [1..3, 1..3], fn roi ->
{roi, Nx.broadcast(Nx.tensor(255, type: roi.type), roi.shape)}
end)
iex> Evision.Mat.to_nx(new)
#Nx.Tensor<
u8[5][5]
Evision.Backend
[
[0, 0, 0, 0, 0],
[0, 255, 255, 255, 0],
[0, 255, 255, 255, 0],
[0, 255, 255, 255, 0],
[0, 0, 0, 0, 0]
]
>
```
"""
@spec get_and_update(Evision.Mat.t(), term(), (Evision.Mat.t() -> Evision.Mat.t())) ::
{Evision.Mat.t(), Evision.Mat.t()}
def get_and_update(mat, key, function) when is_list(key) do
ranges = __generate_complete_range__(mat.dims, key)
roi = roi(mat, ranges)
case function.(roi) do
{^roi, modified_roi} ->
if is_struct(modified_roi, Nx.Tensor) or is_struct(modified_roi, Evision.Mat) do
{mat, update_roi(mat, ranges, modified_roi)}
else
raise RuntimeError,
"Cannot update the requested sub-matrix with unsupported value #{inspect(modified_roi)}"
end
_ ->
{mat, mat}
end
end
def get_and_update(mat, key, function) when is_integer(key) do
get_and_update(mat, [{key, key + 1}], function)
end
def get_and_update(_mat, key, _function) do
raise RuntimeError, "Evision.Mat.get_and_update/3: unknown/unsupported key #{inspect(key)}"
end
@impl Access
@doc """
Access.pop/2 is not implemented yet
"""
@spec pop(any, any) :: none
def pop(_mat, _key) do
raise RuntimeError, "Evision.Mat does not support Access.pop/2 yet"
end
@doc namespace: :"cv.Mat"
@doc """
Create an `Evision.Mat` from list literals.
### Example
Creating `Evision.Mat` from empty list literal (`[]`) is the same as calling `Evision.Mat.empty()`.
```elixir
iex> Evision.Mat.literal!([])
%Evision.Mat{
channels: 1,
dims: 0,
type: {:u, 8},
raw_type: 0,
shape: {},
ref: #Reference<0.1204050731.2031747092.46781>
}
```
By default, the shape of the Mat will stay as is.
```elixir
iex> Evision.Mat.literal!([[[1,1,1],[2,2,2],[3,3,3]]], :u8)
%Evision.Mat{
channels: 1,
dims: 3,
type: {:u, 8},
raw_type: 0,
shape: {1, 3, 3},
ref: #Reference<0.512519210.691404819.106300>
}
```
`Evision.Mat.literal/3` will return a valid 2D image
if the keyword argument, `as_2d`, is set to `true`
and if the list literal can be represented as a 2D image.
```elixir
iex> Evision.Mat.literal!([[[1,1,1],[2,2,2],[3,3,3]]], :u8, as_2d: true)
%Evision.Mat{
channels: 3,
dims: 2,
type: {:u, 8},
raw_type: 16,
shape: {1, 3, 3},
ref: #Reference<0.512519210.691404820.106293>
}
```
"""
@spec literal(list(), mat_type(), Keyword.t()) :: maybe_mat_out()
def literal([]) do
empty()
end
def literal(literal, type, opts \\ [])
def literal([], _type, _opts) do
empty()
end
def literal(literal, type, opts) when is_list(literal) do
# leave all the checks to Nx.tensor/2
as_2d_image = opts[:as_2d] || false
tensor = Nx.tensor(literal, type: type, backend: Evision.Backend)
if as_2d_image do
Evision.Mat.from_nx_2d(tensor)
else
Evision.Mat.from_nx(tensor)
end
end
@doc namespace: :"cv.Mat"
@spec number(number(), mat_type()) :: maybe_mat_out()
def number(number, type) do
type = check_unsupported_type(type)
Evision.Mat.full({1, 1}, number, type)
end
@doc namespace: :"cv.Mat"
@spec at(maybe_mat_in(), integer()) :: number() | {:error, String.t()}
def at(mat, position) when is_integer(position) and position >= 0 do
mat = __from_struct__(mat)
:evision_nif.mat_at(img: mat, pos: position)
|> Evision.Internal.Structurise.to_struct()
end
@doc namespace: :"cv.Mat"
@spec add(maybe_mat_in(), maybe_mat_in()) :: maybe_mat_out()
def add(lhs, rhs) do
lhs = __from_struct__(lhs)