TNN MatConvertParam参数scale和bias设置
生活随笔
收集整理的這篇文章主要介紹了
TNN MatConvertParam参数scale和bias设置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Pytorch的Normalize的計算過程是:TNN MatConvertParam參數設置
使用TNN進行模型推理前,需要進行必要的預處理,如下需要設置TNN_NS::MatConvertParam inputCvtParam的scale和bias兩個參數值
/*** Read image ***/cv::Mat orig_image = cv::imread(IMAGE_NAME);int imageWidth = orig_image.size[1];int imageHeight = orig_image.size[0];printf("image size: width = %d, height = %d\n", imageWidth, imageHeight);/*** Pre process ***//* resize, colorconversion */cv::Mat inputImage;cv::resize(orig_image, inputImage, cv::Size(MODEL_WIDTH, MODEL_HEIGHT));cv::cvtColor(inputImage, inputImage, cv::COLOR_BGR2RGB);/*** normalize ***/auto inputMat = std::make_shared<TNN_NS::Mat>(DEVICE_TYPE, TNN_NS::N8UC3, nchw, (uint8_t*)inputImage.data);CHECK(inputMat != NULL);TNN_NS::MatConvertParam inputCvtParam;inputCvtParam.scale = {1 / 0.5 / 255.f, 1 / 0.5 / 255.f, 1 / 0.5 / 255.f, 1 / 0.5 / 255.;inputCvtParam.bias = {-0.5 / 0.5, -0.5 / 0.5, -0.5 / 0.5, -0.5 / 0.5};status = instance->SetInputMat(inputMat, inputCvtParam);TNN_NS::MatConvertParam inputCvtParam的scale和bias的計算規則是:
y = scale*x+bias如果你的模型是Pytorch訓練的模型,一般會使用:
rgb_mean=(0.5, 0.5, 0.5) rgb_std=(0.5, 0.5, 0.5) transforms.Normalize(rgb_mean, rgb_std)?Pytorch的Normalize的計算過程是減均值除方差,即:
input[channel] = (input[channel] - mean[channel]) / std[channel] 即:y = (x-m)/std (其中輸入x是將0~255歸一化到0~1的圖像數據)將Pytorch的Normalize和TNN的MatConvertParam進行變換,即可對齊了:
y = (x-m)/std? --->? y = scale*x+bias
?
恒等變換如下:
y = (x-m)/std
# 由于Pytorch的Normalize對輸入x是將0~255歸一化到0~1的圖像數據,因此需要逆歸一化為0~255
y = (x-m*255)/(std*255)
#? 拆分每項
y=x/(std*255)-m/std
# 比較y = scale*x+bias得:
scale=1/(std*255)=1/std/255
bias=-m/std
因此Pytorch的
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 對應TNN_NS::MatConvertParam的參數為: TNN_NS::MatConvertParam inputCvtParam;inputCvtParam.scale = {1 / 0.5 / 255.f, 1 / 0.5 / 255.f, 1 / 0.5 / 255.f, 1 / 0.5 / 255.;inputCvtParam.bias = {-0.5 / 0.5, -0.5 / 0.5, -0.5 / 0.5, -0.5 / 0.5};?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的TNN MatConvertParam参数scale和bias设置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决Unable to create g
- 下一篇: TNN API说明文档