c++ opencv读取图片
时间: 2023-09-07 17:17:21 浏览: 46
使用OpenCV读取图片可以使用以下代码:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// 读取图片
Mat image = imread("image.jpg");
// 判断图片是否读取成功
if (image.empty()) {
cout << "Could not open or find the image" << endl;
return -1;
}
// 显示图片
imshow("Image", image);
// 等待按键
waitKey(0);
return 0;
}
```
其中,imread()函数用于读取图片,imshow()函数用于显示图片,waitKey()函数用于等待按键。需要注意的是,图片路径应该根据实际情况进行修改。
相关问题
c++ opencv 读取图像为灰度图
可以使用OpenCV库中的imread函数读取图像,并将其转化为灰度图像。具体代码如下:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
Mat image = imread("test.jpg", IMREAD_GRAYSCALE); // 读取灰度图像
imshow("gray image", image);
waitKey(0);
return 0;
}
```
其中,第二个参数IMREAD_GRAYSCALE表示读取图像时将其转换为灰度图像。读取成功后,可以使用imshow函数显示灰度图像。
C++ opencv 读取中文路径图片
在C++中,可以使用OpenCV库中的imread函数来读取图像,但是它只支持ASCII字符集的路径。如果路径中包含中文字符,可以尝试以下两种方法。
方法一:使用Unicode编码的路径
可以将中文路径转换为Unicode编码,然后使用wstring类型存储路径,最后使用imread函数读取图像。示例代码如下:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace cv;
int main()
{
wstring path = L"D:\\中文路径\\image.jpg"; // 将中文路径转换为Unicode编码
Mat img = imread(string(path.begin(), path.end())); // 将wstring类型转换为string类型
if (img.empty()) {
cout << "Failed to read image!" << endl;
return -1;
}
imshow("Image", img);
waitKey(0);
return 0;
}
```
方法二:使用boost库
可以使用boost库中的filesystem模块来处理中文路径。首先需要安装boost库,并将boost的头文件和库文件链接到工程中。示例代码如下:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
using namespace std;
using namespace cv;
using namespace boost::filesystem;
int main()
{
string path = "D:/中文路径/image.jpg";
path p(path); // 将路径转换为boost库中的path类型
Mat img = imread(p.string());
if (img.empty()) {
cout << "Failed to read image!" << endl;
return -1;
}
imshow("Image", img);
waitKey(0);
return 0;
}
```
这两种方法都可以读取中文路径的图像。需要注意的是,在Windows操作系统中,路径分隔符应该使用反斜杠`\`而不是正斜杠`/`。