Loading

C++计算tensor指定坐标对应的flat数组内存偏移量

需求

使用华为HiAi框架进行模型推理
成功转换模型并构造输入输出tensor
目前需要对output feature map进行解析需要获取tensor指定坐标的值
类似使用array[0,0,0,0]访问返回flat[0]

实现

输出tensor提供了header地址float*和shape数据类型float32
已根据bhwc格式进行flat操作

// get value from bhwc(1,126,28,23) tensor via its header
// WARNING: No memory range check, use with caution!!!
float get_value(const float* header,const int& height,const int& width,const int& channel)
{
    return *(header + height *28*23 + width * 23 + channel);
}

⚠️注意这里有个地方比较坑:
对于flat数组内存偏移量不需要乘每个元素的字节长度
对指针+/-1会自动倍增指针所指对象的字节长度sizeof(float32) = 4
可以理解为地址操作*(header+1)等效于索引header[1]

posted @ 2021-05-19 19:47  azureology  阅读(70)  评论(0编辑  收藏  举报