本文主要是介绍《学习OpenCV》课后习题解答7,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:(P105)
创建一个结构,结构中包含一个整数,一个CvPoint和一个 CvRect;称结构体为“my_struct”。
a. 写两个函数:void Write_my_strct(CvFileStorage* fs, const char * name, my_struct* ms) 和 void read_my_struct(CvFileStorage* fs, CvFileNode* ms_node, my_struct* ms)
b. 创建一个元素为my_struct结构体且长度为10的数组,并将数组写入磁盘和从磁盘读入内存。
解答:
#include<cv.h>
#include<highgui.h>typedef struct my_struct {int integer;CvPoint ptr;CvRect rect;
}my_struct;void write_my_struct(CvFileStorage* fs, const char* name, my_struct* ms) {cvWriteInt(fs, "integer", ms[0].integer);cvStartWriteStruct(fs, "ptr", CV_NODE_SEQ);cvWriteInt(fs, NULL, ms[0].ptr.x);cvWriteInt(fs, NULL, ms[0].ptr.y);cvEndWriteStruct(fs);cvStartWriteStruct(fs, "rect", CV_NODE_SEQ);cvWriteInt(fs, NULL, ms[0].rect.x);cvWriteInt(fs, NULL, ms[0].rect.y);cvWriteInt(fs, NULL, ms[0].rect.width);cvWriteInt(fs, NULL, ms[0].rect.height);cvEndWriteStruct(fs);
}void read_my_struct(CvFileStorage* fs, CvFileNode* ms_node, my_struct* ms) {int integer = cvReadIntByName(fs, NULL, "integer", 5);CvSeq* seq = cvGetFileNodeByName(fs, NULL, "ptr")->data.seq;int ptr_x = cvReadInt((CvFileNode*)cvGetSeqElem(seq, 0));int ptr_y = cvReadInt((CvFileNode*)cvGetSeqElem(seq, 1));seq = cvGetFileNodeByName(fs, NULL, "rect")->data.seq;int rect_x = cvReadInt((CvFileNode*)cvGetSeqElem(seq, 0));int rect_y = cvReadInt((CvFileNode*)cvGetSeqElem(seq, 1));int rect_width = cvReadInt((CvFileNode*)cvGetSeqElem(seq, 2));int rect_height = cvReadInt((CvFileNode*)cvGetSeqElem(seq, 3));CvPoint ptr = cvPoint(ptr_x, ptr_y);CvRect rect = cvRect(rect_x, rect_y, rect_width, rect_height);ms->integer = integer;ms->ptr.x = ptr_x;ms->ptr.y = ptr_y;ms->rect.x = rect_x;ms->rect.y = rect_y;ms->rect.width = rect_width;ms->rect.height = rect_height;
}int main(int argc, char** argv) {my_struct ms[10] = { { 10, cvPoint(5, 5), cvRect(5, 5, 10, 10) } };CvFileStorage* sfs = cvOpenFileStorage("E:\\cfg.xml", NULL, CV_STORAGE_WRITE);write_my_struct(sfs, "struct", ms);cvReleaseFileStorage(&sfs);my_struct* ms2 = (my_struct*)malloc(sizeof(my_struct));CvFileStorage* ofs = cvOpenFileStorage("E:\\cfg.xml", NULL, CV_STORAGE_READ);read_my_struct(ofs, NULL, ms2);cvReleaseFileStorage(&ofs);printf("integer: %d\n", ms2->integer);printf("ptr: (%d, %d) \n", ms->ptr.x, ms->ptr.y);printf("rect: (%d, %d, %d, %d) \n", ms->rect.x, ms->rect.y, ms->rect.width, ms->rect.height);getchar();return 0;
}
这篇关于《学习OpenCV》课后习题解答7的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!