使用 Imread 打开具有 Unicode 名称的图像文件

open image files with unicode names using imread

本文关键字:图像 文件 Unicode Imread 使用      更新时间:2023-10-16

我需要读取带有Unicode名称的图像文件,但是openCV函数imread的图像名称参数仅支持字符串。 如何将我的 Unicode 路径保存到字符串对象。有什么解决方案吗?

您可以:

  1. 使用 ifstream 打开文件 ,
  2. std::vector<uchar>读完,
  3. cv::imdecode解码它。

请参阅下面的示例,该示例使用 ifstream 加载到具有 Unicode 文件名的图像img2

#include <opencv2opencv.hpp>
#include <vector>
#include <fstream>
using namespace cv;
using namespace std;
int main()
{
    // This doesn't work with Unicode characters
    Mat img = imread("D:\SO\img\æbärnɃ.jpg");
    if (img.empty()) {
        cout << "Doesn't work with Unicode filenamesn";
    }
    else {
        cout << "Work with Unicode filenamesn";
        imshow("Unicode with imread", img);
    }
    // This WORKS with Unicode characters
    // This is a wide string!!!
    wstring name = L"D:\SO\img\æbärnɃ.jpg";
    // Open the file with Unicode name
    ifstream f(name, iostream::binary);
    // Get its size
    filebuf* pbuf = f.rdbuf();
    size_t size = pbuf->pubseekoff(0, f.end, f.in);
    pbuf->pubseekpos(0, f.in);
    // Put it in a vector
    vector<uchar> buffer(size);
    pbuf->sgetn((char*)buffer.data(), size);
    // Decode the vector
    Mat img2 = imdecode(buffer, IMREAD_COLOR);
    if (img2.empty()) {
        cout << "Doesn't work with Unicode filenamesn";
    }
    else {
        cout << "Work with Unicode filenamesn";
        imshow("Unicode with fstream", img2);
    }
    waitKey();
    return 0;
}

如果您使用的是Qt,则可以使用QFileQString更方便地执行此操作,因为QString本机处理Unicode字符,并且QFile提供了一种简单的文件大小方法:

QString name = "path/to/unicode_img";
QFile file(name);
file.open(QFile::ReadOnly);
qint64 sz = file.size();
std::vector<uchar> buf(sz);
file.read((char*)buf.data(), sz);
cv::Mat3b img = cv::imdecode(buf, cv::IMREAD_COLOR);

为了完整起见,在这里您可以看到如何在 Python 中执行此操作