You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何std::filesystem::path类型参数需调用.string()传入OpenCV函数?

问题解答

报错原因

cv::imread和cv::imwrite要求的路径参数类型是const cv::String&(OpenCV对std::string的封装),而std::filesystem::path是C标准库中独立的文件路径类型,两者属于不同的类型体系,C语言本身没有定义从std::filesystem::path到std::string/cv::String的隐式转换规则,所以直接传递path对象会触发类型不匹配的编译错误。

为什么.string()能解决问题

std::filesystem::path类提供了.string()成员函数,它会将路径对象转换为std::string类型的字符串。由于cv::String可以隐式接收std::string,所以传递.string()的返回值就能满足OpenCV函数的参数要求,编译通过。

代码里的其他小问题

  • 重复定义了Mat img,会导致编译错误
  • 变量sr未定义,需使用传入的model对象调用upsample
  • sr.upsample(img, img_new)末尾缺少分号
  • img_new未定义,需要提前声明

修正后的示例代码:

#include <filesystem>
#include <opencv2/opencv.hpp>
#include <opencv2/dnn_superres.hpp>

int upsample(cv::dnn_superres::DnnSuperResImpl model,
             std::filesystem::path f,
             std::filesystem::path s) {
    cv::Mat img = cv::imread(f.string()); // 转换为string传入
    if (img.empty()) {
        return -1; // 处理图片读取失败的情况
    }
    cv::Mat img_new;
    model.upsample(img, img_new); // 使用传入的model对象
    cv::imwrite((s / f.filename()).string(), img_new); // 路径拼接后转string
    return 0;
}

内容的提问来源于stack exchange,提问作者InterestingQuestions44

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:45:52