File: Mat.mm

package info (click to toggle)
opencv 4.10.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 282,092 kB
  • sloc: cpp: 1,178,079; xml: 682,621; python: 49,092; lisp: 31,150; java: 25,469; ansic: 11,039; javascript: 6,085; sh: 1,214; cs: 601; perl: 494; objc: 210; makefile: 173
file content (990 lines) | stat: -rw-r--r-- 34,929 bytes parent folder | download
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
//
//  Mat.m
//
//  Created by Giles Payne on 2019/10/06.
//

#import "Mat.h"
#import "Size2i.h"
#import "Scalar.h"
#import "Range.h"
#import "Rect2i.h"
#import "Point2i.h"
#import "CvType.h"
#import "CVObjcUtil.h"

#ifdef AVAILABLE_IMGCODECS
#import "MatConverters.h"
#import "MatQuickLook.h"
#endif

static int idx2Offset(cv::Mat* mat, std::vector<int>& indices) {
    int offset = indices[0];
    for (int dim=1; dim < mat->dims; dim++) {
        offset = offset*mat->size[dim] + indices[dim];
    }
    return offset;
}

static void offset2Idx(cv::Mat* mat, size_t offset, std::vector<int>& indices) {
    for (int dim=mat->dims-1; dim>=0; dim--) {
        indices[dim] = offset % mat->size[dim];
        offset = (offset - indices[dim]) / mat->size[dim];
    }
}

// returns true if final index was reached
static bool updateIdx(cv::Mat* mat, std::vector<int>& indices, size_t inc) {
    size_t currentOffset = idx2Offset(mat, indices);
    size_t newOffset = currentOffset + inc;
    bool reachedEnd = newOffset>=(size_t)mat->total();
    offset2Idx(mat, reachedEnd?0:newOffset, indices);
    return reachedEnd;
}

@implementation Mat {
    NSData* _nsdata;
}

- (cv::Mat&)nativeRef {
    return *_nativePtr;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _nativePtr = cv::Ptr<cv::Mat>(new cv::Mat());
    }
    return self;
}

- (instancetype)initWithNativeMat:(cv::Ptr<cv::Mat>)nativePtr {
    self = [super init];
    if (self) {
        _nativePtr = nativePtr;
    }
    return self;
}

+ (instancetype)fromNativePtr:(cv::Ptr<cv::Mat>)nativePtr {
    return [[Mat alloc] initWithNativeMat:nativePtr];
}

+ (instancetype)fromNative:(cv::Mat&)nativeRef {
    return [[Mat alloc] initWithNativeMat:cv::Ptr<cv::Mat>(new cv::Mat(nativeRef))];
}

