【OpenCV】std::vector<cv::Mat>

制作模板图过程中用vector保存模板图,调试了一中午终于发现错误的地方,非常狗血,提醒大家以后注意使用

std::vector<cv::Mat>

方法一:

std::vector<cv::Mat> template_img;
template_img.push_back(img);

方法二:

std::vector<cv::Mat> template_img;
template_img.push_back(img.clone());

完整代码:

#include <iostream>
#include <cv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include<string.h>
#include <Windows.h>

using namespace cv;
using namespace std;

bool GetImgNameFromFile(const char *filename, vector<string> &imgpath)
{
	WIN32_FIND_DATAA imgdata;
	HANDLE hFind;
	hFind = FindFirstFileA((LPCSTR)filename, &imgdata);
	//如果该目录下没有图片;
	if (hFind == INVALID_HANDLE_VALUE)
	{
		printf("Invalid File Handle. GetLastError reports %d\n", GetLastError());
		return false;
	}
	do
	{
		imgpath.push_back(imgdata.cFileName);
	} while (FindNextFileA(hFind, &imgdata));

	FindClose(hFind);			//关闭句柄,释放资源;
	return true;
}

void characterDB(std::vector<cv::Mat> &template_img)
{
	template_img.clear();
	Mat img;
	Mat img_resize;

	string template_root_path = "F:\\vs\\show\\Template\\";
	string template_num_path[8] = { "0.jpg", "1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"};
	string foldername = "F:\\vs\\show\\Template\\number\\";
	string temp = foldername + string("*.jpg");
	const char *filename = temp.c_str();
	vector<string> imgpath;
	GetImgNameFromFile(filename, imgpath);

	for (std::size_t i = 0; i < imgpath.size(); i++)
	{
		string path = foldername + imgpath[i];
		Mat img = imread(path, 1);			// 读取原图

		template_img.push_back(img.clone());	// 添加元素 方式一
		//template_img.push_back(img);	// 添加元素 方式二

		string template_path = template_root_path + template_num_path[i];
		cv::imwrite(template_path, img);		//保存模板
	}

	return;
}

void main()
{
	std::vector<cv::Mat> template_img;
	characterDB(template_img);
	
	cv::imshow("0", template_img[0]);
	cv::imshow("1", template_img[1]);
	cv::imshow("2", template_img[2]);
	cv::imshow("3", template_img[3]);
	cv::imshow("4", template_img[4]);
	cv::imshow("5", template_img[5]);
	cv::imshow("6", template_img[6]);
	cv::waitKey();

}

区别:方法二vector中的元素添加正确

分析:出现这样问题的原因,可以查看vector的push_back()函数及Mat的copy constructor

完整工程: 链接:http://pan.baidu.com/s/1boBhy2N 密码:t1hp

reference:http://blog.csdn.net/yiyuehuan/article/details/44656723

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值