-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.go
More file actions
2204 lines (2039 loc) · 71.2 KB
/
runtime.go
File metadata and controls
2204 lines (2039 loc) · 71.2 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
package opencv
import (
"context"
"fmt"
"image/color"
"os"
"path/filepath"
"sync"
"sync/atomic"
"unsafe"
internalruntime "github.com/brainplusplus/go-opencv/internal/runtime"
)
// Runtime owns a single OpenCV instance (native DLL) and all Mats.
type Runtime struct {
ctx context.Context
cancel context.CancelFunc
backend backend
closed atomic.Bool
mu sync.Mutex
mats map[matHandle]struct{}
}
type backend interface {
Close(context.Context) error
NewMat(context.Context, int, int, int32) (matHandle, error)
NewMatFromData(context.Context, []byte, int, int, int32) (matHandle, error)
CloseMat(context.Context, matHandle) error
MatRows(context.Context, matHandle) (int, error)
MatCols(context.Context, matHandle) (int, error)
MatType(context.Context, matHandle) (int32, error)
MatClone(context.Context, matHandle) (matHandle, error)
MatEmpty(context.Context, matHandle) (bool, error)
MatElemSize(context.Context, matHandle) (int, error)
MatDataPtr(context.Context, matHandle) (unsafe.Pointer, error)
MatStep(context.Context, matHandle) (int, error)
MatChannels(context.Context, matHandle) (int, error)
MatTotal(context.Context, matHandle) (int, error)
MatRow(context.Context, matHandle, int32) (matHandle, error)
MatCol(context.Context, matHandle, int32) (matHandle, error)
MatRegion(context.Context, matHandle, int32, int32, int32, int32) (matHandle, error)
MatReshape(context.Context, matHandle, int32, int32) (matHandle, error)
MatSetTo(context.Context, matHandle, float64, float64, float64, float64) error
MatConvertTo(context.Context, matHandle, matHandle, int32, float64, float64) error
MatZeros(context.Context, int, int, int32) (matHandle, error)
MatOnes(context.Context, int, int, int32) (matHandle, error)
MatEye(context.Context, int, int, int32) (matHandle, error)
CvtColor(context.Context, matHandle, matHandle, int32) error
Resize(context.Context, matHandle, matHandle, int32, int32) error
Blur(context.Context, matHandle, matHandle, int32, int32) error
GaussianBlur(context.Context, matHandle, matHandle, int32, int32, float64) error
MedianBlur(context.Context, matHandle, matHandle, int32) error
Threshold(context.Context, matHandle, matHandle, float64, float64, int32) error
AdaptiveThreshold(context.Context, matHandle, matHandle, float64, int32, int32, int32, float64) error
Canny(context.Context, matHandle, matHandle, float64, float64) error
Flip(context.Context, matHandle, matHandle, int32) error
Sobel(context.Context, matHandle, matHandle, int32, int32, int32, int32, float64, float64) error
Laplacian(context.Context, matHandle, matHandle, int32, int32, float64, float64) error
Transpose(context.Context, matHandle, matHandle) error
EqualizeHist(context.Context, matHandle, matHandle) error
Normalize(context.Context, matHandle, matHandle, float64, float64, int32) error
Erode(context.Context, matHandle, matHandle, matHandle, int32, int32, int32) error
Dilate(context.Context, matHandle, matHandle, matHandle, int32, int32, int32) error
MorphologyEx(context.Context, matHandle, matHandle, int32, matHandle, int32, int32, int32) error
GetStructuringElement(context.Context, int32, int32, int32) (matHandle, error)
Rectangle(context.Context, matHandle, int32, int32, int32, int32, uint8, uint8, uint8, uint8, int32) error
Circle(context.Context, matHandle, int32, int32, int32, uint8, uint8, uint8, uint8, int32) error
Line(context.Context, matHandle, int32, int32, int32, int32, uint8, uint8, uint8, uint8, int32) error
PutText(context.Context, matHandle, unsafe.Pointer, int32, int32, int32, int32, float64, uint8, uint8, uint8, uint8, int32, int32, int32) error
FillPoly(context.Context, matHandle, unsafe.Pointer, int32, int32, uint8, uint8, uint8, uint8, int32, int32) error
ArrowedLine(context.Context, matHandle, int32, int32, int32, int32, uint8, uint8, uint8, uint8, int32, int32, int32, float64) error
FindContours(context.Context, matHandle, matHandle, int32, int32, int32, int32) error
DrawContours(context.Context, matHandle, matHandle, int32, uint8, uint8, uint8, uint8, int32) error
ContourArea(context.Context, matHandle) (float64, error)
ArcLength(context.Context, matHandle, bool) (float64, error)
BoundingRect(context.Context, matHandle) (int32, int32, int32, int32, error)
MinEnclosingCircle(context.Context, matHandle) (float64, float64, float64, error)
Moments(context.Context, matHandle, bool) ([10]float64, error)
HoughLines(context.Context, matHandle, matHandle, float64, float64, int32, float64, float64) error
HoughLinesP(context.Context, matHandle, matHandle, float64, float64, int32, float64, float64) error
HoughCircles(context.Context, matHandle, matHandle, int32, float64, float64, float64, float64, int32, int32) error
WarpAffine(context.Context, matHandle, matHandle, matHandle, int32, int32) error
WarpPerspective(context.Context, matHandle, matHandle, matHandle, int32, int32) error
GetRotationMatrix2D(context.Context, float64, float64, float64, float64) (matHandle, error)
GetAffineTransform(context.Context, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64) (matHandle, error)
BitwiseAnd(context.Context, matHandle, matHandle, matHandle) error
BitwiseOr(context.Context, matHandle, matHandle, matHandle) error
BitwiseXor(context.Context, matHandle, matHandle, matHandle) error
BitwiseNot(context.Context, matHandle, matHandle) error
Add(context.Context, matHandle, matHandle, matHandle) error
Subtract(context.Context, matHandle, matHandle, matHandle) error
Multiply(context.Context, matHandle, matHandle, matHandle, float64, int32) error
Divide(context.Context, matHandle, matHandle, matHandle, float64, int32) error
AbsDiff(context.Context, matHandle, matHandle, matHandle) error
MinMaxLoc(context.Context, matHandle) (float64, float64, int32, int32, int32, int32, error)
MeanStdDev(context.Context, matHandle, matHandle, matHandle) error
CountNonZero(context.Context, matHandle) (int, error)
Split(context.Context, matHandle, matHandle) error
Merge(context.Context, matHandle, matHandle) error
// Vector helpers
VecPointsNew(context.Context) (matHandle, error)
VecPointsPush(context.Context, matHandle, int32, int32) error
VecPointsLen(context.Context, matHandle) (int, error)
VecPointsGet(context.Context, matHandle, int32) (int32, int32, error)
VecPointsDelete(context.Context, matHandle)
VecVecPointsNew(context.Context) (matHandle, error)
VecVecPointsPush(context.Context, matHandle, matHandle) error
VecVecPointsLen(context.Context, matHandle) (int, error)
VecVecPointsGet(context.Context, matHandle, int32) (matHandle, error)
VecVecPointsDelete(context.Context, matHandle)
VecDoubleNew(context.Context) (matHandle, error)
VecDoubleGet(context.Context, matHandle, int32) (float64, error)
VecDoubleLen(context.Context, matHandle) (int, error)
VecDoubleDelete(context.Context, matHandle)
VecIntNew(context.Context) (matHandle, error)
VecIntGet(context.Context, matHandle, int32) (int32, error)
VecIntLen(context.Context, matHandle) (int, error)
VecIntDelete(context.Context, matHandle)
VecMatNew(context.Context) (matHandle, error)
VecMatPush(context.Context, matHandle, matHandle) error
VecMatLen(context.Context, matHandle) (int, error)
VecMatGet(context.Context, matHandle, int32) (matHandle, error)
VecMatDelete(context.Context, matHandle)
// New imgproc
BilateralFilter(context.Context, matHandle, matHandle, int32, float64, float64) error
InRange(context.Context, matHandle, float64, float64, float64, float64, float64, float64, float64, float64, matHandle) error
MatchTemplate(context.Context, matHandle, matHandle, matHandle, int32) error
CalcHist(context.Context, matHandle, matHandle, int32, float64, float64) error
ConnectedComponents(context.Context, matHandle, matHandle, int32, int32) error
DistanceTransform(context.Context, matHandle, matHandle, int32, int32) error
CopyMakeBorder(context.Context, matHandle, matHandle, int32, int32, int32, int32, int32, float64, float64, float64, float64) error
Rotate(context.Context, matHandle, matHandle, int32) error
Hconcat(context.Context, matHandle, matHandle, matHandle) error
Vconcat(context.Context, matHandle, matHandle, matHandle) error
Remap(context.Context, matHandle, matHandle, matHandle, matHandle, int32, int32, float64) error
LUT(context.Context, matHandle, matHandle, matHandle) error
Integral(context.Context, matHandle, matHandle) error
GetPerspectiveTransform(context.Context, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, float64) (matHandle, error)
FillConvexPoly(context.Context, matHandle, matHandle, int32, float64, float64, float64, float64, int32, int32) error
ConvertModel(context.Context, matHandle, matHandle, int32, int32) error
// Photo
FastNlMeansDenoising(context.Context, matHandle, matHandle, float32, int32, int32) error
FastNlMeansDenoisingColored(context.Context, matHandle, matHandle, float32, float32, int32, int32) error
DetailEnhance(context.Context, matHandle, matHandle, float32, float32) error
EdgePreservingFilter(context.Context, matHandle, matHandle, int32, float32, float32) error
PencilSketch(context.Context, matHandle, matHandle, matHandle, float32, float32, float32) error
Stylization(context.Context, matHandle, matHandle, float32, float32) error
SeamlessClone(context.Context, matHandle, matHandle, matHandle, matHandle, int32, int32, int32) error
// Features2d
FAST(context.Context, matHandle, matHandle, int32, int32) error
ORBDetectCompute(context.Context, matHandle, matHandle, matHandle, matHandle, int32, float32, int32) error
BFMatch(context.Context, matHandle, matHandle, matHandle, int32) error
DrawKeypoints(context.Context, matHandle, matHandle, matHandle, float64, float64, float64) error
// Highgui
ImShow(context.Context, unsafe.Pointer, int32, matHandle) error
WaitKey(context.Context, int32) (int32, error)
DestroyWindow(context.Context, unsafe.Pointer, int32) error
// Core extras
MatDiag(context.Context, matHandle) (matHandle, error)
MatAtU8(context.Context, matHandle, int32, int32, int32) (uint8, error)
MatSetU8(context.Context, matHandle, int32, int32, int32, uint8) error
// Vector helpers — keypoints
VecKeypointNew(context.Context) (matHandle, error)
VecKeypointLen(context.Context, matHandle) (int, error)
VecKeypointGet(context.Context, matHandle, int32) (float32, float32, float32, float32, float32, int32, int32, error)
VecKeypointDelete(context.Context, matHandle)
// Vector helpers — dmatch
VecDMatchNew(context.Context) (matHandle, error)
VecDMatchLen(context.Context, matHandle) (int, error)
VecDMatchGet(context.Context, matHandle, int32) (int32, int32, float32, int32, error)
VecDMatchDelete(context.Context, matHandle)
}
// New creates a Runtime backed by a native shared library.
func New(ctx context.Context, opts ...Option) (*Runtime, error) {
if ctx == nil {
ctx = context.Background()
}
cfg := config{}
for _, opt := range opts {
if err := opt(&cfg); err != nil {
return nil, err
}
}
ctx, cancel := context.WithCancel(ctx)
if cfg.dll != "" {
b, err := internalruntime.NewPuregoBackend(cfg.dll)
if err == nil {
rt := &Runtime{ctx: ctx, cancel: cancel, backend: b, mats: map[matHandle]struct{}{}}
return rt, nil
}
cancel()
return nil, fmt.Errorf("opencv: initialize dll backend (%s): %w", cfg.dll, err)
}
if len(embedLibData) > 0 {
libPath, err := extractLib()
if err == nil {
b, err := internalruntime.NewPuregoBackend(libPath)
if err == nil {
rt := &Runtime{ctx: ctx, cancel: cancel, backend: b, mats: map[matHandle]struct{}{}}
return rt, nil
}
cancel()
return nil, fmt.Errorf("opencv: load embedded library: %w", err)
}
cancel()
return nil, fmt.Errorf("opencv: extract embedded library: %w", err)
}
cancel()
return nil, ErrBackendUnavailable
}
func extractLib() (string, error) {
cacheDir, err := os.UserCacheDir()
if err != nil {
return "", fmt.Errorf("user cache dir: %w", err)
}
dir := filepath.Join(cacheDir, "go-opencv", Version)
if err := os.MkdirAll(dir, 0755); err != nil {
return "", fmt.Errorf("mkdir %s: %w", dir, err)
}
libPath := filepath.Join(dir, embedLibName())
if _, err := os.Stat(libPath); err == nil {
return libPath, nil
}
tmpPath := libPath + ".tmp"
if err := os.WriteFile(tmpPath, embedLibData, 0755); err != nil {
os.Remove(tmpPath)
return "", fmt.Errorf("write %s: %w", tmpPath, err)
}
if err := os.Rename(tmpPath, libPath); err != nil {
os.Remove(tmpPath)
return "", fmt.Errorf("rename %s -> %s: %w", tmpPath, libPath, err)
}
return libPath, nil
}
func (r *Runtime) Close() error {
if r == nil {
return ErrClosed
}
if r.closed.Swap(true) {
return ErrClosed
}
r.cancel()
return r.backend.Close(context.Background())
}
// ---------------------------------------------------------------------------
// Mat factory
// ---------------------------------------------------------------------------
func (r *Runtime) NewMat(rows, cols int, typ MatType) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
h, err := r.backend.NewMat(r.ctx, rows, cols, int32(typ))
if err != nil {
return nil, err
}
model := Unknown
switch typ {
case CV8UC1:
model = Gray
case CV8UC3:
model = BGR
case CV8UC4:
model = RGBA
}
return r.wrapMatWithModel(h, model), nil
}
// Zeros creates a Mat filled with zeros.
func (r *Runtime) Zeros(rows, cols int, typ MatType) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
h, err := r.backend.MatZeros(r.ctx, rows, cols, int32(typ))
if err != nil {
return nil, err
}
model := Unknown
switch typ {
case CV8UC1:
model = Gray
case CV8UC3:
model = BGR
case CV8UC4:
model = RGBA
}
return r.wrapMatWithModel(h, model), nil
}
// Ones creates a Mat filled with ones.
func (r *Runtime) Ones(rows, cols int, typ MatType) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
h, err := r.backend.MatOnes(r.ctx, rows, cols, int32(typ))
if err != nil {
return nil, err
}
return r.wrapMatWithModel(h, Unknown), nil
}
// Eye creates an identity matrix.
func (r *Runtime) Eye(rows, cols int, typ MatType) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
h, err := r.backend.MatEye(r.ctx, rows, cols, int32(typ))
if err != nil {
return nil, err
}
return r.wrapMatWithModel(h, Unknown), nil
}
// GetStructuringElement returns a structuring element of the specified size and shape for morphological operations.
func (r *Runtime) GetStructuringElement(shape MorphShape, ksize Size) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
h, err := r.backend.GetStructuringElement(r.ctx, int32(shape), ksize.Width, ksize.Height)
if err != nil {
return nil, err
}
return r.wrapMatWithModel(h, Unknown), nil
}
// ---------------------------------------------------------------------------
// Color conversion
// ---------------------------------------------------------------------------
func (r *Runtime) CvtColor(src, dst *Mat, code ColorConversionCode) error {
if err := validatePair(r, src, dst); err != nil {
return err
}
if StrictColorValidation() && src.model != Unknown {
if err := validateColorConversion(src.model, code); err != nil {
return err
}
}
if m, ok := outputModelForCode(src.model, code); ok {
dst.model = m
} else {
dst.model = Unknown
}
return r.backend.CvtColor(r.ctx, src.handle, dst.handle, int32(code))
}
// ---------------------------------------------------------------------------
// Geometry transforms
// ---------------------------------------------------------------------------
func (r *Runtime) Resize(src, dst *Mat, size Size) error {
if err := validatePair(r, src, dst); err != nil {
return err
}
dst.model = src.model
return r.backend.Resize(r.ctx, src.handle, dst.handle, size.Width, size.Height)
}
// Flip flips the src Mat and stores the result in dst.
func (r *Runtime) Flip(src, dst *Mat, flipCode FlipCode) error {
if err := validatePair(r, src, dst); err != nil {
return err
}
dst.model = src.model
return r.backend.Flip(r.ctx, src.handle, dst.handle, int32(flipCode))
}
// Transpose transposes the src Mat.
func (r *Runtime) Transpose(src *Mat) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
typ, _ := src.Type()
dst, err := r.NewMat(cols, rows, typ)
if err != nil {
return nil, fmt.Errorf("transpose: create output: %w", err)
}
if err := r.backend.Transpose(r.ctx, src.handle, dst.handle); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// WarpAffine applies an affine transformation to src using the 2x3 matrix M.
func (r *Runtime) WarpAffine(src *Mat, M *Mat, dsize Size) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
typ, _ := src.Type()
dst, err := r.NewMat(int(dsize.Height), int(dsize.Width), typ)
if err != nil {
return nil, fmt.Errorf("warp_affine: create output: %w", err)
}
if err := r.backend.WarpAffine(r.ctx, src.handle, dst.handle, M.handle, dsize.Width, dsize.Height); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// WarpPerspective applies a perspective transformation to src using the 3x3 matrix M.
func (r *Runtime) WarpPerspective(src *Mat, M *Mat, dsize Size) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
typ, _ := src.Type()
dst, err := r.NewMat(int(dsize.Height), int(dsize.Width), typ)
if err != nil {
return nil, fmt.Errorf("warp_perspective: create output: %w", err)
}
if err := r.backend.WarpPerspective(r.ctx, src.handle, dst.handle, M.handle, dsize.Width, dsize.Height); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// GetRotationMatrix2D returns a 2x3 affine transformation matrix for 2D rotation.
func (r *Runtime) GetRotationMatrix2D(center Point, angle, scale float64) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
h, err := r.backend.GetRotationMatrix2D(r.ctx, float64(center.X), float64(center.Y), angle, scale)
if err != nil {
return nil, err
}
return r.wrapMatWithModel(h, Unknown), nil
}
// GetAffineTransform returns a 2x3 affine transformation matrix from three point pairs.
func (r *Runtime) GetAffineTransform(src, dst [3]Point) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
h, err := r.backend.GetAffineTransform(r.ctx,
float64(src[0].X), float64(src[0].Y), float64(src[1].X), float64(src[1].Y), float64(src[2].X), float64(src[2].Y),
float64(dst[0].X), float64(dst[0].Y), float64(dst[1].X), float64(dst[1].Y), float64(dst[2].X), float64(dst[2].Y),
)
if err != nil {
return nil, err
}
return r.wrapMatWithModel(h, Unknown), nil
}
// ---------------------------------------------------------------------------
// Filtering
// ---------------------------------------------------------------------------
func (r *Runtime) Blur(src *Mat, kSize Size) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, err := src.Rows()
if err != nil {
return nil, fmt.Errorf("blur: rows: %w", err)
}
cols, err := src.Cols()
if err != nil {
return nil, fmt.Errorf("blur: cols: %w", err)
}
typ, err := src.Type()
if err != nil {
return nil, fmt.Errorf("blur: type: %w", err)
}
dst, err := r.NewMat(rows, cols, typ)
if err != nil {
return nil, fmt.Errorf("blur: create output: %w", err)
}
if err := r.backend.Blur(r.ctx, src.handle, dst.handle, kSize.Width, kSize.Height); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
func (r *Runtime) GaussianBlur(src *Mat, kSize Size, sigmaX float64) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, err := src.Rows()
if err != nil {
return nil, fmt.Errorf("gaussian blur: rows: %w", err)
}
cols, err := src.Cols()
if err != nil {
return nil, fmt.Errorf("gaussian blur: cols: %w", err)
}
typ, err := src.Type()
if err != nil {
return nil, fmt.Errorf("gaussian blur: type: %w", err)
}
dst, err := r.NewMat(rows, cols, typ)
if err != nil {
return nil, fmt.Errorf("gaussian blur: create output: %w", err)
}
if err := r.backend.GaussianBlur(r.ctx, src.handle, dst.handle, kSize.Width, kSize.Height, sigmaX); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// MedianBlur applies median blur with the given kernel size (must be odd, >1).
func (r *Runtime) MedianBlur(src *Mat, ksize int) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, err := src.Rows()
if err != nil {
return nil, fmt.Errorf("median blur: rows: %w", err)
}
cols, err := src.Cols()
if err != nil {
return nil, fmt.Errorf("median blur: cols: %w", err)
}
typ, err := src.Type()
if err != nil {
return nil, fmt.Errorf("median blur: type: %w", err)
}
dst, err := r.NewMat(rows, cols, typ)
if err != nil {
return nil, fmt.Errorf("median blur: create output: %w", err)
}
if err := r.backend.MedianBlur(r.ctx, src.handle, dst.handle, int32(ksize)); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
func (r *Runtime) Threshold(src *Mat, thresh, maxValue float64, typ ThresholdType) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, err := src.Rows()
if err != nil {
return nil, fmt.Errorf("threshold: rows: %w", err)
}
cols, err := src.Cols()
if err != nil {
return nil, fmt.Errorf("threshold: cols: %w", err)
}
t, err := src.Type()
if err != nil {
return nil, fmt.Errorf("threshold: type: %w", err)
}
dst, err := r.NewMat(rows, cols, t)
if err != nil {
return nil, fmt.Errorf("threshold: create output: %w", err)
}
if err := r.backend.Threshold(r.ctx, src.handle, dst.handle, thresh, maxValue, int32(typ)); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
func (r *Runtime) AdaptiveThreshold(src *Mat, maxValue float64, adaptiveType AdaptiveThresholdType, thresholdType ThresholdType, blockSize int, c float64) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, err := src.Rows()
if err != nil {
return nil, fmt.Errorf("adaptive threshold: rows: %w", err)
}
cols, err := src.Cols()
if err != nil {
return nil, fmt.Errorf("adaptive threshold: cols: %w", err)
}
t, err := src.Type()
if err != nil {
return nil, fmt.Errorf("adaptive threshold: type: %w", err)
}
dst, err := r.NewMat(rows, cols, t)
if err != nil {
return nil, fmt.Errorf("adaptive threshold: create output: %w", err)
}
if err := r.backend.AdaptiveThreshold(r.ctx, src.handle, dst.handle, maxValue, int32(adaptiveType), int32(thresholdType), int32(blockSize), c); err != nil {
dst.Close()
return nil, err
}
dst.model = Gray
return dst, nil
}
// Canny performs Canny edge detection on src and returns the edge mask.
func (r *Runtime) Canny(src *Mat, threshold1, threshold2 float64) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := src.validate(); err != nil {
return nil, err
}
rows, err := src.Rows()
if err != nil {
return nil, fmt.Errorf("canny: rows: %w", err)
}
cols, err := src.Cols()
if err != nil {
return nil, fmt.Errorf("canny: cols: %w", err)
}
dst, err := r.NewMat(rows, cols, CV8UC1)
if err != nil {
return nil, fmt.Errorf("canny: create output: %w", err)
}
if err := r.backend.Canny(r.ctx, src.handle, dst.handle, threshold1, threshold2); err != nil {
dst.Close()
return nil, err
}
dst.model = Gray
return dst, nil
}
// Sobel calculates the Sobel derivative image.
func (r *Runtime) Sobel(src *Mat, ddepth MatType, dx, dy, ksize int, scale, delta float64) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
dst, err := r.NewMat(rows, cols, ddepth)
if err != nil {
return nil, fmt.Errorf("sobel: create output: %w", err)
}
if err := r.backend.Sobel(r.ctx, src.handle, dst.handle, int32(ddepth), int32(dx), int32(dy), int32(ksize), scale, delta); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// Laplacian calculates the Laplacian of the image.
func (r *Runtime) Laplacian(src *Mat, ddepth MatType, ksize int, scale, delta float64) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
dst, err := r.NewMat(rows, cols, ddepth)
if err != nil {
return nil, fmt.Errorf("laplacian: create output: %w", err)
}
if err := r.backend.Laplacian(r.ctx, src.handle, dst.handle, int32(ddepth), int32(ksize), scale, delta); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// EqualizeHist equalizes the histogram of a grayscale image.
func (r *Runtime) EqualizeHist(src *Mat) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
dst, err := r.NewMat(rows, cols, CV8UC1)
if err != nil {
return nil, fmt.Errorf("equalize_hist: create output: %w", err)
}
if err := r.backend.EqualizeHist(r.ctx, src.handle, dst.handle); err != nil {
dst.Close()
return nil, err
}
dst.model = Gray
return dst, nil
}
// Normalize normalizes the input Mat.
func (r *Runtime) Normalize(src *Mat, alpha, beta float64, normType NormType) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
typ, _ := src.Type()
dst, err := r.NewMat(rows, cols, typ)
if err != nil {
return nil, fmt.Errorf("normalize: create output: %w", err)
}
if err := r.backend.Normalize(r.ctx, src.handle, dst.handle, alpha, beta, int32(normType)); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// ---------------------------------------------------------------------------
// Morphology
// ---------------------------------------------------------------------------
// Erode erodes the image using a structuring element.
func (r *Runtime) Erode(src *Mat, kernel *Mat, anchor Point, iterations int) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
typ, _ := src.Type()
dst, err := r.NewMat(rows, cols, typ)
if err != nil {
return nil, fmt.Errorf("erode: create output: %w", err)
}
var kh matHandle
if kernel != nil {
kh = kernel.handle
}
if err := r.backend.Erode(r.ctx, src.handle, dst.handle, kh, anchor.X, anchor.Y, int32(iterations)); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// Dilate dilates the image using a structuring element.
func (r *Runtime) Dilate(src *Mat, kernel *Mat, anchor Point, iterations int) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
typ, _ := src.Type()
dst, err := r.NewMat(rows, cols, typ)
if err != nil {
return nil, fmt.Errorf("dilate: create output: %w", err)
}
var kh matHandle
if kernel != nil {
kh = kernel.handle
}
if err := r.backend.Dilate(r.ctx, src.handle, dst.handle, kh, anchor.X, anchor.Y, int32(iterations)); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// MorphologyEx performs advanced morphological transformations.
func (r *Runtime) MorphologyEx(src *Mat, op MorphType, kernel *Mat, anchor Point, iterations int) (*Mat, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
rows, _ := src.Rows()
cols, _ := src.Cols()
typ, _ := src.Type()
dst, err := r.NewMat(rows, cols, typ)
if err != nil {
return nil, fmt.Errorf("morphology_ex: create output: %w", err)
}
var kh matHandle
if kernel != nil {
kh = kernel.handle
}
if err := r.backend.MorphologyEx(r.ctx, src.handle, dst.handle, int32(op), kh, anchor.X, anchor.Y, int32(iterations)); err != nil {
dst.Close()
return nil, err
}
dst.model = src.model
return dst, nil
}
// ---------------------------------------------------------------------------
// Drawing
// ---------------------------------------------------------------------------
func (r *Runtime) Rectangle(img *Mat, rect Rect, c color.Color, thickness int) error {
if err := r.validateOpen(); err != nil {
return err
}
if err := r.validateOwnedMat(img); err != nil {
return err
}
cr, cg, cb, ca := colorFetch(c)
return r.backend.Rectangle(
r.ctx, img.handle,
rect.X, rect.Y, rect.X+rect.Width, rect.Y+rect.Height,
cr, cg, cb, ca, int32(thickness),
)
}
func (r *Runtime) Circle(img *Mat, center Point, radius int, c color.Color, thickness int) error {
if err := r.validateOpen(); err != nil {
return err
}
if err := r.validateOwnedMat(img); err != nil {
return err
}
cr, cg, cb, ca := colorFetch(c)
return r.backend.Circle(r.ctx, img.handle, center.X, center.Y, int32(radius), cr, cg, cb, ca, int32(thickness))
}
func (r *Runtime) Line(img *Mat, point1, point2 Point, c color.Color, thickness int) error {
if err := r.validateOpen(); err != nil {
return err
}
if err := r.validateOwnedMat(img); err != nil {
return err
}
cr, cg, cb, ca := colorFetch(c)
return r.backend.Line(r.ctx, img.handle, point1.X, point1.Y, point2.X, point2.Y, cr, cg, cb, ca, int32(thickness))
}
// PutText draws a text string on the image.
func (r *Runtime) PutText(img *Mat, text string, org Point, fontFace HersheyFontType, fontScale float64, c color.Color, thickness int) error {
if err := r.validateOpen(); err != nil {
return err
}
if err := r.validateOwnedMat(img); err != nil {
return err
}
cr, cg, cb, ca := colorFetch(c)
textBytes := []byte(text)
return r.backend.PutText(
r.ctx, img.handle,
unsafe.Pointer(&textBytes[0]), int32(len(textBytes)),
org.X, org.Y, int32(fontFace), fontScale,
cr, cg, cb, ca, int32(thickness), int32(Line8), 0,
)
}
// ArrowedLine draws an arrow from point1 to point2.
func (r *Runtime) ArrowedLine(img *Mat, point1, point2 Point, c color.Color, thickness int, tipLength float64) error {
if err := r.validateOpen(); err != nil {
return err
}
if err := r.validateOwnedMat(img); err != nil {
return err
}
cr, cg, cb, ca := colorFetch(c)
return r.backend.ArrowedLine(r.ctx, img.handle, point1.X, point1.Y, point2.X, point2.Y, cr, cg, cb, ca, int32(thickness), int32(Line8), 0, tipLength)
}
// ---------------------------------------------------------------------------
// Contours
// ---------------------------------------------------------------------------
// FindContours finds contours in a binary image.
func (r *Runtime) FindContours(src *Mat, mode RetrievalMode, method ContourApproximationMode) ([][]Point, error) {
if err := r.validateOpen(); err != nil {
return nil, err
}
if err := r.validateOwnedMat(src); err != nil {
return nil, err
}
contoursVec, err := r.backend.VecVecPointsNew(r.ctx)
if err != nil {
return nil, fmt.Errorf("find_contours: create contours vec: %w", err)
}
defer r.backend.VecVecPointsDelete(r.ctx, contoursVec)
if err := r.backend.FindContours(r.ctx, src.handle, contoursVec, int32(mode), int32(method), 0, 0); err != nil {
return nil, fmt.Errorf("find_contours: %w", err)
}
nContours, err := r.backend.VecVecPointsLen(r.ctx, contoursVec)
if err != nil {
return nil, err
}
result := make([][]Point, nContours)
for i := 0; i < nContours; i++ {
contourVec, err := r.backend.VecVecPointsGet(r.ctx, contoursVec, int32(i))
if err != nil {
return nil, err
}
defer r.backend.VecPointsDelete(r.ctx, contourVec)
nPts, err := r.backend.VecPointsLen(r.ctx, contourVec)
if err != nil {
return nil, err
}
pts := make([]Point, nPts)
for j := 0; j < nPts; j++ {
x, y, err := r.backend.VecPointsGet(r.ctx, contourVec, int32(j))
if err != nil {
return nil, err
}
pts[j] = Point{X: x, Y: y}
}
result[i] = pts
}
return result, nil
}
// DrawContours draws contour outlines or filled contours.
func (r *Runtime) DrawContours(img *Mat, contours [][]Point, contourIdx int, c color.Color, thickness int) error {
if err := r.validateOpen(); err != nil {
return err
}
if err := r.validateOwnedMat(img); err != nil {
return err
}
contoursVec, err := r.backend.VecVecPointsNew(r.ctx)
if err != nil {
return err
}
defer r.backend.VecVecPointsDelete(r.ctx, contoursVec)
for _, contour := range contours {
ptVec, err := r.backend.VecPointsNew(r.ctx)
if err != nil {
return err
}
for _, pt := range contour {
r.backend.VecPointsPush(r.ctx, ptVec, pt.X, pt.Y)
}
r.backend.VecVecPointsPush(r.ctx, contoursVec, ptVec)
r.backend.VecPointsDelete(r.ctx, ptVec)
}
cr, cg, cb, ca := colorFetch(c)
return r.backend.DrawContours(r.ctx, img.handle, contoursVec, int32(contourIdx), cr, cg, cb, ca, int32(thickness))
}
// ContourArea computes the area of a contour.
func (r *Runtime) ContourArea(contour []Point) (float64, error) {
if err := r.validateOpen(); err != nil {
return 0, err
}
ptVec, err := r.backend.VecPointsNew(r.ctx)
if err != nil {
return 0, err
}