Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access elements inside MLMultiArray in CoreML

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]];
like image 723
kid.abr Avatar asked Dec 15 '17 08:12

kid.abr


1 Answers

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];
like image 157
Matthijs Hollemans Avatar answered Oct 21 '22 12:10

Matthijs Hollemans