把下面的代码用c++实现 import numpy as np import torch import cv2 result = np.fromfile('permute_1_0.raw', dtype=np.float32) img = result.reshape((2,480,480)) torch_img = torch.from_numpy(img) index = torch.max(torch_img, dim=0)[1].numpy().astype(np.uint8) index[index > 0] = 255 # 白色 cv2.imshow('out', index) cv2.waitKey(0)
时间: 2024-03-17 21:40:40 浏览: 121
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
以下是用C++实现的代码:
```
#include <opencv2/opencv.hpp>
#include <torch/torch.h>
int main() {
// 读取数据
std::ifstream input("permute_1_0.raw", std::ios::binary);
std::vector<float> data(2 * 480 * 480);
input.read(reinterpret_cast<char*>(data.data()), data.size() * sizeof(float));
input.close();
// 转换数据类型
torch::Tensor tensor = torch::from_blob(data.data(), {2, 480, 480}, torch::kFloat32).clone();
// 获取最大值索引
torch::Tensor max = std::get<0>(torch::max(tensor, 0));
torch::Tensor index = max.argmax(0).to(torch::kUInt8);
// 去除背景
index.masked_fill_(index == 0, 255);
// 转换为OpenCV格式
cv::Mat out(index.sizes()[0], index.sizes()[1], CV_8UC1, index.data_ptr());
// 显示图像
cv::imshow("out", out);
cv::waitKey(0);
return 0;
}
```
注意需要安装OpenCV和PyTorch C++ API,并且需要将`permute_1_0.raw`文件放在当前目录下。
阅读全文