制作模板图过程中用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