我需要读取带有Unicode名称的图像文件,但openCV函数imread的图像名称参数仅支持字符串。如何将Unicode路径保存到字符串对象。对此有什么解决方案吗?
答案 0 :(得分:3)
你可以:
ifstream
,std::vector<uchar>
,cv::imdecode
对其进行解码。 请参阅下面的示例,使用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,则可以使用QFile
和QString
更方便地执行此操作,因为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中看到如何执行此操作