这段时间在做关于svm训练的测试,需要对正负样本进读入,顾参考同事的代码,写了如下类
头文件:getDirImageList.h
#pragma once #include <io.h> #include <string> #include <afx.h> //#include "keyDefine.h" class CReadImgPatch { private: CString mImgAdress; CStringArray m_ImgInfo; int m_ntotal_sample; public: void mSetDir(CString dir); void mInit(const CString m_); int GetDirImageList(const CString &dir, CStringArray &filearray);//只有这个有用,其他的是为了扩展用的 };
cpp文件:getDirImageList.cpp
#include "getDirImageList.h" int CReadImgPatch::GetDirImageList(const CString &dir, CStringArray &filearray) { CString _find_filename = dir+_T("\\*.jpg"); filearray.RemoveAll(); _finddata_t _find_data; memset(&_find_data, 0, sizeof(_find_data)); intptr_t _find_handle = _findfirst(_find_filename, &_find_data); if (-1 == _find_handle) { return 0; } do { if (FILE_ATTRIBUTE_ARCHIVE == _find_data.attrib) { filearray.Add(dir+_T("\\") + _find_data.name); } } while ( 0== _findnext(_find_handle,&_find_data)); return filearray.GetSize(); }
测试代码:main.cpp#include <fstream> #include <opencv2/opencv.hpp> #include "getDirImageList.h" using namespace std; int main(int argc, char* argv) { CString positive_sample_dir = "E:\\zzd\\experienceData\\humanCount\\head\\pos\\"; CString negetive_sample_dir = "E:\\zzd\\experienceData\\humanCount\\head\\neg"; CStringArray m_testimage_positive; CStringArray m_testimage_negative; int m_npositive_sample = GetDirImageList(positive_sample_dir,m_testimage_positive); int m_nnegative_sample = GetDirImageList(negetive_sample_dir,m_testimage_negative); int m_ntotal_sample = m_npositive_sample+m_npositive_sample; for (int i=0; i<m_npositive_sample; i++) { Mat m_srcimg = imread(m_testimage_positive[i].GetBuffer(),0); } return 1; }
但是在使用本代码之前需要设置关于MFC和多字节处理,
1.项目->属性->配置属性->常规->MFC的使用:选择在共享DLL中使用MFC,否则将会报如下错误:
fatal error C1189: #error : Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d]
2.项目->属性->配置属性->常规->字符集:选择使用多字节字符集,否则会报如下错误:
error C2664: “_findfirst64i32”: 不能将参数 1 从“CString”转换为“const char *”
因为在vs2010中默认字符集是UNICODE字符集,CString中字符是以wchar_t的形式来存储的,而不是char