问题描述
我需要读取带有Unicode名称的图像文件,但openCV函数imread的图像名称参数仅支持字符串。如何将Unicode路径保存到字符串对象。有没有解决方法?
I need reading image files with Unicode names however openCV function imread's argument for image names supports only strings. how can I save my Unicode path to string objects. Is there any solution for this?
推荐答案
您可以:
- 使用
ifstream
打开文件, - 在
标准中读取所有内容: :vector< uchar>
, - 使用
cv :: imdecode
对其进行解码。
- open the file with
ifstream
, - read it all in a
std::vector<uchar>
, - decode it with
cv::imdecode
.
请参阅下面的示例加载到 img2
带有Unicode文件名的图像使用 ifstream
:
See the example below that loads into img2
an image with a Unicode filename using 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
提供了一种简单的文件大小方式:
If you're using Qt, you can do this a little more conveniently with QFile
and QString
, since QString
natively handle Unicode characters, and QFile
provides an easy way to the the file size:
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);
为了完整性,你可以看到如何用Python做到这一点
For completeness, here you can see how to do this in Python
这篇关于使用imread打开带有unicode名称的图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!