- (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type {
    self = [super init];
    if (self) {
        _nativePtr = new cv::Mat(rows, cols, type);
    }
    return self;
}

- (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type data:(NSData*)data {
    self = [super init];
    if (self) {
        _nativePtr = new cv::Mat(rows, cols, type, (void*)data.bytes);
        _nsdata = data; // hold onto a reference otherwise this object might be deallocated
    }
    return self;
}

- (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type data:(NSData*)data step:(long)step {
    self = [super init];
    if (self) {
        _nativePtr = new cv::Mat(rows, cols, type, (void*)data.bytes, step);
        _nsdata = data; // hold onto a reference otherwise this object might be deallocated
    }
    return self;
}

- (instancetype)initWithSize:(Size2i*)size type:(int)type {
    self = [super init];
    if (self) {
        _nativePtr = new cv::Mat(size.height, size.width, type);
    }
    return self;
}

- (instancetype)initWithSizes:(NSArray<NSNumber*>*)sizes type:(int)type {
    self = [super init];
    if (self) {
        std::vector<int> vSizes;
        for (NSNumber* size in sizes) {
            vSizes.push_back(size.intValue);
        }
        _nativePtr = new cv::Mat((int)sizes.count, vSizes.data(), type);
    }
    return self;
}

- (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type scalar:(Scalar*)scalar {
    self = [super init];
    if (self) {
        cv::Scalar scalerTemp(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
        _nativePtr = new cv::Mat(rows, cols, type, scalerTemp);
    }
    return self;
}

- (instancetype)initWithSize:(Size2i*)size type:(int)type scalar:(Scalar *)scalar {
    self = [super init];
    if (self) {
        cv::Scalar scalerTemp(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
        _nativePtr = new cv::Mat(size.height, size.width, type, scalerTemp);
    }
    return self;
}

- (instancetype)initWithSizes:(NSArray<NSNumber*>*)sizes type:(int)type scalar:(Scalar *)scalar {
    self = [super init];
    if (self) {
        cv::Scalar scalerTemp(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
        std::vector<int> vSizes;
        for (NSNumber* size in sizes) {
            vSizes.push_back(size.intValue);
        }
        _nativePtr = new cv::Mat((int)sizes.count, vSizes.data(), type, scalerTemp);
    }
    return self;
}

- (instancetype)initWithMat:(Mat*)mat rowRange:(Range*)rowRange colRange:(Range*)colRange {
    self = [super init];
    if (self) {
        cv::Range rows(rowRange.start, rowRange.end);
        cv::Range cols(colRange.start, colRange.end);
        _nativePtr = new cv::Mat(*(cv::Mat*)mat.nativePtr, rows, cols);
    }
    return self;
}

- (instancetype)initWithMat:(Mat*)mat rowRange:(Range*)rowRange {
    self = [super init];
    if (self) {
        cv::Range rows(rowRange.start, rowRange.end);
        _nativePtr = new cv::Mat(*(cv::Mat*)mat.nativePtr, rows);
    }
    return self;
}

- (instancetype)initWithMat:(Mat*)mat ranges:(NSArray<Range*>*)ranges {
    self = [super init];
    if (self) {
        std::vector<cv::Range> tempRanges;
        for (Range* range in ranges) {
            tempRanges.push_back(cv::Range(range.start, range.end));
        }
        _nativePtr = new cv::Mat(mat.nativePtr->operator()(tempRanges));
    }
    return self;
}

- (instancetype)initWithMat:(Mat*)mat rect:(Rect2i*)roi {
    self = [super init];
    if (self) {
        cv::Range rows(roi.y, roi.y + roi.height);
        cv::Range cols(roi.x, roi.x + roi.width);
        _nativePtr = new cv::Mat(*(cv::Mat*)mat.nativePtr, rows, cols);
    }
    return self;
}

- (BOOL)isSameMat:(Mat*)mat {
    return self.nativePtr == mat.nativePtr;
}

- (Mat*)adjustRoiTop:(int)dtop bottom:(int)dbottom left:(int)dleft right:(int)dright {
    cv::Mat adjusted = _nativePtr->adjustROI(dtop, dbottom, dleft, dright);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(adjusted)];
}

- (void)assignTo:(Mat*)mat type:(int)type {
    _nativePtr->assignTo(*(cv::Mat*)mat.nativePtr, type);
}

- (void)assignTo:(Mat*)mat {
    _nativePtr->assignTo(*(cv::Mat*)mat.nativePtr);
}

- (int)channels {
    return _nativePtr->channels();
}

- (int)checkVector:(int)elemChannels depth:(int)depth requireContinuous:(BOOL) requireContinuous {
    return _nativePtr->checkVector(elemChannels, depth, requireContinuous);
}

- (int)checkVector:(int)elemChannels depth:(int)depth {
    return _nativePtr->checkVector(elemChannels, depth);
}

- (int)checkVector:(int)elemChannels {
    return _nativePtr->checkVector(elemChannels);
}

- (Mat*)clone {
    return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->clone()))];
}

- (Mat*)col:(int)x {
    return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->col(x)))];
}

- (Mat*)colRange:(int)start end:(int)end {
    return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->colRange(start, end)))];
}

- (Mat*)colRange:(Range*)range {
    return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->colRange(range.start, range.end)))];
}

- (int)dims {
    return _nativePtr->dims;
}

- (int)cols {
    return _nativePtr->cols;
}

- (void)convertTo:(Mat*)mat rtype:(int)rtype alpha:(double)alpha beta:(double)beta {
    _nativePtr->convertTo(*(cv::Mat*)mat->_nativePtr, rtype, alpha, beta);
}

- (void)convertTo:(Mat*)mat rtype:(int)rtype alpha:(double)alpha {
    _nativePtr->convertTo(*(cv::Mat*)mat->_nativePtr, rtype, alpha);
}

