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
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;