opencv(C++)读取和保存图像:读取单个图像并保存+读取文件夹内所有图像并保存

当前环境

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;
}

总结

  如有错误欢迎指正,共同进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值