代码之家  ›  专栏  ›  技术社区  ›  kid.abr

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

  •  5
  • kid.abr  · 技术社区  · 7 年前

    我已初始化 MLMultiArray 使用 initWithDataPointer 如下代码所示:

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

    基于 MLMultiArray 本文件中提及的文件 link , subscript 需要用于访问元素。

    如果我按所示方式访问元素,是否正确?

    NSNumber *val = [mlMultiArray objectForKeyedSubscript:[NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:1],[NSNumber numberWithInt:1], nil]];
    
    1 回复  |  直到 7 年前
        1
  •  8
  •   Matthijs Hollemans    7 年前

    我建议您使用 mlMultiArray.dataPointer ,将其投射到 double * ,然后直接访问数据缓冲区的内容。可以计算where元素 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];