opencv读取和保存图像
当前环境
VS2022
opencv4.6.0+contrib
halcon识别一维码识别步骤如下:
读取单个图像并保存
函数说明:
@param filename:图像路径.
@param flags: 加载的格式有很多,常用的有三种,-1:原始图像,0:灰度图像,1:彩色图像加载
Mat imread( const String& filename, int flags = IMREAD_COLOR );
#include <iostream>
#include <opencv2/opencv.hpp>
int main()
{
//1 加载图像
cv::Mat srcImg = cv::imread("../Data/1.png", -1);
if (srcImg.empty())
{
std::cerr << "Failed to load the image." << std::endl;
return -1;
}
//2 保存图像
cv::imwrite("../Data/1_save.png", srcImg);
return 0;
}
读取文件夹内所有图像并保存
需要注意的是,DstImg文件夹应该手动创建,当然也可以在代码中先判断文件夹是否存在,不存在则创建
#include <iostream>
#include <opencv2/opencv.hpp>
int main()
{
cv::Mat srcImg, dstImg;
cv::String savedfilename;
cv::String savepath = "../Data/DstImg/";
std::vector<cv::Mat> images; //存放文件数据
//1 加载路径
cv::String readpath = "../Data/SrcImg/*.jpg";
std::vector<cv::String> filenames;
cv::glob(readpath, filenames, true);
//2 加载图像并保存
for (int i = 0; i < filenames.size(); i++)
{
//2.1 加载图像
srcImg = cv::imread(filenames[i], -1);
if (srcImg.empty())
{
std::cerr << filenames[i] << " can't be loaded!" << std::endl;
continue;
}
images.push_back(srcImg);
//3 图像保存
savedfilename = savepath + std::to_string(i) + ".jpg";
imwrite(savedfilename, images[i]);
}
return 0;
}
总结
如有错误欢迎指正,共同进步!