- (void)convertTo:(Mat*)mat rtype:(int)rtype {
    _nativePtr->convertTo(*(cv::Mat*)mat->_nativePtr, rtype);
}

- (void)copyTo:(Mat*)mat {
    _nativePtr->copyTo(*(cv::Mat*)mat->_nativePtr);
}

- (void)copyTo:(Mat*)mat mask:(Mat*)mask {
    _nativePtr->copyTo(*(cv::Mat*)mat->_nativePtr, *(cv::Mat*)mask->_nativePtr);
}

- (void)create:(int)rows cols:(int)cols type:(int)type {
    _nativePtr->create(rows, cols, type);
}

- (void)create:(Size2i*)size type:(int)type {
    cv::Size tempSize(size.width, size.height);
    _nativePtr->create(tempSize, type);
}

- (void)createEx:(NSArray<NSNumber*>*)sizes type:(int)type {
    std::vector<int> tempSizes;
    for (NSNumber* size in sizes) {
        tempSizes.push_back(size.intValue);
    }
    _nativePtr->create((int)tempSizes.size(), tempSizes.data(), type);
}

- (void)copySize:(Mat*)mat {
    _nativePtr->copySize(*(cv::Mat*)mat.nativePtr);
}

- (Mat*)cross:(Mat*)mat {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->cross(*(cv::Mat*)mat.nativePtr))];
}

- (unsigned char*)dataPtr {
    return _nativePtr->data;
}

- (int)depth {
    return _nativePtr->depth();
}

- (Mat*)diag:(int)diagonal {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->diag(diagonal))];
}

- (Mat*)diag {
    return [self diag:0];
}

+ (Mat*)diag:(Mat*)diagonal {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::diag(*(cv::Mat*)diagonal.nativePtr))];
}

- (double)dot:(Mat*)mat {
    return _nativePtr->dot(*(cv::Mat*)mat.nativePtr);
}

- (long)elemSize {
    return _nativePtr->elemSize();
}

- (long)elemSize1 {
    return _nativePtr->elemSize1();
}

- (BOOL)empty {
    return _nativePtr->empty();
}

+ (Mat*)eye:(int)rows cols:(int)cols type:(int)type {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::eye(rows, cols, type))];
}

+ (Mat*)eye:(Size2i*)size type:(int)type {
    cv::Size tempSize(size.width, size.height);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::eye(tempSize, type))];
}

- (Mat*)inv:(int)method {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->inv(method))];
}

- (Mat*)inv {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->inv())];
}

- (BOOL)isContinuous {
    return _nativePtr->isContinuous();
}

- (BOOL)isSubmatrix {
    return _nativePtr->isSubmatrix();
}

- (void)locateROI:(Size2i*)wholeSize ofs:(Point2i*)ofs {
    cv::Size tempWholeSize;
    cv::Point tempOfs;
    _nativePtr->locateROI(tempWholeSize, tempOfs);
    if (wholeSize != nil) {
        wholeSize.width = tempWholeSize.width;
        wholeSize.height = tempWholeSize.height;
    }
    if (ofs != nil) {
        ofs.x = tempOfs.x;
        ofs.y = tempOfs.y;
    }
}

- (Mat*)mul:(Mat*)mat scale:(double)scale {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->mul(*(cv::Mat*)mat.nativePtr, scale))];
}

- (Mat*)mul:(Mat*)mat {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->mul(*(cv::Mat*)mat.nativePtr))];
}

- (Mat*)matMul:(Mat*)mat {
    cv::Mat temp = self.nativeRef * mat.nativeRef;
    return [Mat fromNative:temp];
}

+ (Mat*)ones:(int)rows cols:(int)cols type:(int)type {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::ones(rows, cols, type))];
}

+ (Mat*)ones:(Size2i*)size type:(int)type {
    cv::Size tempSize(size.width, size.height);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::ones(tempSize, type))];
}

+ (Mat*)onesEx:(NSArray<NSNumber*>*)sizes type:(int)type {
    std::vector<int> tempSizes;
    for (NSNumber* size in sizes) {
        tempSizes.push_back(size.intValue);
    }
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::ones((int)tempSizes.size(), tempSizes.data(), type))];
}

