2017-04-12 93 views
1

我需要使用Unicode名稱讀取圖像文件,但openCV函數imread的圖像名稱參數僅支持字符串。我怎樣才能保存我的Unicode路徑字符串對象。有沒有解決方案?使用imread打開unicode名稱的圖像文件

+0

有可能是一個合適的解決方案,但作爲一種解決方法,你可以創建一個純ASCII文件名指向其Unicode文件名以外的符號鏈接OpenCV讓OpenCV在操作系統級別索引外部時處理它們。這就是'ln -s UnicodeName.jpg ASCIIName.jpg',然後用你的程序處理'ASCIIName.jpg'。 –

回答

2

您可以:

  1. 打開與ifstream文件,
  2. 讀這一切在std::vector<uchar>
  3. cv::imdecode解碼。

請參見下面的例子加載到img2使用ifstream一個Unicode文件名的圖像:

#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,您可以用QFile做多這一點方便和QString,因爲QString本地處理Unicode字符,而QFile提供了一種簡單的方法來處理文件大小:

QString name = "path/to/unicode_img"; 
QFile file(name); 
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做這個

+1

酷解決方案 - 天才! –

+0

哦,是的,它的工作! – ahamid555

+0

@ahamid很高興幫助;) – Miki

相關問題