C++中实现维度变换numpy.transpose()

C++中实现维度变换numpy.transpose()

1. 工程需求

使用TensorRT部署工业模型的时候,常需要将数据转换为深度学习模型需要的维度数据。如果数据维度变换不正确,直接会导致推理结果出错。

2. 参考

C++ – C++实现Python numpy的矩阵维度转置算法,例如(N,H,W,C)转换为(N,C,H,W)

3. 核心原理

例如将矩阵数据进行(N,H,W,C)转换为(N,C,H,W),核心原理是:将原矩阵中的第(N,H,W,C)个值赋值给transpose后的矩阵的(N,C,H,W)位置的值

4. 举例

依旧以矩阵数据从(N,H,W,C)转换为(N,C,H,W)为例,具体代码如下,4层循环即可。注意数组展平后,索引值计算。

#include <iostream>
#include <string>

int main()
{
    int N = 1;
    int H = 2;
    int W = 3;
    int C = 4;

    float temp_int[24] = { 0, 1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 };
    float temp_int_transpose[24] = { 0 };

    // [N,H,W,C] -> [N,C,H,W]
    for (int n = 0; n < N; ++n)
    {
        for (int c = 0; c < C; ++c)
        {
            for (int h = 0; h < H; ++h)
            {
                for (int w = 0; w < W; ++w)
                {
                    int old_index = n * H * W * C + h * W * C + w * C + c; // 原始索引值
                    int new_index = n * C * H * W + c * H * W + h * W + w; // 新索引值

                    temp_int_transpose[new_index] = temp_int[old_index];
                    std::cout << temp_int_transpose[new_index] << ",";
                }
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_36354875/article/details/125841632
今日推荐