- (void)push_back:(Mat*)mat {
    _nativePtr->push_back(*(cv::Mat*)mat.nativePtr);
}

- (Mat*)reshape:(int)channels rows:(int)rows {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->reshape(channels, rows))];
}

- (Mat*)reshape:(int)channels {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->reshape(channels))];
}

- (Mat*)reshape:(int)channels newshape:(NSArray<NSNumber*>*)newshape {
    std::vector<int> tempNewshape;
    for (NSNumber* size in newshape) {
        tempNewshape.push_back(size.intValue);
    }
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->reshape(channels, tempNewshape))];
}

- (Mat*)row:(int)y {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->row(y))];
}

- (Mat*)rowRange:(int)start end:(int)end {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->rowRange(start, end))];
}

- (Mat*)rowRange:(Range*)range {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->rowRange(range.start, range.end))];
}

- (int)rows {
    return _nativePtr->rows;
}

- (Mat*)setToScalar:(Scalar*)scalar {
    cv::Scalar tempScalar(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator=(tempScalar))];
}

- (Mat*)setToScalar:(Scalar*)scalar mask:(Mat*)mask {
    cv::Scalar tempScalar(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->setTo(tempScalar, *(cv::Mat*)mask.nativePtr))];
}

- (Mat*)setToValue:(Mat*)value mask:(Mat*)mask {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->setTo(*(cv::Mat*)value.nativePtr, *(cv::Mat*)mask.nativePtr))];
}

- (Mat*)setToValue:(Mat*)value {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->setTo(*(cv::Mat*)value.nativePtr))];
}

- (Size2i*)size {
    return [[Size2i alloc] initWithWidth:_nativePtr->size().width height:_nativePtr->size().height];
}

- (int)size:(int)dimIndex {
    return _nativePtr->size[dimIndex];
}

- (long)step1:(int)dimIndex {
    return _nativePtr->step1(dimIndex);
}

- (long)step1 {
    return _nativePtr->step1();
}

- (Mat*)submat:(int)rowStart rowEnd:(int)rowEnd colStart:(int)colStart colEnd:(int)colEnd {
    Range* rowRange = [[Range alloc] initWithStart:rowStart end:rowEnd];
    Range* colRange = [[Range alloc] initWithStart:colStart end:colEnd];
    return [self submat:rowRange colRange:colRange];
}

- (Mat*)submat:(Range*)rowRange colRange:(Range*)colRange {
    cv::Range tempRowRange(rowRange.start, rowRange.end);
    cv::Range tempColRange(colRange.start, colRange.end);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator()(tempRowRange, tempColRange))];
}

- (Mat*)submat:(NSArray<Range*>*)ranges {
    std::vector<cv::Range> tempRanges;
    for (Range* range in ranges) {
        tempRanges.push_back(cv::Range(range.start, range.end));
    }
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator()(tempRanges))];
}

- (Mat*)submatRoi:(Rect2i*)roi {
    cv::Rect tempRoi(roi.x, roi.y, roi.width, roi.height);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator()(tempRoi))];
}

- (Mat*)t {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->t())];
}

- (long)total {
    return _nativePtr->total();
}

- (int)type {
    return _nativePtr->type();
}

+ (Mat*)zeros:(int)rows cols:(int)cols type:(int)type {
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::zeros(rows, cols, type))];
}

+ (Mat*)zeros:(Size2i*)size type:(int)type {
    cv::Size tempSize(size.width, size.height);
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::zeros(tempSize, type))];
}

+ (Mat*)zerosEx:(NSArray<NSNumber*>*)sizes type:(int)type {
    std::vector<int> tempSizes;
    for (NSNumber* size in sizes) {
        tempSizes.push_back(size.intValue);
    }
    return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::zeros((int)tempSizes.size(), tempSizes.data(), type))];
}

- (NSString*)dimsDescription {
    if (_nativePtr->dims <= 0) {
        return @"-1*-1*";
    } else {
        NSMutableString* ret = [NSMutableString string];
        for (int index=0; index<_nativePtr->dims; index++) {
            [ret appendFormat:@"%d*", _nativePtr->size[index]];
        }
        return ret;
    }
}

