opencv保存jpg格式图片 C++
时间: 2024-12-06 11:20:16 浏览: 20
在OpenCV库中,使用C++保存JPEG格式的图片通常涉及以下几个步骤:
1. 导入必要的库:
```cpp
#include <opencv2/opencv.hpp>
```
2. 加载图像数据:
```cpp
cv::Mat image = cv::imread("input_image.jpg"); // 读取图像文件
if (!image.data) {
std::cout << "Error reading the image" << std::endl;
return;
}
```
3. 设置存储选项(如果你需要自定义质量或其他设置,可以传递一个`cv::IMWRITE_JPEG_QUALITY`标志):
```cpp
cv::Mat result;
int quality = 95; // JPEG质量范围0-100,默认值为95
if (image.type() == CV_8UC4) { // 确保是RGBA格式,如果是BGR则转换
cv::cvtColor(image, result, cv::COLOR_BGR2RGB);
} else {
result = image.clone();
}
std::vector<int> params;
params.push_back(cv::IMWRITE_JPEG_QUALITY);
params.push_back(quality);
```
4. 将图像保存为JPEG格式:
```cpp
std::string output_path = "output_image.jpg";
cv::imwrite(output_path, result, params);
if (!cv::imwrite(output_path, result)) {
std::cout << "Failed to write the image" << std::endl;
}
```
阅读全文