c++模型推理时 HWC转CHW

问题1:转化engine文件时,不知道是由什么决定输入方式要按照hwc还是chw的。

c++ 图片HWC格式转CHW格式

vector<uint8_t> fileData(channels * height * width);
float* hostInputBuffer = static_cast<float*>(channels * height * width);

 // Convert HWC to CHW and Normalize
 for (int c = 0; c < channels; ++c)
 {
     for (int h = 0; h < height; ++h)
     {
         for (int w = 0; w < width; ++w)
         {
             int dstIdx = c * height * width + h * width + w;
             int srcIdx = h * width * channels + w * channels + c;
             hostInputBuffer[dstIdx] =  static_cast<const float>(fileData[srcIdx]);
         }
     }
 }

参考:https://blog.csdn.net/wuqingshan2010/article/details/106198445/

using namespace cv;
Mat MatBGRImage = imread("wokspace/my_src.jpg");
auto t0 = iLogger::timestamp_now_float();

Mat RGBImg, ResizeImg;
cvtColor(MatBGRImage, RGBImg, COLOR_BGR2RGB);
cv::resize(RGBImg, ResizeImg, Size(224, 224));
// mean_rgb = [0.485, 0.456, 0.406]
// std_rgb  = [0.229, 0.224, 0.225]

int channels = ResizeImg.channels(), height = ResizeImg.rows, width = ResizeImg.cols;

float* nchwMat = (float*)malloc(channels * height * width * sizeof(float));
memset(nchwMat, 0, channels * height * width * sizeof(float));

// Convert HWC to CHW and Normalize
float mean_rgb[3] = {0.485, 0.456, 0.406};
float std_rgb[3]  = {0.229, 0.224, 0.225};
uint8_t* ptMat = ResizeImg.ptr<uint8_t>(0);
int area = height * width;
for (int c = 0; c < channels; ++c)
{
    for (int h = 0; h < height; ++h)
    {
        for (int w = 0; w < width; ++w)
        {
            int srcIdx = c * area + h * width + w;
            int divider = srcIdx / 3;  // 0, 1, 2
            for (int i = 0; i < 3; ++i)
            {
                nchwMat[divider + i * area] = static_cast<float>((ptMat[srcIdx] * 1.0f/255.0f - mean_rgb[i]) * 1.0f/std_rgb[i] );
            }
        }
    }
}
// 复制到GPU
size_t Src_size = 3 * 224 * 224 * sizeof(float);

for (int i = 0; i < explicit_batch; ++i)
{
    cudaMemcpy(static_cast<float*>(input_tensor_image->pValue + i * Src_size), 
            nchwMat, Src_size, cudaMemcpyHostToDevice);
}
free(nchwMat);
auto t1 = iLogger::timestamp_now_float();
auto ms0 = t1 - t0;
printf("preprocess time: %.3f ms\n", ms0);

参考:
https://blog.csdn.net/weixin_45137428/article/details/122229184

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值