- (NSString*)description {
    NSString* dimDesc = [self dimsDescription];
    return [NSString stringWithFormat:@"Mat [ %@%@, isCont=%s, isSubmat=%s, nativeObj=0x%p, dataAddr=0x%p ]", dimDesc, [CvType typeToString:_nativePtr->type()], _nativePtr->isContinuous()?"YES":"NO", _nativePtr->isSubmatrix()?"YES":"NO", (void*)_nativePtr, (void*)_nativePtr->data];
}

- (NSString*)dump {
    NSMutableString* ret = [NSMutableString string];
    cv::Ptr<cv::Formatted> formatted = cv::Formatter::get()->format(*_nativePtr);
    for(const char* format = formatted->next(); format; format = formatted->next()) {
        [ret appendFormat:@"%s", format];
    }
    return ret;
}

template<typename T> void putData(uchar* dataDest, int count, T (^readData)(int)) {
    T* tDataDest = (T*)dataDest;
    for (int index = 0; index < count; index++) {
        tDataDest[index] = readData(index);
    }
}

- (void)put:(uchar*)dest data:(NSArray<NSNumber*>*)data offset:(int)offset count:(int)count {
    int depth = _nativePtr->depth();
    if (depth == CV_8U) {
        putData(dest, count, ^uchar (int index) { return cv::saturate_cast<uchar>(data[offset + index].doubleValue);} );
    } else if (depth == CV_8S) {
        putData(dest, count, ^schar (int index) { return cv::saturate_cast<schar>(data[offset + index].doubleValue);} );
    } else if (depth == CV_16U) {
        putData(dest, count, ^ushort (int index) { return cv::saturate_cast<ushort>(data[offset + index].doubleValue);} );
    } else if (depth == CV_16S) {
        putData(dest, count, ^short (int index) { return cv::saturate_cast<short>(data[offset + index].doubleValue);} );
    } else if (depth == CV_32S) {
        putData(dest, count, ^int32_t (int index) { return cv::saturate_cast<int32_t>(data[offset + index].doubleValue);} );
    } else if (depth == CV_32F) {
        putData(dest, count, ^float (int index) { return cv::saturate_cast<float>(data[offset + index].doubleValue);} );
    } else if (depth == CV_64F) {
        putData(dest, count, ^double (int index) { return data[offset + index].doubleValue;} );
    }
}

- (int)put:(NSArray<NSNumber*>*)indices data:(NSArray<NSNumber*>*)data {
    cv::Mat* mat = _nativePtr;
    int type = mat->type();
    int rawValueSize = (int)(mat->elemSize() / mat->channels());
    if (data == nil || data.count % [CvType channels:type] != 0) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Provided data element number (%lu) should be multiple of the Mat channels count (%d)", (unsigned long)(data == nil ? 0 : data.count), [CvType channels:type]]
                userInfo:nil];
        @throw exception;
    }
    std::vector<int> tempIndices;
    for (NSNumber* index in indices) {
        tempIndices.push_back(index.intValue);
    }
    for (int index = 0; index < mat->dims; index++) {
        if (mat->size[index]<=tempIndices[index]) {
            return 0; // indexes out of range
        }
    }

    int arrayAvailable = (int)data.count;
    int matAvailable = getMatAvailable(mat, tempIndices);
    int available = MIN(arrayAvailable, matAvailable);
    int copyOffset = 0;
    int copyCount = MIN((mat->size[mat->dims - 1] - tempIndices[mat->dims - 1]) * mat->channels(), available);
    int result = (int)(available * rawValueSize);

    while (available > 0) {
        [self put:mat->ptr(tempIndices.data()) data:data offset:(int)copyOffset count:copyCount];
        if (updateIdx(mat, tempIndices, copyCount / mat->channels())) {
            break;
        }
        available -= copyCount;
        copyOffset += copyCount;
        copyCount = MIN(mat->size[mat->dims-1] * mat->channels(), available);
    }
    return result;
}

- (int)put:(int)row col:(int)col data:(NSArray<NSNumber*>*)data {
    NSArray<NSNumber*>* indices = @[[NSNumber numberWithInt:row], [NSNumber numberWithInt:col]];
    return [self put:indices data:data];
}

