opencv imread() on Windows for non-ASCII file names

后端 未结 4 1319
清歌不尽
清歌不尽 2020-12-10 04:55

We have an OpenCV problem of opening (and writing) file paths that contain non-Ascii characters on Windows. I saw questions OpenCV imread with foreign characters and imread

4条回答
  •  眼角桃花
    2020-12-10 05:41

    Here my solution using std::ifstream:

    std::ifstream file(path.toStdWString(), std::iostream::binary);
    if (!file.good()) {
        return cv::Mat();
    }
    file.exceptions(std::ifstream::badbit | std::ifstream::failbit | std::ifstream::eofbit);
    file.seekg(0, std::ios::end);
    std::streampos length(file.tellg());
    std::vector buffer(static_cast(length));
    if (static_cast(length) == 0) {
        return cv::Mat();
    }
    file.seekg(0, std::ios::beg);
    try {
        file.read(buffer.data(), static_cast(length));
    } catch (...) {
        return cv::Mat();
    }
    file.close();
    cv::Mat image = cv::imdecode(buffer, CV_LOAD_IMAGE_COLOR);
    return image;
    

    Or a bit shorter using Qt:

    QFile file(path);
    std::vector buffer;
    buffer.resize(file.size());
    if (!file.open(QIODevice::ReadOnly)) {
        return cv::Mat();
    }
    file.read(buffer.data(), file.size());
    file.close();
    cv::Mat image = cv::imdecode(buffer, CV_LOAD_IMAGE_COLOR);
    return image;
    

提交回复
热议问题