简体   繁体   English

如何在CoreML中访问MLMultiArray内部的元素

[英]How to access elements inside MLMultiArray in CoreML

I have initialized MLMultiArray using initWithDataPointer as shown in the code below: 我已经使用initWithDataPointer初始化了MLMultiArray ,如下面的代码所示:

float count = 512 * 384;
  double *tempBuffer = malloc(count * sizeof(double));
  NSError *error = NULL;
  NSArray *shape = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:512],[NSNumber numberWithInt:384], nil];
  NSArray *stride = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:1],[NSNumber numberWithInt:1], nil];

  MLMultiArray *mlMultiArray = [[MLMultiArray alloc] initWithDataPointer:tempBuffer
                                                                   shape:shape
                                                                dataType:MLMultiArrayDataTypeDouble
                                                                 strides:stride
                                                             deallocator:^(void * _Nonnull bytes) { free(bytes); }
                                                                   error:&error];

Based on the MLMultiArray documentation mentioned in this link , subscript needs to be used for accessing elements. 根据此链接中提到的MLMultiArray文档, subscript需要用于访问元素。

If I access the elements in the way shown, is it correct? 如果我以所示方式访问元素,是否正确?

NSNumber *val = [mlMultiArray objectForKeyedSubscript:[NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:1],[NSNumber numberWithInt:1], nil]];

I suggest you use mlMultiArray.dataPointer , cast it to double * , and then access the contents of the data buffer directly. 我建议您使用mlMultiArray.dataPointer ,将其mlMultiArray.dataPointerdouble * ,然后直接访问数据缓冲区的内容。 You can compute where element i, j, k is using the strides: 您可以使用步幅计算元素i, j, k位置:

double *ptr = (double *) mlMultiArray.dataPointer;
NSInteger offset = i*stride[0].intValue + j*stride[1].intValue + k*stride[2].intValue;
double val = ptr[offset];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM