OpenCv3编程学习七

    技术2022-07-11  73

    了解两种输入类型:

    XML和YAML文件

    xml:是可扩展标识语言,而YAM相对来说更加优化了xml的优点。 首先采用FileStorage类来进行xml写入或者读取数据。 1.实例化一个FileStorage类的对象 2.使用流操作符 3.使用一个释放函数来构掉类 第一步是XML和YAML文件的打开: 1.调用构造函数准备文件读操作 2.调用函数准备文件写操作 第二步是进行文件读写操作 1.文本和数字的输入输出:写入文件可以用“<<” 读取文件可以用“>>” 第三步是vector和maps的输入输出 对于vector结构来说,要在第一个元素前面加“[”,最好一个元素前面加“]”,而map则是,第一个加“{”,最后一个加“}” 最后一步是:调用release函数进行文件的关闭。

    #include<opencv2/opencv.hpp> #include<time.h> using namespace cv; int main() { //首先是调用函数初始化 FileStorage fs("test.yaml", FileStorage::WRITE); //再试文件的写入 fs << "frameCount" << 5; time_t rawtime; time(&rawtime); fs << "calibrationDate" << asctime(localtime(&rawtime)); Mat cameraMatrix = (Mat_<double>(3, 3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1); Mat distCoeffs = (Mat_<double>(5, 1) << 0.1,0.01,-0.001, 0, 0); fs << "cameraMatrix" << cameraMatrix << "disCoeffs" << distCoeffs; fs << "features" << "["; for (int i = 0; i < 3; i++) { int x = rand() % 640; int y = rand() % 480; uchar lbp = rand() % 256; fs << "{:" << "x" << x << "y" << y << "lbp" << "[:"; for (int j = 0; j < 8; j++) fs << ((lbp >> j) & 1); fs << "]" << "}"; } fs << "]"; fs.release(); printf_s("文件读写完毕,请在工程目录下查看生成的文件"); getchar(); return 0; }

    这样就会生成一个对应的文件,格式按照代码书写出来。

    其次就是对于xml文件的读取:

    #include<opencv2/opencv.hpp> #include<time.h> using namespace cv; using namespace std; int main() { //先改变对应的字体颜色 system("color 6F"); //进行初始化 FileStorage fs2("test.yaml", FileStorage::READ); //第一种方法 int frameCount = (int)fs2["frameCount"]; std::string date; //使用第二种方法,直接用FileNode运算符 fs2["calibrationDate"] >> date; Mat cameraMatrix2, distCoeffs2; fs2["cameraMatrix"] >> cameraMatrix2; cout << "frameCount:" << frameCount << endl << "calibration date:" << date << endl << "camera matrix: " << cameraMatrix2 << endl << "distortion coeffs: " << distCoeffs2 << endl; FileNode features = fs2["faetures"]; FileNodeIterator it = features.begin(), it_end = features.end(); int idx = 0; std::vector<uchar> lbpval; //使用fileNodeIterator来遍历序列 for (; it != it_end; ++it, idx++) { cout << "feature #" << idx << ";"; cout << "x=" << (int)(*it)["x"] << ",y=" << (int)(*it)["y"] << ", lbp:("; //或者用另一种方法 (*it)["lbp"] >> lbpval; for (int i = 0; i < (int)lbpval.size(); i++) cout << "" << (int)lbpval[i]; cout << ")" << endl; } //再进行释放 fs2.release(); //再输入一些帮助字符 printf_s("\n文件读取完毕,请输入任意键结束程序"); getchar(); return 0; }
    Processed: 0.010, SQL: 9