使用imread打开带有unicode名称的图像文件

时间:2017-04-12 04:50:57

标签: c++ image opencv unicode

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

1 个答案:

答案 0 :(得分:3)

你可以:

  1. 使用ifstream
  2. 打开文件
  3. std::vector<uchar>
  4. 中全部阅读
  5. 使用cv::imdecode对其进行解码。
  6. 请参阅下面的示例,使用img2将带有Unicode文件名的图片加载到ifstream中:

    #include <opencv2\opencv.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 filenames\n";
        }
        else {
            cout << "Work with Unicode filenames\n";
            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 filenames\n";
        }
        else {
            cout << "Work with Unicode filenames\n";
            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);
    

    为了完整性,here您可以在Python中看到如何执行此操作