一、很多时候模型输入都是NCHW,opecv加载图片的时候需要转换一下,代码如下
cv::Mat frame = cv::imread(filePath);
cv::resize(frame, frame, cv::Size(640, 640));
cv::Mat rgb_image;
cv::cvtColor(frame, rgb_image, cv::COLOR_BGR2RGB);
// 转换为 NCHW 格式
cv::Mat nchw_image;
{
int height = rgb_image.rows;
int width = rgb_image.cols;
int channels = rgb_image.channels();
// 将输入图像转换为 CHW 格式
cv::Mat chw(height * width * channels, 1, CV_8UC1);
int index = 0;
for (int c = 0; c < channels; ++c) {
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
chw.at<uchar>(index++) = rgb_image.at<cv::Vec3b>(h, w)[c];
}
}
}
// 创建 NCHW 格式的输出图像
nchw_image.create(1, channels * height * width, CV_8UC1);
std::memcpy(nchw_image.data, chw.data, chw.total() * chw.elemSize());
}
mark