我使用了如下代码导出了一个onnx模型:import torch import torchvision.models… · The Chat Archive
Explore / Programming gpt-4o-mini-2024-07-18 · OpenAI WildChat-4.8M (AI2)我使用了如下代码导出了一个onnx模型:import torch import torchvision.models as models numclasses = 5… Save Share Download ▾ Report我使用了如下代码导出了一个onnx模型:import torch
import torchvision.models as models
num_classes = 5
model = models.resnet18(pretrained=True)
model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
model.load_state_dict(torch.load('../savemodel/resNet18.pth',
map_location=torch.device('cpu')), strict=False)
model.eval()
dummy_input = torch.randn(1, 3, 224, 224) # 根据实际输入形状调整
onnx_file_path = "../savemodel/resnet_model.onnx"
torch.onnx.export(
model, # 要导出的模型
dummy_input, # 一个示例输入
onnx_file_path, # 导出的ONNX文件路径
export_params=True, # 是否导出模型参数
opset_version=11, # ONNX版本,选择合适的版本
do_constant_folding=True, # 是否启用常量折叠优化
input_names=['input'], # 输入名称
output_names=['output'], # 输出名称
dynamic_axes={ # 支持动态批处理大小
'input': {0: 'batch_size'},
'output': {0: 'batch_size'}}
) 我该如何使用openvino2022.1 c++推理他呢?
Assistant2024-09-07 05:34 UTC Copy response
Assistant2024-09-07 05:36 UTC Copy response
在使用 torch.onnx.export 导出 ONNX 模型时,dynamic_axes 参数用于指定输入和输出的动态轴,这样可以支持变量批处理大小(batch size)或其他维度的变化。这在实际推理时非常有用,因为您可能希望模型能够处理不同大小的输入。
以下是如何使用 dynamic_axes 的详细解释及示例:
1. dynamic_axes 的定义
dynamic_axes 是一个字典,表明哪些维度应该是动态的,具体格式如下:
dynamic_axes={
'input_name': {
axis_index: 'dynamic_name'
},
'output_name': {
axis_index: 'dynamic_name'
}
}
input_name 和 output_name 是您在 input_names 和 output_names 中定义的名称。
axis_index 是要动态化的维度索引,从 0 开始,例如:
0:表示批处理维度
1:表示特征维度或高度
2:表示宽度
dynamic_name 是一个字符串,用于在导出 ONNX 模型时标识该动态维度。
可以举个推理图片的代码示例吗?比如我在一个文件夹下有两张图像,如何输入进模型进行推理呢?
Assistant2024-09-07 05:37 UTC Copy response
Assistant2024-09-07 05:39 UTC Copy response
error: (-215:Assertion failed) type2 == CV_64F && (sz2.height == 1 || sz2.height == 4) in function 'cv::arithm_op'
Assistant2024-09-07 05:47 UTC Copy response
错误消息 error: (-215:Assertion failed) type2 == CV_64F && (sz2.height == 1 || sz2.height == 4) in function 'cv::arithm_op' 通常表示在进行 OpenCV 图像操作时,输入图像的类型或大小不符合预期。这通常发生在试图进行数学运算或图像混合时,涉及不同数据类型或不匹配的矩阵维度。
源码如下 cv::Mat resized_img, cropped_img, float_img, normalized_img;
cv::resize(img, resized_img, cv::Size(256, 256));
int crop_size = 224;
int x_start = (resized_img.cols - crop_size) / 2;
int y_start = (resized_img.rows - crop_size) / 2;
cropped_img = resized_img(cv::Rect(x_start, y_start, crop_size, crop_size));
cropped_img.convertTo(float_img, CV_32F);
cv::Mat mean = (cv::Mat_(1, 3) << 0.485, 0.456, 0.406);
cv::Mat std = (cv::Mat_(1, 3) << 0.229, 0.224, 0.225);
normalized_img = (cropped_img / 255.0 - mean) / std;
cv::dnn::blobFromImage(normalized_img, normalized_img);
return normalized_img;
Assistant2024-09-07 05:48 UTC Copy response
从您提供的代码来看,您正在使用 OpenCV 来预处理图像,以便将其输入到深度学习模型中。然而,您在进行归一化处理的方式会导致错误,因为图像与均值和标准差操作的维度不匹配,而 cv::Mat 的操作并不总是支持自动广播。
让我们对代码进行一些修改,以确保图像在进行归一化时能够正确处理。
修改后的预处理代码
以下是改进版的代码。在这个版本中,我们将确保均值和标准差都具有正确的尺寸,并且按照 (C, H, W) 的格式来处理图像数据:
cv::Mat preprocessImage(const cv::Mat& img) {
// 调整图像大小
cv::Mat resized_img, cropped_img, float_img, normalized_img;
cv::resize(img, resized_img, cv::Size(256, 256));
// 中心裁剪
int crop_size = 224;
int x_start = (resized_img.cols - crop_size) / 2;
int y_start = (resized_img.rows - crop_size) / 2;
cropped_img = resized_img(cv::Rect(x_start, y_start, crop_size, crop_size));
// 转换为 float 类型
cropped_img.convertTo(float_img, CV_32F, 1.0 / 255.0); // 同时进行归一化至 [0, 1]
// 定义均值和标准差
cv::Mat mean = (cv::Mat_<float>(1, 3) << 0.485, 0.456, 0.406);
cv::Mat std = (cv::Mat_<float>(1, 3) << 0.229, 0.224, 0.225);
// 确保均值和标准差的维度能广播,添加一个尺寸和通道相同的 Matrix
cv::Mat mean_mat;
cv::Mat std_mat;
cv::Mat mean_expanded;
cv::Mat std_expanded;
cv::repeat(mean, crop_size, crop_size, mean_expanded);
cv::repeat(std, crop_size, crop_size, std_expanded);
// 在归一化前确保图像与均值和标准差具有相同的形状
normalized_img = (float_img - mean_expanded) / std_expanded;
// 转换为 blob 格式(NCHW)
cv::Mat blob;
cv::dnn::blobFromImage(normalized_img, blob);
return blob; // 返回 blob 格式的图像
}
还是报错The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'cv::arithm_op
Assistant2024-09-07 05:50 UTC Copy response
这个错误消息表明您在尝试对不同尺寸的矩阵进行操作,而这些操作必须遵循 OpenCV 的数组运算要求,如相同形状或相同通道数。我们需要仔细处理均值和标准差的广播,以确保它们在进行运算时与待处理图像具有相同的维度。
以下是一个确保正确处理均值和标准差归一化的改进版本:
处理图像的正确方式
确保您遵循 (C, H, W) 的格式处理,并且均值和标准差必须能够正确进行广播。
修改后的预处理代码
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
cv::Mat preprocessImage(const cv::Mat& img) {
// Resize to 256x256
cv::Mat resized_img;
cv::resize(img, resized_img, cv::Size(256, 256));
// Center crop to 224x224
int crop_size = 224;
int x_start = (resized_img.cols - crop_size) / 2;
int y_start = (resized_img.rows - crop_size) / 2;
cv::Mat cropped_img = resized_img(cv::Rect(x_start, y_start, crop_size, crop_size));
// Convert to float
cv::Mat float_img;
cropped_img.convertTo(float_img, CV_32F, 1.0 / 255.0); // Normalize to [0, 1]
// Define mean and standard deviation in (C,) format
cv::Mat mean = (cv::Mat_<float>(1, 3) << 0.485, 0.456, 0.406);
cv::Mat std = (cv::Mat_<float>(1, 3) << 0.229, 0.224, 0.225);
// Create a new Mat to hold the normalized image
cv::Mat normalized_img;
// Split the float image into channels
std::vector<cv::Mat> channels(3);
cv::split(float_img, channels);
// Normalize each channel
for (int i = 0; i < 3; ++i) {
channels[i] = (channels[i] - mean.at<float>(0, i)) / std.at<float>(0, i);
}
// Merge channels back
cv::merge(channels, normalized_img);
// Convert to blob format (NCHW)
cv::Mat blob;
cv::dnn::blobFromImage(normalized_img, blob);
return blob; // Return blob format image
}
Assistant2024-09-07 05:51 UTC Copy response
您的代码看起来是一个完整的 OpenVINO 和 OpenCV 应用程序,它实现了加载图像、预处理、调用推理以及输出结果的功能。然而,我注意到您在预处理阶段的某些方面可能需要调整,尤其是关于图像的归一化和转换为 blob 格式的步骤。
修改建议
以下是您可能需要修改的要点:
图像归一化 :
当进行归一化时,确保均值和标准差在广播方面处理正确。考虑到均值和标准差的元素是作用于每个通道,您不需要扩展它们以匹配图像的高度和宽度。直接从 float_img 中每个通道中减去相应的均值,并除以标准差即可。
:
cv::dnn::blobFromImage(normalized_img, blob);这段代码不对啊
Assistant2024-09-07 05:55 UTC Copy response
对不起,您是对的;在使用 cv::dnn::blobFromImage 的上下文中,它期望的输入是原始图像或进行了适当比例和通道顺序的图像。因此,在生成 blob 时,不需要再进行归一化。
修正的思路 :
我们应该在预处理图像时进行 normalization,但这里却不应该再次转换为 blob。应直接将 float_img 传递给 blobFromImage。
Assistant2024-09-07 05:58 UTC Copy response
Copy first prompt Copy first response
Details
Model gpt-4o-mini-2024-07-18
Provider OpenAI
Model provenance As recorded by source dataset
Turns 10 (20 messages)
Language zh
Conversation date Sep 7, 2024
Added to archive Nov 16, 2026
ID 01m7h41tq1tsqnktpmfkvdsp74Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: a3d87347d1e8660036eac78a84467afa
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
要使用 OpenVINO 2022.1 在 C++ 中推理导出的 ONNX 模型,您需要按照以下步骤进行操作:
1. 安装 OpenVINO
确保您已经正确安装了 OpenVINO 2022.1,并配置了环境变量。您可以通过执行 OpenVINO 安装目录下的 setupvars.sh(对于 Linux)或 setupvars.bat (对于 Windows)来配置环境。
2. 转换 ONNX 模型
使用 OpenVINO 的模型优化器 (Model Optimizer) 将 ONNX 模型转换为 OpenVINO 的 IR(Intermediate Representation)格式。这可以使用如下命令完成:
mo --input_model ../savemodel/resnet_model.onnx --framework onnx
这将生成 resnet_model.xml 和 resnet_model.bin 文件。
3. 编写 C++ 推理代码
以下是一个简单的 C++ 示例,演示如何加载 IR 模型并进行推理。请根据您的 OpenVINO 安装路径和项目结构进行调整。
#include <inference_engine.hpp>
#include <iostream>
#include <vector>
using namespace InferenceEngine;
int main() {
// Create an instance of Inference Engine
Core ie;
// Load the model.
std::string model_xml = "../savemodel/resnet_model.xml";
std::string model_bin = "../savemodel/resnet_model.bin";
// Read the model.
CNNNetwork network = ie.ReadNetwork(model_xml, model_bin);
// Prepare input and output blobs
InputsDataMap inputInfo(network.getInputsInfo());
OutputsDataMap outputInfo(network.getOutputsInfo());
// Get the input blob
auto inputBlob = inputInfo.begin()->second;
inputBlob->setPrecision(Precision::FP32); // Assuming your input is float
// Create an executable network
ExecutableNetwork executableNetwork = ie.LoadNetwork(network, "CPU");
// Create an infer request
InferRequest inferRequest = executableNetwork.CreateInferRequest();
// Prepare the input data (dummy input for example)
const int batchSize = 1;
const int channels = 3;
const int height = 224;
const int width = 224;
// Create dummy input data (initialize with your real data)
std::vector<float> inputData(batchSize * channels * height * width, 0); // Replace with actual data
inferRequest.SetBlob(inputInfo.begin()->first, make_shared_blob<float>({Precision::FP32, {1, 3, 224, 224}, Layout::NCHW, inputData.data()}));
// Run inference
inferRequest.Infer();
// Get output
auto outputBlob = inferRequest.GetBlob(outputInfo.begin()->first);
float* outputData = outputBlob->buffer().as<float*>();
// Process the output (example: print the first class score)
for (size_t i = 0; i < outputBlob->size(); ++i) {
std::cout << "Output class " << i << ": " << outputData[i] << std::endl;
}
return 0;
}
4. 编译与运行
确保链接 OpenVINO 的库,在 CMakeLists.txt 中包含相应的 OpenVINO 头文件和库。例如:
find_package(InferenceEngine REQUIRED)
add_executable(your_executable your_code.cpp)
target_link_libraries(your_executable PRIVATE InferenceEngine::InferenceEngine)
5. 运行程序
编译后,运行程序会将数据传入模型并输出预测结果。
注意事项
确保输入数据的预处理与训练时相同,例如归一化等。
您可能需要根据您的模型和具体需求调整输出处理部分。例如,您可能需要确定最高概率的类别。
2. 示例代码 以下是您提供的代码示例,显示了如何定义 dynamic_axes:
torch.onnx.export(
model, # 要导出的模型
dummy_input, # 一个示例输入
onnx_file_path, # 导出的ONNX文件路径
export_params=True, # 是否导出模型参数
opset_version=11, # ONNX版本,选择合适的版本
do_constant_folding=True, # 是否启用常量折叠优化
input_names=['input'], # 输入名称
output_names=['output'], # 输出名称
dynamic_axes={ # 支持动态批处理大小
'input': {0: 'batch_size'}, # 将批处理维度动态化
'output': {0: 'batch_size'} # 将输出的批处理维度动态化
}
)
3. 应用动态轴的优点
灵活性 :模型可以处理不同批量大小的输入,这在实际应用中是非常重要的。
通用性 :降低了后端推理代码的复杂性,因为可以直接给模型传入不同大小的输入。
4. 运行时使用动态轴 在 ONNX 模型的推理过程中,您也需要提供符合动态轴的输入。例如,使用 OpenVINO 时,您依然需要按照动态轴所允许的输入大小进行推理,确保输入的尺寸匹配。
例如,您可以在 OpenVINO 中以动态方式处理不同大小的输入,只需确保在推理时提供正确的输入格式。
总结 使用 dynamic_axes 使得导出的 ONNX 模型更具灵活性,适应不同的输入形状,特别是在批处理大小变化的场景中。确保在推理代码中正确处理动态维度,以最大限度地利用模型的灵活性。
当然可以!下面是一个完整的 C++ 示例代码,演示如何使用 OpenVINO 对一个文件夹中的两张图像进行推理。这个例子假设你已经将模型转换为 OpenVINO 的 IR 格式(.xml 和 .bin 文件),并且你使用 OpenVINO 的 Inference Engine API。
1. 包含必要的头文件
首先,确保已经包含了正确的 OpenVINO 头文件和其他可能需要的库。
#include <inference_engine.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <filesystem>
#include <vector>
using namespace InferenceEngine;
namespace fs = std::filesystem;
2. 图像预处理函数
编写一个函数来处理图像,包括读取图像以及调整大小和归一化等。
Blob::Ptr preprocessImage(const std::string& imagePath, const Size& inputSize) {
// 使用 OpenCV 读取图像
cv::Mat image = cv::imread(imagePath);
if (image.empty()) {
throw std::runtime_error("Could not open or find the image: " + imagePath);
}
// 调整图像大小
cv::resize(image, image, cv::Size(inputSize.width, inputSize.height));
// 转换图像格式为 float,并执行归一化
image.convertTo(image, CV_32F, 1.0 / 255); // 归一化到 [0, 1]
// 转换图像为 (NCHW) 格式
std::vector<float> imageData(image.total() * image.channels());
std::memcpy(imageData.data(), image.data, image.total() * image.elemSize());
Blob::Ptr blob = make_shared_blob<float>({Precision::FP32, {1, 3, inputSize.height, inputSize.width}, Layout::NCHW});
blob->allocate();
std::memcpy(blob->buffer(), imageData.data(), imageData.size() * sizeof(float));
return blob;
}
3. 主推理代码
在 main 函数中,添加以下代码,这是一种工作流程示例,包括加载模型、处理图像、执行推理和显示推理结果:
int main() {
// 创建 Inference Engine
Core ie;
// 加载 IR 模型
std::string model_xml = "../savemodel/resnet_model.xml";
std::string model_bin = "../savemodel/resnet_model.bin";
// 读取模型
CNNNetwork network = ie.ReadNetwork(model_xml, model_bin);
// 准备输入和输出 blob
InputsDataMap inputInfo(network.getInputsInfo());
OutputsDataMap outputInfo(network.getOutputsInfo());
// 获取输入 blob
auto inputBlob = inputInfo.begin()->second;
inputBlob->setPrecision(Precision::FP32); // 假设输入是 float 类型
// 创建可执行的网络
ExecutableNetwork executableNetwork = ie.LoadNetwork(network, "CPU");
// 创建推理请求
InferRequest inferRequest = executableNetwork.CreateInferRequest();
// 设置图像文件夹路径
std::string imageDir = "./images"; // 假设图像在这个目录下
int numImages = 0;
// 遍历文件夹中的图像文件
for (const auto& entry : fs::directory_iterator(imageDir)) {
if (entry.path().extension() == ".jpg" || entry.path().extension() == ".png") {
numImages++;
// 预处理图像
auto blob = preprocessImage(entry.path().string(), Size(224, 224)); // 假设输入尺寸为 224x224
// 设置推理请求的输入 blob
inferRequest.SetBlob(inputInfo.begin()->first, blob);
// 执行推理
inferRequest.Infer();
// 获取输出
auto outputBlob = inferRequest.GetBlob(outputInfo.begin()->first);
float* outputData = outputBlob->buffer().as<float*>();
// 处理输出(例如:打印每个类的分数)
for (size_t i = 0; i < outputBlob->size(); ++i) {
std::cout << "Image: " << entry.path().filename() << ", Output class " << i << ": " << outputData[i] << std::endl;
}
}
}
if (numImages == 0) {
std::cout << "No images found in the specified directory." << std::endl;
}
return 0;
}
4. 编译与运行
确保链接 OpenVINO 和 OpenCV 的库,在 CMakeLists.txt 中包含相应的设置:
find_package(InferenceEngine REQUIRED)
find_package(OpenCV REQUIRED)
add_executable(inference_app your_code.cpp)
target_link_libraries(inference_app PRIVATE InferenceEngine::InferenceEngine ${OpenCV_LIBS})
总结
这个示例展示了如何加载图片、预处理图像、设置输入 blob、执行推理并打印输出结果。在实际使用时,您可能需要根据模型的输出处理信心(如类别分数、得分或者进一步的后处理)。确保您安装了 OpenCV,并根据所用的模型输入尺寸调整代码中的相关参数。
可以的!如果您希望一次性将多张图片作为输入进行推理,您需要确保模型支持这一点(通常情况下是批处理模式),并且在设置输入 blob 时要正确处理这些图片。
以下是一个示例,演示如何一次处理多张图片(例如,将两张图片作为输入)并进行推理。假设我们仍然处理的是 ResNet 模型,并且我们希望在推理时批量输入图像。
1. 修改 preprocessImage 函数
可以重命名并修改 preprocessImage 函数,返回多个图像的 blob。
Blob::Ptr preprocessImages(const std::vector<std::string>& imagePaths, const Size& inputSize) {
int batchSize = static_cast<int>(imagePaths.size());
std::vector<float> batchData;
for (const auto& imagePath : imagePaths) {
// 使用 OpenCV 读取图像
cv::Mat image = cv::imread(imagePath);
if (image.empty()) {
throw std::runtime_error("Could not open or find the image: " + imagePath);
}
// 调整图像大小
cv::resize(image, image, cv::Size(inputSize.width, inputSize.height));
// 归一化
image.convertTo(image, CV_32F, 1.0 / 255);
// 转换为 (C, H, W) 格式
std::vector<float> imageData(image.total() * image.channels());
std::memcpy(imageData.data(), image.data, image.total() * image.elemSize());
batchData.insert(batchData.end(), imageData.begin(), imageData.end());
}
// 创建 (N, C, H, W) blob
Blob::Ptr blob = make_shared_blob<float>({Precision::FP32, {batchSize, 3, inputSize.height, inputSize.width}, Layout::NCHW});
blob->allocate();
std::memcpy(blob->buffer(), batchData.data(), batchData.size() * sizeof(float));
return blob;
}
2. 主推理代码的修改
在 main 函数中,修改为处理两张图片并将它们一起输入:
int main() {
// 创建 Inference Engine
Core ie;
// 加载 IR 模型
std::string model_xml = "../savemodel/resnet_model.xml";
std::string model_bin = "../savemodel/resnet_model.bin";
// 读取模型
CNNNetwork network = ie.ReadNetwork(model_xml, model_bin);
// 准备输入和输出 blob
InputsDataMap inputInfo(network.getInputsInfo());
OutputsDataMap outputInfo(network.getOutputsInfo());
// 确保模型支持批处理
auto inputBlob = inputInfo.begin()->second;
inputBlob->setPrecision(Precision::FP32);
// 创建可执行的网络
ExecutableNetwork executableNetwork = ie.LoadNetwork(network, "CPU");
// 创建推理请求
InferRequest inferRequest = executableNetwork.CreateInferRequest();
// 设置图像路径
std::vector<std::string> imagePaths = {
"./images/image1.jpg", // 替换为您的第一张图像路径
"./images/image2.jpg" // 替换为您的第二张图像路径
};
// 预处理图像
auto blob = preprocessImages(imagePaths, Size(224, 224)); // 输入尺寸可以根据需要调整
// 设置推理请求的输入 blob
inferRequest.SetBlob(inputInfo.begin()->first, blob);
// 执行推理
inferRequest.Infer();
// 获取输出
auto outputBlob = inferRequest.GetBlob(outputInfo.begin()->first);
float* outputData = outputBlob->buffer().as<float*>();
// 遍历输出并处理
for (size_t i = 0; i < imagePaths.size(); ++i) {
std::cout << "Results for image: " << imagePaths[i] << std::endl;
for (size_t j = 0; j < outputBlob->size() / imagePaths.size(); ++j) {
std::cout << "Output class " << j << ": " << outputData[i * (outputBlob->size() / imagePaths.size()) + j] << std::endl;
}
}
return 0;
}
3. 总结
在这个示例中,我们创建了一个处理多张图片的函数,在 main 函数中构建图片路径的向量,并一起输入到模型中进行推理。推理的输出将被打印,其中每张输入图像的输出结果都将被显示。
确保您的模型支持批量输入(通常大多数现代模型都支持)。根据您的模型大小和输入图像的数量,您也可以扩展这个示例来处理更多的图像。
以下是一些检查和故障排除的步骤,确保图像处理流程中的数据类型和维度正确:
1. 检查图像读取 确保您的图像确实已成功读取并且不是空的。如果 cv::imread 无法读取图像,它将返回一个空的 cv::Mat。可以在读取图像后添加检查:
cv::Mat image = cv::imread(imagePath);
if (image.empty()) {
throw std::runtime_error("Could not open or find the image: " + imagePath);
}
2. 检查数据类型 当您使用 convertTo 将图像转换为浮点型时,请确保它实际上被转换为 CV_32F(单通道浮点型)。避免在处理过程中使用不匹配的类型。
// 确保使用 CV_32F 类型
image.convertTo(image, CV_32F, 1.0 / 255);
3. 确保图像尺寸一致 在批量处理图像之前,确保所有图像都具有相同的尺寸。在调整大小时,确定您在 cv::resize 中指定的大小与模型输入的维度相符。
// 调整图像大小,确保使用相同输入尺寸
cv::resize(image, image, cv::Size(inputSize.width, inputSize.height)); // inputSize 应与模型输入一致
4. 纠正分配给 Blob 的数据 在为 Blob 分配数据时,确保您正确处理图像的通道顺序(NCHW 格式),并且没有错误的数据拷贝。
完整代码示例 以下是一个简化且完整的代码段,确保了数据类型正确和批量处理一致性,您可以参考或直接替换旧代码:
Blob::Ptr preprocessImages(const std::vector<std::string>& imagePaths, const Size& inputSize) {
int batchSize = static_cast<int>(imagePaths.size());
std::vector<float> batchData(batchSize * 3 * inputSize.height * inputSize.width);
for (size_t i = 0; i < batchSize; ++i) {
cv::Mat image = cv::imread(imagePaths[i]);
if (image.empty()) {
throw std::runtime_error("Could not open or find the image: " + imagePaths[i]);
}
cv::resize(image, image, cv::Size(inputSize.width, inputSize.height));
image.convertTo(image, CV_32F, 1.0 / 255); // Normalize to [0, 1]
// Fill the batch data in the order of (C, H, W)
for (int c = 0; c < 3; ++c) { // Assuming 3 channels
for (int h = 0; h < inputSize.height; ++h) {
for (int w = 0; w < inputSize.width; ++w) {
batchData[i * 3 * inputSize.height * inputSize.width + c * inputSize.height * inputSize.width + h * inputSize.width + w] =
image.at<cv::Vec3f>(h, w)[c];
}
}
}
}
// Create a Blob for the batch
Blob::Ptr blob = make_shared_blob<float>({Precision::FP32, {batchSize, 3, inputSize.height, inputSize.width}, Layout::NCHW});
blob->allocate();
std::memcpy(blob->buffer(), batchData.data(), batchData.size() * sizeof(float));
return blob;
}
在这个示例中,我们确保了输入图像的读取、大小调整、数据类型和 Blob 的数据填充都是正确的。如果问题继续存在,请仔细检查输入数据的形状、通道顺序和数据类型。
关键修改点
图片的归一化 :
使用 float_img 进行归一化操作时,我们先将其转换为 [0, 1] 范围,然后再减去均值并除以标准差。(直接在 convertTo 中做归一化)
维度匹配 :
mean 和 std 在进行操作之前,我们使用 cv::repeat 函数将它们展开成与 cropped_img 相同的尺寸,以便可以进行逐元素操作。
使用 cv::dnn::blobFromImage :
最后,我们使用 cv::dnn::blobFromImage 来转化为网络可处理的 blob 格式。
注意事项
必须确保输入图像的形状与模型的输入要求相符。
让均值和标准差在操作前的维度与实际图像保持一致,这样可以避免发生维度不匹配的错误。
此外,此段代码假设输入的 img 是 BGR 格式,如果你的模型需要 RGB 格式,可以在处理之前使用 cv::cvtColor(img, img, cv::COLOR_BGR2RGB) 来转换颜色空间。
关键点修改说明
图像通道分离 :
通过使用 cv::split 将经过归一化的 float_img 拆分为单独的通道。
循环归一化 :
对每个通道进行归一化操作,确保每个通道使用独立的均值和标准差。
通道合并 :
使用 cv::merge 函数将归一化后的通道合并回单个图像。
结论 通过这种方式,您处理的每个图像通道都将正确应用均值和标准差并避免因维度不匹配而导致的错误。这将确保在进行数学运算时,所有操作均符合 OpenCV 的要求。您可以用此修改过的代码替换您的原始代码,并进行图像预处理。
#include <openvino/openvino.hpp>
#include <opencv2/opencv.hpp>
#include
#include
#include
using namespace std;
cv::Mat preprocess(const cv::Mat& img) {
try {
// 调整图像大小
cv::Mat resized_img, cropped_img, float_img, normalized_img;
cv::resize(img, resized_img, cv::Size(224, 224));
// 中心裁剪
int crop_size = 224;
int x_start = (resized_img.cols - crop_size) / 2;
int y_start = (resized_img.rows - crop_size) / 2;
cropped_img = resized_img(cv::Rect(x_start, y_start, crop_size, crop_size));
// 转换为 float 类型
cropped_img.convertTo(float_img, CV_32F, 1.0 / 255.0); // 同时进行归一化至 [0, 1]
// 定义均值和标准差
cv::Mat mean = (cv::Mat_(1, 3) << 0.485, 0.456, 0.406);
cv::Mat std = (cv::Mat_(1, 3) << 0.229, 0.224, 0.225);
// 确保均值和标准差的维度能广播,添加一个尺寸和通道相同的 Matrix
cv::Mat mean_mat;
cv::Mat std_mat;
cv::Mat mean_expanded;
cv::Mat std_expanded;
cv::repeat(mean, crop_size, crop_size, mean_expanded);
cv::repeat(std, crop_size, crop_size, std_expanded);
// 在归一化前确保图像与均值和标准差具有相同的形状
normalized_img = (float_img - mean_expanded) / std_expanded;
// 转换为 blob 格式(NCHW)
cv::Mat blob;
cv::dnn::blobFromImage(normalized_img, blob);
return blob; // 返回 blob 格式的图像
}
catch (cv::Exception EX) {
cout << EX.what() << endl;
}
}
int main() {
// 1. 初始化 OpenVINO 核心对象
ov::Core core;
// 2. 读取模型 (.xml and .bin)
std::shared_ptrov::Model model = core.read_model("resnet_model.onnx");
// 3. 编译模型 (选择 CPU 作为推理设备)
ov::CompiledModel compiled_model = core.compile_model(model, "CPU");
// 4. 创建推理请求
ov::InferRequest infer_request = compiled_model.create_infer_request();
// 5. 加载图像
std::string img_path = "G:\python\Test5_resnet\data\data_set\flower_data\val\daisy\169371301_d9b91a2a42.jpg";
cv::Mat img = cv::imread(img_path);
if (img.empty()) {
std::cerr << "Error: Unable to load image!" << std::endl;
return -1;
}
// 6. 预处理图像
cv::Mat processed_img = preprocess(img);
// 7. 设置输入张量数据
ov::Tensor input_tensor = infer_request.get_input_tensor();
std::memcpy(input_tensor.data(), processed_img.data, processed_img.total() * sizeof(float));
// 8. 执行推理
infer_request.infer();
// 9. 获取推理结果
ov::Tensor output_tensor = infer_request.get_output_tensor();
const float* output_data = output_tensor.data<const float>();
// 10. 读取分类标签
std::ifstream input("class_indices.json");
std::map<int, std::string> class_indices;
if (input.is_open()) {
std::string line;
while (std::getline(input, line)) {
std::size_t pos = line.find(':');
int index = std::stoi(line.substr(1, pos - 2));
std::string class_name = line.substr(pos + 3, line.length() - pos - 5);
class_indices[index] = class_name;
}
input.close();
}
// 11. 处理结果
int max_class_index = std::max_element(output_data, output_data + 5) - output_data;
float max_probability = output_data[max_class_index];
std::cout << "Predicted class: " << class_indices[max_class_index]
<< " with probability " << max_probability << std::endl;
for (int i = 0; i < 5; i++) {
std::cout << "Class: " << class_indices[i] << " Probability: " << output_data[i] << std::endl;
}
return 0;
}
我所有的源码
传递至预处理函数的图像格式
cv::dnn::blobFromImage 已经会处理图像的转换,因此您可能希望直接将已归一化的图像转化为 blob。
修改后的预处理函数 以下是修改后的 preprocess 函数,确保图像被适当地归一化和转换为 blob 格式:
cv::Mat preprocess(const cv::Mat& img) {
// 调整图像大小
cv::Mat resized_img, cropped_img, float_img;
cv::resize(img, resized_img, cv::Size(256, 256));
// 中心裁剪
int crop_size = 224;
int x_start = (resized_img.cols - crop_size) / 2;
int y_start = (resized_img.rows - crop_size) / 2;
cropped_img = resized_img(cv::Rect(x_start, y_start, crop_size, crop_size));
// 转换为 float 类型并归一化到 [0, 1]
cropped_img.convertTo(float_img, CV_32F, 1.0 / 255.0);
// 定义均值和标准差
cv::Mat mean = (cv::Mat_<float>(3, 1) << 0.485, 0.456, 0.406);
cv::Mat std = (cv::Mat_<float>(3, 1) << 0.229, 0.224, 0.225);
// 通道分离
std::vector<cv::Mat> channels(3);
cv::split(float_img, channels);
// 逐通道归一化
for (int i = 0; i < 3; ++i) {
channels[i] = (channels[i] - mean.at<float>(i)) / std.at<float>(i);
}
// 合并通道
cv::Mat normalized_img;
cv::merge(channels, normalized_img);
// 转换为 blob 格式(NCHW)
cv::Mat blob;
cv::dnn::blobFromImage(normalized_img, blob);
return blob; // 返回 blob 格式的图像
}
主函数注意事项 在主函数中,您需要确保从 processed_img 复制数据时,符合 OpenVINO 的要求。
// 设置输入张量数据
ov::Tensor input_tensor = infer_request.get_input_tensor();
std::memcpy(input_tensor.data<float>(), processed_img.data, processed_img.size[1] * processed_img.size[2] * 3 * sizeof(float));
完整代码回顾 非常感谢您提供完整的代码!确保根据这些更改进行测试。以下是完整的程序流程:
加载模型。
读入并处理图像(调整大小、裁剪和归一化)。
将处理后的图像设置为输入。
执行推理并读取输出。
处理输出并打印分类结果。
其他建议
确保 class_indices.json 文件存在且格式正确,以便能够正确读取类标签。
充分处理异常情况,例如读取失败、索引超出范围等。
通过这些更改,您的程序应该能够正确运行。如果您有其他问题或需要进一步的帮助,请随时询问!
修正代码
在调用 cv::dnn::blobFromImage 前的归一化中,直接归一化原始图像(float_img)。
我们在 blobFromImage 前不应该归一化(因为它会处理的输入是非归一化的图像)。
归一化应该在填充输入 blob 之前完成。
修正后的 preprocess 函数 这里是完整的 preprocess 函数,执行图像大小调整、中心裁剪和单通道归一化:
cv::Mat preprocess(const cv::Mat& img) {
// Resize to 256 x 256
cv::Mat resized_img;
cv::resize(img, resized_img, cv::Size(256, 256));
// Center crop to 224 x 224
int crop_size = 224;
int x_start = (resized_img.cols - crop_size) / 2;
int y_start = (resized_img.rows - crop_size) / 2;
cv::Mat cropped_img = resized_img(cv::Rect(x_start, y_start, crop_size, crop_size));
// Convert to float and normalize to [0, 1]
cv::Mat float_img;
cropped_img.convertTo(float_img, CV_32F, 1.0 / 255.0);
// Define mean and standard deviation
cv::Mat mean = (cv::Mat_<float>(3, 1) << 0.485, 0.456, 0.406);
cv::Mat std = (cv::Mat_<float>(3, 1) << 0.229, 0.224, 0.225);
// Split the float image into 3 channels
std::vector<cv::Mat> channels(3);
cv::split(float_img, channels);
// Normalize each channel (in-place)
for (int i = 0; i < 3; ++i) {
channels[i] = (channels[i] - mean.at<float>(i)) / std.at<float>(i);
}
// Merge back the channels
cv::Mat normalized_img;
cv::merge(channels, normalized_img);
// Convert to blob format (NCHW)
cv::Mat blob = cv::dnn::blobFromImage(normalized_img); // Use normalized_img directly
return blob; // Return blob format image
}
主函数中的修改 在主函数中,您仍然按照原来的步骤设置输入张量的数据:
// 设置输入张量数据
ov::Tensor input_tensor = infer_request.get_input_tensor();
std::memcpy(input_tensor.data<float>(), processed_img.data, processed_img.size[1] * processed_img.size[2] * 3 * sizeof(float));
确保 processed_img 是您返回的 blob 格式图像。您可以通过以下方式确认 blob 的形状:
std::cout << "Input shape: " << processed_img.size << std::endl;
总结
归一化应在填充输入 blob 之前完成。
不再调用 cv::dnn::blobFromImage 多次,可以直接将已经预处理的图像用于 blob 转换。
测试更新后的代码,并处理分类的输出步骤。
通过这些更改,您的代码应该能够正常运行。如果您有其他问题或错误,请继续询问!
感谢您的耐心和详细信息。如果您仍然遇到错误,让我们仔细分析并确保代码的每一部分都正确。
整体结构
图像处理和预处理 :确保图像调整、中心裁剪、归一化,以及转化为 blob 格式的过程清晰且符合要求。
OpenVINO 推理 :确保将 blob 数据正确地转移到推理请求中。
完整代码示例
以下是一个调整后的完整的 C++ 代码示例,包括图像预处理、推理和结果输出。我们会更仔细地处理预处理部分,确保每一步都符合预期。
#include <openvino/openvino.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
#include <map>
cv::Mat preprocess(const cv::Mat& img) {
// Resize to 256x256
cv::Mat resized_img;
cv::resize(img, resized_img, cv::Size(256, 256));
// Center crop to 224x224
int crop_size = 224;
int x_start = (resized_img.cols - crop_size) / 2;
int y_start = (resized_img.rows - crop_size) / 2;
cv::Mat cropped_img = resized_img(cv::Rect(x_start, y_start, crop_size, crop_size));
// Convert to float and normalize to [0, 1]
cv::Mat float_img;
cropped_img.convertTo(float_img, CV_32F, 1.0 / 255.0);
// Define mean and std for normalization
cv::Mat mean = (cv::Mat_<float>(3, 1) << 0.485, 0.456, 0.406);
cv::Mat std = (cv::Mat_<float>(3, 1) << 0.229, 0.224, 0.225);
// Normalize each channel
std::vector<cv::Mat> channels(3);
cv::split(float_img, channels);
for (int i = 0; i < 3; ++i) {
channels[i] = (channels[i] - mean.at<float>(i)) / std.at<float>(i);
}
cv::Mat normalized_img;
cv::merge(channels, normalized_img);
// Convert to blob format (NCHW)
cv::Mat blob = cv::dnn::blobFromImage(normalized_img);
return blob; // Return blob format image
}
int main() {
// 1. Initialize OpenVINO core object
ov::Core core;
// 2. Read the model (.xml and .bin)
std::shared_ptr<ov::Model> model = core.read_model("resnet_model.onnx");
// 3. Compile the model (choose CPU as inference device)
ov::CompiledModel compiled_model = core.compile_model(model, "CPU");
// 4. Create an inference request
ov::InferRequest infer_request = compiled_model.create_infer_request();
// 5. Load the image
std::string img_path = "your_image_path.jpg"; // Specify your image path
cv::Mat img = cv::imread(img_path);
if (img.empty()) {
std::cerr << "Error: Unable to load image!" << std::endl;
return -1;
}
// 6. Preprocess the image
cv::Mat processed_img = preprocess(img);
// 7. Set input tensor data
ov::Tensor input_tensor = infer_request.get_input_tensor();
std::memcpy(input_tensor.data<float>(), processed_img.data, processed_img.total() * sizeof(float));
// 8. Execute inference
infer_request.infer();
// 9. Get inference result
ov::Tensor output_tensor = infer_request.get_output_tensor();
const float* output_data = output_tensor.data<const float>();
// 10. Read class labels
std::ifstream input("class_indices.json");
std::map<int, std::string> class_indices;
if (input.is_open()) {
std::string line;
while (std::getline(input, line)) {
std::size_t pos = line.find(':');
int index = std::stoi(line.substr(1, pos - 2));
std::string class_name = line.substr(pos + 3, line.length() - pos - 5);
class_indices[index] = class_name;
}
input.close();
}
// 11. Process results
int max_class_index = std::max_element(output_data, output_data + output_tensor.get_element_count()) - output_data;
float max_probability = output_data[max_class_index];
std::cout << "Predicted class: " << class_indices[max_class_index]
<< " with probability " << max_probability << std::endl;
for (int i = 0; i < class_indices.size(); i++) {
std::cout << "Class: " << class_indices[i] << " Probability: " << output_data[i] << std::endl;
}
return 0;
}
注意事项:
图像路径 :确保在调用 cv::imread 时,指定的图片路径 your_image_path.jpg 是正确的,如果图像文件不在当前工作目录下,请使用绝对路径。
类标签文件 :确保 class_indices.json 文件的格式正确且可读。
经过正确处理的 Blob :确保经过预处理的图像在设置输入张量之前计算正确的字节数。
NCHW 布局 :请确保内容与所用的模型兼容,不同的模型可能具有不同的输入布局要求。
调试
如果错误依旧存在,当我们处理 processed_img 的时候,确保它是真实的 blob,您可以检查它的形状和数据类型:
std::cout << "Processed image shape: " << processed_img.size << std::endl;
std::cout << "Input shape: " << infer_request.get_input_tensor().get_shape() << std::endl;
结论
上述代码是经过详细检查和调整的,意图提供您所需的基础功能。如果您在实现过程中遇到 exception 或具体错误消息,请提供相关信息,以帮助我们更好地解决问题。