win10用c++部署libtorch过程中的一些问题,python与c++对应的图像预处理

1.将bgr转rgb

opencv 默认读进去的是bgr的顺序,需处理成rgb顺序。

Python处理:

img = img[:, :, (2, 1, 0)]

C++处理:

cv::cvtColor(testimg, testimg, CV_BGR2RGB);

2.图像矩阵变换

1)opencv读入图片的矩阵格式是:(height,width,channels),是一个channel last的三维矩阵,即(高度,宽度,通道)。

而在深度学习中,因为要对不同通道应用卷积,所以会采取另一种方式:channel first,即(channels,height,width)。为了应对该要求,可以这么做:

print(img.shape)

img = img.transpose(2,0,1)

print(img.shape)

输出:

(480,640,3)

(3,480,640)

 

2)在深度学习搭建CNN时,往往要做相应的图像数据处理,比如图像要扩展维度,比如扩展成(batch_size,channels,height,width)。对于这种要求,可以这么做:

img = np.expand_dims(img, axis=0)

print(img.shape)

输出:

(1,3,480,640)

 

对应的c++代码为:

auto img_tensor = torch::from_blob(testimg.data, { 1,480,640, 3 }, torch::kFloat32);
img_tensor = img_tensor.permute({ 0,3,1,2 });

3. c++ model forward返回值

返回类型为 torch::jit::IValue

torch::jit::IValue result = module->forward(inputs);

 

如果只有一个返回值,可以直接转tensor:

auto outputs = module->forward(inputs).toTensor();

 

注意,如果有多个返回值,需要先转tuple:

auto outputs = module->forward(inputs).toTuple();

torch::Tensor out1 = outputs->elements()[0].toTensor();

torch::Tensor out2 = outputs→elements()[1].toTensor();

 

4.使用GPU

把model和inputs都放到gpu上:

std::shared_ptr<torch::jit::script::Module> module = torch::jit::load(argv[2]);

//put to cuda

module->to(at::kCUDA);

 

// 注意是把tensor放到gpu,而不是vector<torch::jit::IValue>

std::vector<torch::jit::IValue> inputs;

image_tensor.to(at::kCUDA)

inputs.push_back(image_tensor)

可以指定 GPU id: to(torch::Device(torch::kCUDA, id))

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值