template<typename T> void getData(uchar* dataSource, int count, void (^writeData)(int,T)) {
    T* tDataSource = (T*)dataSource;
    for (int index = 0; index < count; index++) {
        writeData(index, tDataSource[index]);
    }
}

- (void)get:(uchar*)source data:(NSMutableArray<NSNumber*>*)data offset:(int)offset count:(int)count {
    int depth = _nativePtr->depth();
    if (depth == CV_8U) {
        getData(source, count, ^void (int index, uchar value) { data[offset + index] = [[NSNumber alloc] initWithUnsignedChar:value]; } );
    } else if (depth == CV_8S) {
        getData(source, count, ^void (int index, char value) { data[offset + index] = [[NSNumber alloc] initWithChar:value]; } );
    } else if (depth == CV_16U) {
        getData(source, count, ^void (int index, ushort value) { data[offset + index] = [[NSNumber alloc] initWithUnsignedShort:value]; } );
    } else if (depth == CV_16S) {
        getData(source, count, ^void (int index, short value) { data[offset + index] = [[NSNumber alloc] initWithShort:value]; } );
    } else if (depth == CV_32S) {
        getData(source, count, ^void (int index, int32_t value) { data[offset + index] = [[NSNumber alloc] initWithInt:value]; } );
    } else if (depth == CV_32F) {
        getData(source, count, ^void (int index, float value) { data[offset + index] = [[NSNumber alloc] initWithFloat:value]; } );
    } else if (depth == CV_64F) {
        getData(source, count, ^void (int index, double value) { data[offset + index] = [[NSNumber alloc] initWithDouble:value]; } );
    }
}

- (int)get:(NSArray<NSNumber*>*)indices data:(NSMutableArray<NSNumber*>*)data {
    cv::Mat* mat = _nativePtr;
    int type = mat->type();
    if (data == nil || data.count % [CvType channels:type] != 0) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Provided data element number (%lu) should be multiple of the Mat channels count (%d)", (unsigned long)(data == nil ? 0 : data.count), [CvType channels:type]]
                userInfo:nil];
        @throw exception;
    }
    std::vector<int> tempIndices;
    for (NSNumber* index in indices) {
        tempIndices.push_back(index.intValue);
    }
    for (int index = 0; index < mat->dims; index++) {
        if (mat->size[index]<=tempIndices[index]) {
            return 0; // indexes out of range
        }
    }

    int arrayAvailable = (int)data.count;
    int copyOffset = 0;
    int matAvailable = getMatAvailable(mat, tempIndices);
    int available = MIN(arrayAvailable, matAvailable);
    int copyCount = MIN((mat->size[mat->dims - 1] - tempIndices[mat->dims - 1]) * mat->channels(), available);
    int result = (int)(available * mat->elemSize() / mat->channels());

    while (available > 0) {
        [self get:mat->ptr(tempIndices.data()) data:data offset:(int)copyOffset count:copyCount];
        if (updateIdx(mat, tempIndices, copyCount / mat->channels())) {
            break;
        }
        available -= copyCount;
        copyOffset += copyCount;
        copyCount = MIN(mat->size[mat->dims-1] * mat->channels(), available);
    }
    return result;
}

- (int)get:(int)row col:(int)col data:(NSMutableArray<NSNumber*>*)data {
    NSArray<NSNumber*>* indices = @[[NSNumber numberWithInt:row], [NSNumber numberWithInt:col]];
    return [self get:indices data:data];
}

- (NSArray<NSNumber*>*)get:(int)row col:(int)col {
    NSMutableArray<NSNumber*>* result = [NSMutableArray new];
    for (int index = 0; index<_nativePtr->channels(); index++) {
        [result addObject:@0];
    }
    [self get:row col:col data:result];
    return result;
}

- (NSArray<NSNumber*>*)get:(NSArray<NSNumber*>*)indices {
    NSMutableArray<NSNumber*>* result = [NSMutableArray new];
    for (int index = 0; index<_nativePtr->channels(); index++) {
        [result addObject:@0];
    }
    [self get:indices data:result];
    return result;
}

template<typename T> void getData(uchar* source, void (^writeData)(int,T), int dataOffset, int dataLength) {
    T* tSource = (T*)source;
    for (int index = 0; index < dataLength; index++) {
        writeData(dataOffset+index, tSource[index]);
    }
}

int getMatAvailable(cv::Mat* mat, std::vector<int>& indices) {
    int blockSize = 1;
    int unavailableCount = 0;
    for (int index = mat->dims - 1; index >= 0; index--) {
        unavailableCount += blockSize * indices[index];
        blockSize *= mat->size[index];
    }
    return (int)(mat->channels() * (mat->total() - unavailableCount));
}

template<typename T> int getData(NSArray<NSNumber*>* indices, cv::Mat* mat, int count, T* tBuffer) {
    std::vector<int> tempIndices;
    for (NSNumber* index in indices) {
        tempIndices.push_back(index.intValue);
    }
    for (int index = 0; index < mat->dims; index++) {
        if (mat->size[index]<=tempIndices[index]) {
            return 0; // indexes out of range
        }
    }

    int arrayAvailable = count;
    size_t countBytes = count * sizeof(T);
    size_t remainingBytes = (size_t)(mat->total() - idx2Offset(mat, tempIndices))*mat->elemSize();
    countBytes = (countBytes>remainingBytes)?remainingBytes:countBytes;
    int result = (int)countBytes;
    int matAvailable = getMatAvailable(mat, tempIndices);
    int available = MIN(arrayAvailable, matAvailable);
    if (mat->isContinuous()) {
        memcpy(tBuffer, mat->ptr(tempIndices.data()), available * sizeof(T));
    } else {
        char* buff = (char*)tBuffer;
        size_t blockSize = mat->size[mat->dims-1] * mat->elemSize();
        size_t firstPartialBlockSize = (mat->size[mat->dims-1] - tempIndices[mat->dims-1]) * mat->step[mat->dims-1];
        for (int dim=mat->dims-2; dim>=0 && blockSize == mat->step[dim]; dim--) {
            blockSize *= mat->size[dim];
            firstPartialBlockSize += (mat->size[dim] - (tempIndices[dim]+1)) * mat->step[dim];
        }
        size_t copyCount = (countBytes<firstPartialBlockSize)?countBytes:firstPartialBlockSize;
        uchar* data = mat->ptr(tempIndices.data());
        while(countBytes>0) {
            memcpy(buff, data, copyCount);
            updateIdx(mat, tempIndices, copyCount / mat->elemSize());
            countBytes -= copyCount;
            buff += copyCount;
            copyCount = countBytes<blockSize?countBytes:blockSize;
            data = mat->ptr(tempIndices.data());
        }
    }
    return result;
}

- (int)get:(NSArray<NSNumber*>*)indices count:(int)count byteBuffer:(char*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_8U && depth != CV_8S) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_8U or CV_8S.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return getData(indices, _nativePtr, count, buffer);
}

- (int)get:(NSArray<NSNumber*>*)indices count:(int)count doubleBuffer:(double*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_64F) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_64F.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return getData(indices, _nativePtr, count, buffer);
}

- (int)get:(NSArray<NSNumber*>*)indices count:(int)count floatBuffer:(float*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_32F) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32F.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return getData(indices, _nativePtr, count, buffer);
}

- (int)get:(NSArray<NSNumber*>*)indices count:(int)count intBuffer:(int*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_32S) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32S.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return getData(indices, _nativePtr, count, buffer);
}

- (int)get:(NSArray<NSNumber*>*)indices count:(int)count shortBuffer:(short*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_16S && depth != CV_16U) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_16S and CV_16U.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return getData(indices, _nativePtr, count, buffer);
}

