Mat.mm 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. //
  2. // Mat.m
  3. //
  4. // Created by Giles Payne on 2019/10/06.
  5. //
  6. #import "Mat.h"
  7. #import "Size2i.h"
  8. #import "Scalar.h"
  9. #import "Range.h"
  10. #import "Rect2i.h"
  11. #import "Point2i.h"
  12. #import "CvType.h"
  13. #import "CVObjcUtil.h"
  14. static int idx2Offset(cv::Mat* mat, std::vector<int>& indices) {
  15. int offset = indices[0];
  16. for (int dim=1; dim < mat->dims; dim++) {
  17. offset = offset*mat->size[dim] + indices[dim];
  18. }
  19. return offset;
  20. }
  21. static void offset2Idx(cv::Mat* mat, size_t offset, std::vector<int>& indices) {
  22. for (int dim=mat->dims-1; dim>=0; dim--) {
  23. indices[dim] = offset % mat->size[dim];
  24. offset = (offset - indices[dim]) / mat->size[dim];
  25. }
  26. }
  27. // returns true if final index was reached
  28. static bool updateIdx(cv::Mat* mat, std::vector<int>& indices, size_t inc) {
  29. size_t currentOffset = idx2Offset(mat, indices);
  30. size_t newOffset = currentOffset + inc;
  31. bool reachedEnd = newOffset>=(size_t)mat->total();
  32. offset2Idx(mat, reachedEnd?0:newOffset, indices);
  33. return reachedEnd;
  34. }
  35. @implementation Mat {
  36. NSData* _nsdata;
  37. }
  38. - (cv::Mat&)nativeRef {
  39. return *_nativePtr;
  40. }
  41. - (instancetype)init {
  42. self = [super init];
  43. if (self) {
  44. _nativePtr = cv::Ptr<cv::Mat>(new cv::Mat());
  45. }
  46. return self;
  47. }
  48. - (instancetype)initWithNativeMat:(cv::Ptr<cv::Mat>)nativePtr {
  49. self = [super init];
  50. if (self) {
  51. _nativePtr = nativePtr;
  52. }
  53. return self;
  54. }
  55. + (instancetype)fromNativePtr:(cv::Ptr<cv::Mat>)nativePtr {
  56. return [[Mat alloc] initWithNativeMat:nativePtr];
  57. }
  58. + (instancetype)fromNative:(cv::Mat&)nativeRef {
  59. return [[Mat alloc] initWithNativeMat:cv::Ptr<cv::Mat>(new cv::Mat(nativeRef))];
  60. }
  61. - (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type {
  62. self = [super init];
  63. if (self) {
  64. _nativePtr = new cv::Mat(rows, cols, type);
  65. }
  66. return self;
  67. }
  68. - (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type data:(NSData*)data {
  69. self = [super init];
  70. if (self) {
  71. _nativePtr = new cv::Mat(rows, cols, type, (void*)data.bytes);
  72. _nsdata = data; // hold onto a reference otherwise this object might be deallocated
  73. }
  74. return self;
  75. }
  76. - (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type data:(NSData*)data step:(long)step {
  77. self = [super init];
  78. if (self) {
  79. _nativePtr = new cv::Mat(rows, cols, type, (void*)data.bytes, step);
  80. _nsdata = data; // hold onto a reference otherwise this object might be deallocated
  81. }
  82. return self;
  83. }
  84. - (instancetype)initWithSize:(Size2i*)size type:(int)type {
  85. self = [super init];
  86. if (self) {
  87. _nativePtr = new cv::Mat(size.width, size.height, type);
  88. }
  89. return self;
  90. }
  91. - (instancetype)initWithSizes:(NSArray<NSNumber*>*)sizes type:(int)type {
  92. self = [super init];
  93. if (self) {
  94. std::vector<int> vSizes;
  95. for (NSNumber* size in sizes) {
  96. vSizes.push_back(size.intValue);
  97. }
  98. _nativePtr = new cv::Mat((int)sizes.count, vSizes.data(), type);
  99. }
  100. return self;
  101. }
  102. - (instancetype)initWithRows:(int)rows cols:(int)cols type:(int)type scalar:(Scalar*)scalar {
  103. self = [super init];
  104. if (self) {
  105. cv::Scalar scalerTemp(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
  106. _nativePtr = new cv::Mat(rows, cols, type, scalerTemp);
  107. }
  108. return self;
  109. }
  110. - (instancetype)initWithSize:(Size2i*)size type:(int)type scalar:(Scalar *)scalar {
  111. self = [super init];
  112. if (self) {
  113. cv::Scalar scalerTemp(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
  114. _nativePtr = new cv::Mat(size.width, size.height, type, scalerTemp);
  115. }
  116. return self;
  117. }
  118. - (instancetype)initWithSizes:(NSArray<NSNumber*>*)sizes type:(int)type scalar:(Scalar *)scalar {
  119. self = [super init];
  120. if (self) {
  121. cv::Scalar scalerTemp(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
  122. std::vector<int> vSizes;
  123. for (NSNumber* size in sizes) {
  124. vSizes.push_back(size.intValue);
  125. }
  126. _nativePtr = new cv::Mat((int)sizes.count, vSizes.data(), type, scalerTemp);
  127. }
  128. return self;
  129. }
  130. - (instancetype)initWithMat:(Mat*)mat rowRange:(Range*)rowRange colRange:(Range*)colRange {
  131. self = [super init];
  132. if (self) {
  133. cv::Range rows(rowRange.start, rowRange.end);
  134. cv::Range cols(colRange.start, colRange.end);
  135. _nativePtr = new cv::Mat(*(cv::Mat*)mat.nativePtr, rows, cols);
  136. }
  137. return self;
  138. }
  139. - (instancetype)initWithMat:(Mat*)mat rowRange:(Range*)rowRange {
  140. self = [super init];
  141. if (self) {
  142. cv::Range rows(rowRange.start, rowRange.end);
  143. _nativePtr = new cv::Mat(*(cv::Mat*)mat.nativePtr, rows);
  144. }
  145. return self;
  146. }
  147. - (instancetype)initWithMat:(Mat*)mat ranges:(NSArray<Range*>*)ranges {
  148. self = [super init];
  149. if (self) {
  150. std::vector<cv::Range> tempRanges;
  151. for (Range* range in ranges) {
  152. tempRanges.push_back(cv::Range(range.start, range.end));
  153. }
  154. _nativePtr = new cv::Mat(mat.nativePtr->operator()(tempRanges));
  155. }
  156. return self;
  157. }
  158. - (instancetype)initWithMat:(Mat*)mat rect:(Rect2i*)roi {
  159. self = [super init];
  160. if (self) {
  161. cv::Range rows(roi.y, roi.y + roi.height);
  162. cv::Range cols(roi.x, roi.x + roi.width);
  163. _nativePtr = new cv::Mat(*(cv::Mat*)mat.nativePtr, rows, cols);
  164. }
  165. return self;
  166. }
  167. - (BOOL)isSameMat:(Mat*)mat {
  168. return self.nativePtr == mat.nativePtr;
  169. }
  170. - (Mat*)adjustRoiTop:(int)dtop bottom:(int)dbottom left:(int)dleft right:(int)dright {
  171. cv::Mat adjusted = _nativePtr->adjustROI(dtop, dbottom, dleft, dright);
  172. return [[Mat alloc] initWithNativeMat:new cv::Mat(adjusted)];
  173. }
  174. - (void)assignTo:(Mat*)mat type:(int)type {
  175. _nativePtr->assignTo(*(cv::Mat*)mat.nativePtr, type);
  176. }
  177. - (void)assignTo:(Mat*)mat {
  178. _nativePtr->assignTo(*(cv::Mat*)mat.nativePtr);
  179. }
  180. - (int)channels {
  181. return _nativePtr->channels();
  182. }
  183. - (int)checkVector:(int)elemChannels depth:(int)depth requireContinuous:(BOOL) requireContinuous {
  184. return _nativePtr->checkVector(elemChannels, depth, requireContinuous);
  185. }
  186. - (int)checkVector:(int)elemChannels depth:(int)depth {
  187. return _nativePtr->checkVector(elemChannels, depth);
  188. }
  189. - (int)checkVector:(int)elemChannels {
  190. return _nativePtr->checkVector(elemChannels);
  191. }
  192. - (Mat*)clone {
  193. return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->clone()))];
  194. }
  195. - (Mat*)col:(int)x {
  196. return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->col(x)))];
  197. }
  198. - (Mat*)colRange:(int)start end:(int)end {
  199. return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->colRange(start, end)))];
  200. }
  201. - (Mat*)colRange:(Range*)range {
  202. return [[Mat alloc] initWithNativeMat:(new cv::Mat(_nativePtr->colRange(range.start, range.end)))];
  203. }
  204. - (int)dims {
  205. return _nativePtr->dims;
  206. }
  207. - (int)cols {
  208. return _nativePtr->cols;
  209. }
  210. - (void)convertTo:(Mat*)mat rtype:(int)rtype alpha:(double)alpha beta:(double)beta {
  211. _nativePtr->convertTo(*(cv::Mat*)mat->_nativePtr, rtype, alpha, beta);
  212. }
  213. - (void)convertTo:(Mat*)mat rtype:(int)rtype alpha:(double)alpha {
  214. _nativePtr->convertTo(*(cv::Mat*)mat->_nativePtr, rtype, alpha);
  215. }
  216. - (void)convertTo:(Mat*)mat rtype:(int)rtype {
  217. _nativePtr->convertTo(*(cv::Mat*)mat->_nativePtr, rtype);
  218. }
  219. - (void)copyTo:(Mat*)mat {
  220. _nativePtr->copyTo(*(cv::Mat*)mat->_nativePtr);
  221. }
  222. - (void)copyTo:(Mat*)mat mask:(Mat*)mask {
  223. _nativePtr->copyTo(*(cv::Mat*)mat->_nativePtr, *(cv::Mat*)mask->_nativePtr);
  224. }
  225. - (void)create:(int)rows cols:(int)cols type:(int)type {
  226. _nativePtr->create(rows, cols, type);
  227. }
  228. - (void)create:(Size2i*)size type:(int)type {
  229. cv::Size tempSize(size.width, size.height);
  230. _nativePtr->create(tempSize, type);
  231. }
  232. - (void)createEx:(NSArray<NSNumber*>*)sizes type:(int)type {
  233. std::vector<int> tempSizes;
  234. for (NSNumber* size in sizes) {
  235. tempSizes.push_back(size.intValue);
  236. }
  237. _nativePtr->create((int)tempSizes.size(), tempSizes.data(), type);
  238. }
  239. - (void)copySize:(Mat*)mat {
  240. _nativePtr->copySize(*(cv::Mat*)mat.nativePtr);
  241. }
  242. - (Mat*)cross:(Mat*)mat {
  243. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->cross(*(cv::Mat*)mat.nativePtr))];
  244. }
  245. - (unsigned char*)dataPtr {
  246. return _nativePtr->data;
  247. }
  248. - (int)depth {
  249. return _nativePtr->depth();
  250. }
  251. - (Mat*)diag:(int)diagonal {
  252. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->diag(diagonal))];
  253. }
  254. - (Mat*)diag {
  255. return [self diag:0];
  256. }
  257. + (Mat*)diag:(Mat*)diagonal {
  258. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::diag(*(cv::Mat*)diagonal.nativePtr))];
  259. }
  260. - (double)dot:(Mat*)mat {
  261. return _nativePtr->dot(*(cv::Mat*)mat.nativePtr);
  262. }
  263. - (long)elemSize {
  264. return _nativePtr->elemSize();
  265. }
  266. - (long)elemSize1 {
  267. return _nativePtr->elemSize1();
  268. }
  269. - (BOOL)empty {
  270. return _nativePtr->empty();
  271. }
  272. + (Mat*)eye:(int)rows cols:(int)cols type:(int)type {
  273. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::eye(rows, cols, type))];
  274. }
  275. + (Mat*)eye:(Size2i*)size type:(int)type {
  276. cv::Size tempSize(size.width, size.height);
  277. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::eye(tempSize, type))];
  278. }
  279. - (Mat*)inv:(int)method {
  280. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->inv(method))];
  281. }
  282. - (Mat*)inv {
  283. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->inv())];
  284. }
  285. - (BOOL)isContinuous {
  286. return _nativePtr->isContinuous();
  287. }
  288. - (BOOL)isSubmatrix {
  289. return _nativePtr->isSubmatrix();
  290. }
  291. - (void)locateROI:(Size2i*)wholeSize ofs:(Point2i*)ofs {
  292. cv::Size tempWholeSize;
  293. cv::Point tempOfs;
  294. _nativePtr->locateROI(tempWholeSize, tempOfs);
  295. if (wholeSize != nil) {
  296. wholeSize.width = tempWholeSize.width;
  297. wholeSize.height = tempWholeSize.height;
  298. }
  299. if (ofs != nil) {
  300. ofs.x = tempOfs.x;
  301. ofs.y = tempOfs.y;
  302. }
  303. }
  304. - (Mat*)mul:(Mat*)mat scale:(double)scale {
  305. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->mul(*(cv::Mat*)mat.nativePtr, scale))];
  306. }
  307. - (Mat*)mul:(Mat*)mat {
  308. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->mul(*(cv::Mat*)mat.nativePtr))];
  309. }
  310. - (Mat*)matMul:(Mat*)mat {
  311. cv::Mat temp = self.nativeRef * mat.nativeRef;
  312. return [Mat fromNative:temp];
  313. }
  314. + (Mat*)ones:(int)rows cols:(int)cols type:(int)type {
  315. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::ones(rows, cols, type))];
  316. }
  317. + (Mat*)ones:(Size2i*)size type:(int)type {
  318. cv::Size tempSize(size.width, size.height);
  319. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::ones(tempSize, type))];
  320. }
  321. + (Mat*)onesEx:(NSArray<NSNumber*>*)sizes type:(int)type {
  322. std::vector<int> tempSizes;
  323. for (NSNumber* size in sizes) {
  324. tempSizes.push_back(size.intValue);
  325. }
  326. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::ones((int)tempSizes.size(), tempSizes.data(), type))];
  327. }
  328. - (void)push_back:(Mat*)mat {
  329. _nativePtr->push_back(*(cv::Mat*)mat.nativePtr);
  330. }
  331. - (Mat*)reshape:(int)channels rows:(int)rows {
  332. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->reshape(channels, rows))];
  333. }
  334. - (Mat*)reshape:(int)channels {
  335. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->reshape(channels))];
  336. }
  337. - (Mat*)reshape:(int)channels newshape:(NSArray<NSNumber*>*)newshape {
  338. std::vector<int> tempNewshape;
  339. for (NSNumber* size in newshape) {
  340. tempNewshape.push_back(size.intValue);
  341. }
  342. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->reshape(channels, tempNewshape))];
  343. }
  344. - (Mat*)row:(int)y {
  345. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->row(y))];
  346. }
  347. - (Mat*)rowRange:(int)start end:(int)end {
  348. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->rowRange(start, end))];
  349. }
  350. - (Mat*)rowRange:(Range*)range {
  351. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->rowRange(range.start, range.end))];
  352. }
  353. - (int)rows {
  354. return _nativePtr->rows;
  355. }
  356. - (Mat*)setToScalar:(Scalar*)scalar {
  357. cv::Scalar tempScalar(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
  358. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator=(tempScalar))];
  359. }
  360. - (Mat*)setToScalar:(Scalar*)scalar mask:(Mat*)mask {
  361. cv::Scalar tempScalar(scalar.val[0].doubleValue, scalar.val[1].doubleValue, scalar.val[2].doubleValue, scalar.val[3].doubleValue);
  362. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->setTo(tempScalar, *(cv::Mat*)mask.nativePtr))];
  363. }
  364. - (Mat*)setToValue:(Mat*)value mask:(Mat*)mask {
  365. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->setTo(*(cv::Mat*)value.nativePtr, *(cv::Mat*)mask.nativePtr))];
  366. }
  367. - (Mat*)setToValue:(Mat*)value {
  368. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->setTo(*(cv::Mat*)value.nativePtr))];
  369. }
  370. - (Size2i*)size {
  371. return [[Size2i alloc] initWithWidth:_nativePtr->size().width height:_nativePtr->size().height];
  372. }
  373. - (int)size:(int)dimIndex {
  374. return _nativePtr->size[dimIndex];
  375. }
  376. - (long)step1:(int)dimIndex {
  377. return _nativePtr->step1(dimIndex);
  378. }
  379. - (long)step1 {
  380. return _nativePtr->step1();
  381. }
  382. - (Mat*)submat:(int)rowStart rowEnd:(int)rowEnd colStart:(int)colStart colEnd:(int)colEnd {
  383. Range* rowRange = [[Range alloc] initWithStart:rowStart end:rowEnd];
  384. Range* colRange = [[Range alloc] initWithStart:colStart end:colEnd];
  385. return [self submat:rowRange colRange:colRange];
  386. }
  387. - (Mat*)submat:(Range*)rowRange colRange:(Range*)colRange {
  388. cv::Range tempRowRange(rowRange.start, rowRange.end);
  389. cv::Range tempColRange(colRange.start, colRange.end);
  390. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator()(tempRowRange, tempColRange))];
  391. }
  392. - (Mat*)submat:(NSArray<Range*>*)ranges {
  393. std::vector<cv::Range> tempRanges;
  394. for (Range* range in ranges) {
  395. tempRanges.push_back(cv::Range(range.start, range.end));
  396. }
  397. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator()(tempRanges))];
  398. }
  399. - (Mat*)submatRoi:(Rect2i*)roi {
  400. cv::Rect tempRoi(roi.x, roi.y, roi.width, roi.height);
  401. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->operator()(tempRoi))];
  402. }
  403. - (Mat*)t {
  404. return [[Mat alloc] initWithNativeMat:new cv::Mat(_nativePtr->t())];
  405. }
  406. - (long)total {
  407. return _nativePtr->total();
  408. }
  409. - (int)type {
  410. return _nativePtr->type();
  411. }
  412. + (Mat*)zeros:(int)rows cols:(int)cols type:(int)type {
  413. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::zeros(rows, cols, type))];
  414. }
  415. + (Mat*)zeros:(Size2i*)size type:(int)type {
  416. cv::Size tempSize(size.width, size.height);
  417. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::zeros(tempSize, type))];
  418. }
  419. + (Mat*)zerosEx:(NSArray<NSNumber*>*)sizes type:(int)type {
  420. std::vector<int> tempSizes;
  421. for (NSNumber* size in sizes) {
  422. tempSizes.push_back(size.intValue);
  423. }
  424. return [[Mat alloc] initWithNativeMat:new cv::Mat(cv::Mat::zeros((int)tempSizes.size(), tempSizes.data(), type))];
  425. }
  426. - (NSString*)dimsDescription {
  427. if (_nativePtr->dims <= 0) {
  428. return @"-1*-1*";
  429. } else {
  430. NSMutableString* ret = [NSMutableString string];
  431. for (int index=0; index<_nativePtr->dims; index++) {
  432. [ret appendFormat:@"%d*", _nativePtr->size[index]];
  433. }
  434. return ret;
  435. }
  436. }
  437. - (NSString*)description {
  438. NSString* dimDesc = [self dimsDescription];
  439. 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];
  440. }
  441. - (NSString*)dump {
  442. NSMutableString* ret = [NSMutableString string];
  443. cv::Ptr<cv::Formatted> formatted = cv::Formatter::get()->format(*_nativePtr);
  444. for(const char* format = formatted->next(); format; format = formatted->next()) {
  445. [ret appendFormat:@"%s", format];
  446. }
  447. return ret;
  448. }
  449. template<typename T> void putData(uchar* dataDest, int count, T (^readData)(int)) {
  450. T* tDataDest = (T*)dataDest;
  451. for (int index = 0; index < count; index++) {
  452. tDataDest[index] = readData(index);
  453. }
  454. }
  455. - (void)put:(uchar*)dest data:(NSArray<NSNumber*>*)data offset:(int)offset count:(int)count {
  456. int depth = _nativePtr->depth();
  457. if (depth == CV_8U) {
  458. putData(dest, count, ^uchar (int index) { return cv::saturate_cast<uchar>(data[offset + index].doubleValue);} );
  459. } else if (depth == CV_8S) {
  460. putData(dest, count, ^schar (int index) { return cv::saturate_cast<schar>(data[offset + index].doubleValue);} );
  461. } else if (depth == CV_16U) {
  462. putData(dest, count, ^ushort (int index) { return cv::saturate_cast<ushort>(data[offset + index].doubleValue);} );
  463. } else if (depth == CV_16S) {
  464. putData(dest, count, ^short (int index) { return cv::saturate_cast<short>(data[offset + index].doubleValue);} );
  465. } else if (depth == CV_32S) {
  466. putData(dest, count, ^int32_t (int index) { return cv::saturate_cast<int32_t>(data[offset + index].doubleValue);} );
  467. } else if (depth == CV_32F) {
  468. putData(dest, count, ^float (int index) { return cv::saturate_cast<float>(data[offset + index].doubleValue);} );
  469. } else if (depth == CV_64F) {
  470. putData(dest, count, ^double (int index) { return data[offset + index].doubleValue;} );
  471. }
  472. }
  473. - (int)put:(NSArray<NSNumber*>*)indices data:(NSArray<NSNumber*>*)data {
  474. cv::Mat* mat = _nativePtr;
  475. int type = mat->type();
  476. int rawValueSize = (int)(mat->elemSize() / mat->channels());
  477. if (data == nil || data.count % [CvType channels:type] != 0) {
  478. NSException* exception = [NSException
  479. exceptionWithName:@"UnsupportedOperationException"
  480. 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]]
  481. userInfo:nil];
  482. @throw exception;
  483. }
  484. std::vector<int> tempIndices;
  485. for (NSNumber* index in indices) {
  486. tempIndices.push_back(index.intValue);
  487. }
  488. for (int index = 0; index < mat->dims; index++) {
  489. if (mat->size[index]<=tempIndices[index]) {
  490. return 0; // indexes out of range
  491. }
  492. }
  493. int arrayAvailable = (int)data.count;
  494. int matAvailable = getMatAvailable(mat, tempIndices);
  495. int available = MIN(arrayAvailable, matAvailable);
  496. int copyOffset = 0;
  497. int copyCount = MIN((mat->size[mat->dims - 1] - tempIndices[mat->dims - 1]) * mat->channels(), available);
  498. int result = (int)(available * rawValueSize);
  499. while (available > 0) {
  500. [self put:mat->ptr(tempIndices.data()) data:data offset:(int)copyOffset count:copyCount];
  501. if (updateIdx(mat, tempIndices, copyCount / mat->channels())) {
  502. break;
  503. }
  504. available -= copyCount;
  505. copyOffset += copyCount;
  506. copyCount = MIN(mat->size[mat->dims-1] * mat->channels(), available);
  507. }
  508. return result;
  509. }
  510. - (int)put:(int)row col:(int)col data:(NSArray<NSNumber*>*)data {
  511. NSArray<NSNumber*>* indices = @[[NSNumber numberWithInt:row], [NSNumber numberWithInt:col]];
  512. return [self put:indices data:data];
  513. }
  514. template<typename T> void getData(uchar* dataSource, int count, void (^writeData)(int,T)) {
  515. T* tDataSource = (T*)dataSource;
  516. for (int index = 0; index < count; index++) {
  517. writeData(index, tDataSource[index]);
  518. }
  519. }
  520. - (void)get:(uchar*)source data:(NSMutableArray<NSNumber*>*)data offset:(int)offset count:(int)count {
  521. int depth = _nativePtr->depth();
  522. if (depth == CV_8U) {
  523. getData(source, count, ^void (int index, uchar value) { data[offset + index] = [[NSNumber alloc] initWithUnsignedChar:value]; } );
  524. } else if (depth == CV_8S) {
  525. getData(source, count, ^void (int index, char value) { data[offset + index] = [[NSNumber alloc] initWithChar:value]; } );
  526. } else if (depth == CV_16U) {
  527. getData(source, count, ^void (int index, ushort value) { data[offset + index] = [[NSNumber alloc] initWithUnsignedShort:value]; } );
  528. } else if (depth == CV_16S) {
  529. getData(source, count, ^void (int index, short value) { data[offset + index] = [[NSNumber alloc] initWithShort:value]; } );
  530. } else if (depth == CV_32S) {
  531. getData(source, count, ^void (int index, int32_t value) { data[offset + index] = [[NSNumber alloc] initWithInt:value]; } );
  532. } else if (depth == CV_32F) {
  533. getData(source, count, ^void (int index, float value) { data[offset + index] = [[NSNumber alloc] initWithFloat:value]; } );
  534. } else if (depth == CV_64F) {
  535. getData(source, count, ^void (int index, double value) { data[offset + index] = [[NSNumber alloc] initWithDouble:value]; } );
  536. }
  537. }
  538. - (int)get:(NSArray<NSNumber*>*)indices data:(NSMutableArray<NSNumber*>*)data {
  539. cv::Mat* mat = _nativePtr;
  540. int type = mat->type();
  541. if (data == nil || data.count % [CvType channels:type] != 0) {
  542. NSException* exception = [NSException
  543. exceptionWithName:@"UnsupportedOperationException"
  544. 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]]
  545. userInfo:nil];
  546. @throw exception;
  547. }
  548. std::vector<int> tempIndices;
  549. for (NSNumber* index in indices) {
  550. tempIndices.push_back(index.intValue);
  551. }
  552. for (int index = 0; index < mat->dims; index++) {
  553. if (mat->size[index]<=tempIndices[index]) {
  554. return 0; // indexes out of range
  555. }
  556. }
  557. int arrayAvailable = (int)data.count;
  558. int copyOffset = 0;
  559. int matAvailable = getMatAvailable(mat, tempIndices);
  560. int available = MIN(arrayAvailable, matAvailable);
  561. int copyCount = MIN((mat->size[mat->dims - 1] - tempIndices[mat->dims - 1]) * mat->channels(), available);
  562. int result = (int)(available * mat->elemSize() / mat->channels());
  563. while (available > 0) {
  564. [self get:mat->ptr(tempIndices.data()) data:data offset:(int)copyOffset count:copyCount];
  565. if (updateIdx(mat, tempIndices, copyCount / mat->channels())) {
  566. break;
  567. }
  568. available -= copyCount;
  569. copyOffset += copyCount;
  570. copyCount = MIN(mat->size[mat->dims-1] * mat->channels(), available);
  571. }
  572. return result;
  573. }
  574. - (int)get:(int)row col:(int)col data:(NSMutableArray<NSNumber*>*)data {
  575. NSArray<NSNumber*>* indices = @[[NSNumber numberWithInt:row], [NSNumber numberWithInt:col]];
  576. return [self get:indices data:data];
  577. }
  578. - (NSArray<NSNumber*>*)get:(int)row col:(int)col {
  579. NSMutableArray<NSNumber*>* result = [NSMutableArray new];
  580. for (int index = 0; index<_nativePtr->channels(); index++) {
  581. [result addObject:@0];
  582. }
  583. [self get:row col:col data:result];
  584. return result;
  585. }
  586. - (NSArray<NSNumber*>*)get:(NSArray<NSNumber*>*)indices {
  587. NSMutableArray<NSNumber*>* result = [NSMutableArray new];
  588. for (int index = 0; index<_nativePtr->channels(); index++) {
  589. [result addObject:@0];
  590. }
  591. [self get:indices data:result];
  592. return result;
  593. }
  594. template<typename T> void getData(uchar* source, void (^writeData)(int,T), int dataOffset, int dataLength) {
  595. T* tSource = (T*)source;
  596. for (int index = 0; index < dataLength; index++) {
  597. writeData(dataOffset+index, tSource[index]);
  598. }
  599. }
  600. int getMatAvailable(cv::Mat* mat, std::vector<int>& indices) {
  601. int blockSize = 1;
  602. int unavailableCount = 0;
  603. for (int index = mat->dims - 1; index >= 0; index--) {
  604. unavailableCount += blockSize * indices[index];
  605. blockSize *= mat->size[index];
  606. }
  607. return (int)(mat->channels() * (mat->total() - unavailableCount));
  608. }
  609. template<typename T> int getData(NSArray<NSNumber*>* indices, cv::Mat* mat, int count, T* tBuffer) {
  610. std::vector<int> tempIndices;
  611. for (NSNumber* index in indices) {
  612. tempIndices.push_back(index.intValue);
  613. }
  614. for (int index = 0; index < mat->dims; index++) {
  615. if (mat->size[index]<=tempIndices[index]) {
  616. return 0; // indexes out of range
  617. }
  618. }
  619. int arrayAvailable = count;
  620. size_t countBytes = count * sizeof(T);
  621. size_t remainingBytes = (size_t)(mat->total() - idx2Offset(mat, tempIndices))*mat->elemSize();
  622. countBytes = (countBytes>remainingBytes)?remainingBytes:countBytes;
  623. int result = (int)countBytes;
  624. int matAvailable = getMatAvailable(mat, tempIndices);
  625. int available = MIN(arrayAvailable, matAvailable);
  626. if (mat->isContinuous()) {
  627. memcpy(tBuffer, mat->ptr(tempIndices.data()), available * sizeof(T));
  628. } else {
  629. char* buff = (char*)tBuffer;
  630. size_t blockSize = mat->size[mat->dims-1] * mat->elemSize();
  631. size_t firstPartialBlockSize = (mat->size[mat->dims-1] - tempIndices[mat->dims-1]) * mat->step[mat->dims-1];
  632. for (int dim=mat->dims-2; dim>=0 && blockSize == mat->step[dim]; dim--) {
  633. blockSize *= mat->size[dim];
  634. firstPartialBlockSize += (mat->size[dim] - (tempIndices[dim]+1)) * mat->step[dim];
  635. }
  636. size_t copyCount = (countBytes<firstPartialBlockSize)?countBytes:firstPartialBlockSize;
  637. uchar* data = mat->ptr(tempIndices.data());
  638. while(countBytes>0) {
  639. memcpy(buff, data, copyCount);
  640. updateIdx(mat, tempIndices, copyCount / mat->elemSize());
  641. countBytes -= copyCount;
  642. buff += copyCount;
  643. copyCount = countBytes<blockSize?countBytes:blockSize;
  644. data = mat->ptr(tempIndices.data());
  645. }
  646. }
  647. return result;
  648. }
  649. - (int)get:(NSArray<NSNumber*>*)indices count:(int)count byteBuffer:(char*)buffer {
  650. int depth = _nativePtr->depth();
  651. if (depth != CV_8U && depth != CV_8S) {
  652. NSException* exception = [NSException
  653. exceptionWithName:@"UnsupportedOperationException"
  654. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_8U or CV_8S.", [CvType typeToString:depth]]
  655. userInfo:nil];
  656. @throw exception;
  657. }
  658. return getData(indices, _nativePtr, count, buffer);
  659. }
  660. - (int)get:(NSArray<NSNumber*>*)indices count:(int)count doubleBuffer:(double*)buffer {
  661. int depth = _nativePtr->depth();
  662. if (depth != CV_64F) {
  663. NSException* exception = [NSException
  664. exceptionWithName:@"UnsupportedOperationException"
  665. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_64F.", [CvType typeToString:depth]]
  666. userInfo:nil];
  667. @throw exception;
  668. }
  669. return getData(indices, _nativePtr, count, buffer);
  670. }
  671. - (int)get:(NSArray<NSNumber*>*)indices count:(int)count floatBuffer:(float*)buffer {
  672. int depth = _nativePtr->depth();
  673. if (depth != CV_32F) {
  674. NSException* exception = [NSException
  675. exceptionWithName:@"UnsupportedOperationException"
  676. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32F.", [CvType typeToString:depth]]
  677. userInfo:nil];
  678. @throw exception;
  679. }
  680. return getData(indices, _nativePtr, count, buffer);
  681. }
  682. - (int)get:(NSArray<NSNumber*>*)indices count:(int)count intBuffer:(int*)buffer {
  683. int depth = _nativePtr->depth();
  684. if (depth != CV_32S) {
  685. NSException* exception = [NSException
  686. exceptionWithName:@"UnsupportedOperationException"
  687. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32S.", [CvType typeToString:depth]]
  688. userInfo:nil];
  689. @throw exception;
  690. }
  691. return getData(indices, _nativePtr, count, buffer);
  692. }
  693. - (int)get:(NSArray<NSNumber*>*)indices count:(int)count shortBuffer:(short*)buffer {
  694. int depth = _nativePtr->depth();
  695. if (depth != CV_16S && depth != CV_16U) {
  696. NSException* exception = [NSException
  697. exceptionWithName:@"UnsupportedOperationException"
  698. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_16S and CV_16U.", [CvType typeToString:depth]]
  699. userInfo:nil];
  700. @throw exception;
  701. }
  702. return getData(indices, _nativePtr, count, buffer);
  703. }
  704. template<typename T> int putData(NSArray<NSNumber*>* indices, cv::Mat* mat, int count, const T* tBuffer) {
  705. std::vector<int> tempIndices;
  706. for (NSNumber* index in indices) {
  707. tempIndices.push_back(index.intValue);
  708. }
  709. for (int index = 0; index < mat->dims; index++) {
  710. if (mat->size[index]<=tempIndices[index]) {
  711. return 0; // indexes out of range
  712. }
  713. }
  714. int arrayAvailable = count;
  715. size_t countBytes = count * sizeof(T);
  716. size_t remainingBytes = (size_t)(mat->total() - idx2Offset(mat, tempIndices))*mat->elemSize();
  717. countBytes = (countBytes>remainingBytes)?remainingBytes:countBytes;
  718. int result = (int)countBytes;
  719. int matAvailable = getMatAvailable(mat, tempIndices);
  720. int available = MIN(arrayAvailable, matAvailable);
  721. if (mat->isContinuous()) {
  722. memcpy(mat->ptr(tempIndices.data()), tBuffer, available * sizeof(T));
  723. } else {
  724. char* buff = (char*)tBuffer;
  725. size_t blockSize = mat->size[mat->dims-1] * mat->elemSize();
  726. size_t firstPartialBlockSize = (mat->size[mat->dims-1] - tempIndices[mat->dims-1]) * mat->step[mat->dims-1];
  727. for (int dim=mat->dims-2; dim>=0 && blockSize == mat->step[dim]; dim--) {
  728. blockSize *= mat->size[dim];
  729. firstPartialBlockSize += (mat->size[dim] - (tempIndices[dim]+1)) * mat->step[dim];
  730. }
  731. size_t copyCount = (countBytes<firstPartialBlockSize)?countBytes:firstPartialBlockSize;
  732. uchar* data = mat->ptr(tempIndices.data());
  733. while(countBytes>0){
  734. memcpy(data, buff, copyCount);
  735. updateIdx(mat, tempIndices, copyCount / mat->elemSize());
  736. countBytes -= copyCount;
  737. buff += copyCount;
  738. copyCount = countBytes<blockSize?countBytes:blockSize;
  739. data = mat->ptr(tempIndices.data());
  740. }
  741. }
  742. return result;
  743. }
  744. - (int)put:(NSArray<NSNumber*>*)indices count:(int)count byteBuffer:(const char*)buffer {
  745. int depth = _nativePtr->depth();
  746. if (depth != CV_8U && depth != CV_8S) {
  747. NSException* exception = [NSException
  748. exceptionWithName:@"UnsupportedOperationException"
  749. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_8U or CV_8S.", [CvType typeToString:depth]]
  750. userInfo:nil];
  751. @throw exception;
  752. }
  753. return putData(indices, _nativePtr, count, buffer);
  754. }
  755. - (int)put:(NSArray<NSNumber*>*)indices count:(int)count doubleBuffer:(const double*)buffer {
  756. int depth = _nativePtr->depth();
  757. if (depth != CV_64F) {
  758. NSException* exception = [NSException
  759. exceptionWithName:@"UnsupportedOperationException"
  760. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_64F.", [CvType typeToString:depth]]
  761. userInfo:nil];
  762. @throw exception;
  763. }
  764. return putData(indices, _nativePtr, count, buffer);
  765. }
  766. - (int)put:(NSArray<NSNumber*>*)indices count:(int)count floatBuffer:(const float*)buffer {
  767. int depth = _nativePtr->depth();
  768. if (depth != CV_32F) {
  769. NSException* exception = [NSException
  770. exceptionWithName:@"UnsupportedOperationException"
  771. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32F.", [CvType typeToString:depth]]
  772. userInfo:nil];
  773. @throw exception;
  774. }
  775. return putData(indices, _nativePtr, count, buffer);
  776. }
  777. - (int)put:(NSArray<NSNumber*>*)indices count:(int)count intBuffer:(const int*)buffer {
  778. int depth = _nativePtr->depth();
  779. if (depth != CV_32S) {
  780. NSException* exception = [NSException
  781. exceptionWithName:@"UnsupportedOperationException"
  782. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depth for this call is CV_32S.", [CvType typeToString:depth]]
  783. userInfo:nil];
  784. @throw exception;
  785. }
  786. return putData(indices, _nativePtr, count, buffer);
  787. }
  788. - (int)put:(NSArray<NSNumber*>*)indices count:(int)count shortBuffer:(const short*)buffer {
  789. int depth = _nativePtr->depth();
  790. if (depth != CV_16S && depth != CV_16U) {
  791. NSException* exception = [NSException
  792. exceptionWithName:@"UnsupportedOperationException"
  793. reason:[NSString stringWithFormat:@"Invalid depth (%@). Valid depths for this call are CV_16S and CV_16U.", [CvType typeToString:depth]]
  794. userInfo:nil];
  795. @throw exception;
  796. }
  797. return putData(indices, _nativePtr, count, buffer);
  798. }
  799. - (int)height {
  800. return [self rows];
  801. }
  802. - (int)width {
  803. return [self cols];
  804. }
  805. @end