How to access elements inside MLMultiArray in CoreML

心已入冬 提交于 2019-12-11 05:33:09

问题


I have initialized MLMultiArray using initWithDataPointer as shown in the code below:

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.

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]];

回答1:


I suggest you use mlMultiArray.dataPointer, cast it to double *, and then access the contents of the data buffer directly. You can compute where element i, j, k is using the strides:

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


来源:https://stackoverflow.com/questions/47828706/how-to-access-elements-inside-mlmultiarray-in-coreml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!