template<typename T> int putData(NSArray<NSNumber*>* indices, cv::Mat* mat, int count, const T* tBuffer)  {
    std::vector<int> tempIndices;
    for (NSNumber* index in indices) {
        tempIndices.push_back(index.intValue);
    }
    for (int index = 0; index < mat->dims; index++) {
        if (mat->size[index]<=tempIndices[index]) {
            return 0; // indexes out of range
        }
    }

    int arrayAvailable = count;
    size_t countBytes = count * sizeof(T);
    size_t remainingBytes = (size_t)(mat->total() - idx2Offset(mat, tempIndices))*mat->elemSize();
    countBytes = (countBytes>remainingBytes)?remainingBytes:countBytes;
    int result = (int)countBytes;
    int matAvailable = getMatAvailable(mat, tempIndices);
    int available = MIN(arrayAvailable, matAvailable);
    if (mat->isContinuous()) {
        memcpy(mat->ptr(tempIndices.data()), tBuffer, available * sizeof(T));
    } else {
        char* buff = (char*)tBuffer;
        size_t blockSize = mat->size[mat->dims-1] * mat->elemSize();
        size_t firstPartialBlockSize = (mat->size[mat->dims-1] - tempIndices[mat->dims-1]) * mat->step[mat->dims-1];
        for (int dim=mat->dims-2; dim>=0 && blockSize == mat->step[dim]; dim--) {
            blockSize *= mat->size[dim];
            firstPartialBlockSize += (mat->size[dim] - (tempIndices[dim]+1)) * mat->step[dim];
        }
        size_t copyCount = (countBytes<firstPartialBlockSize)?countBytes:firstPartialBlockSize;
        uchar* data = mat->ptr(tempIndices.data());
        while(countBytes>0){
            memcpy(data, buff, copyCount);
            updateIdx(mat, tempIndices, copyCount / mat->elemSize());
            countBytes -= copyCount;
            buff += copyCount;
            copyCount = countBytes<blockSize?countBytes:blockSize;
            data = mat->ptr(tempIndices.data());
        }
    }
    return result;
}

- (int)put:(NSArray<NSNumber*>*)indices count:(int)count byteBuffer:(const char*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_8U && depth != CV_8S) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_8U or CV_8S.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return putData(indices, _nativePtr, count, buffer);
}

- (int)put:(NSArray<NSNumber*>*)indices count:(int)count doubleBuffer:(const double*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_64F) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_64F.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return putData(indices, _nativePtr, count, buffer);
}

- (int)put:(NSArray<NSNumber*>*)indices count:(int)count floatBuffer:(const float*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_32F) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32F.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return putData(indices, _nativePtr, count, buffer);
}

- (int)put:(NSArray<NSNumber*>*)indices count:(int)count intBuffer:(const int*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_32S) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32S.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return putData(indices, _nativePtr, count, buffer);
}

- (int)put:(NSArray<NSNumber*>*)indices count:(int)count shortBuffer:(const short*)buffer {
    int depth = _nativePtr->depth();
    if (depth != CV_16S && depth != CV_16U) {
        NSException* exception = [NSException
                exceptionWithName:@"UnsupportedOperationException"
                                  reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_16S and CV_16U.", [CvType typeToString:depth]]
                userInfo:nil];
        @throw exception;
    }
    return putData(indices, _nativePtr, count, buffer);
}

- (int)height {
    return [self rows];
}

- (int)width {
    return [self cols];
}

#ifdef AVAILABLE_IMGCODECS

-(CGImageRef)toCGImage {
    return [MatConverters convertMatToCGImageRef:self];
}

-(instancetype)initWithCGImage:(CGImageRef)image {
    return [MatConverters convertCGImageRefToMat:image];
}

-(instancetype)initWithCGImage:(CGImageRef)image alphaExist:(BOOL)alphaExist {
    return [MatConverters convertCGImageRefToMat:image alphaExist:alphaExist];
}

#if TARGET_OS_IPHONE || TARGET_OS_VISION

-(UIImage*)toUIImage {
    return [MatConverters converMatToUIImage:self];
}

-(instancetype)initWithUIImage:(UIImage*)image {
    return [MatConverters convertUIImageToMat:image];
}

-(instancetype)initWithUIImage:(UIImage*)image alphaExist:(BOOL)alphaExist {
    return [MatConverters convertUIImageToMat:image alphaExist:alphaExist];
}

#elif TARGET_OS_MAC

-(NSImage*)toNSImage {
    return [MatConverters converMatToNSImage:self];
}

-(instancetype)initWithNSImage:(NSImage*)image {
    return [MatConverters convertNSImageToMat:image];
}

-(instancetype)initWithNSImage:(NSImage*)image alphaExist:(BOOL)alphaExist {
    return [MatConverters convertNSImageToMat:image alphaExist:alphaExist];
}

#endif

- (id)debugQuickLookObject {
    return [MatQuickLook matDebugQuickLookObject:self];
}

#endif

@end