我是opencv和c ++的新手,我已经阅读了关于cvpoint数组的类似问题,但我无法使其工作。这是我的代码,我试图将CvPoint分配给CvPoint数组,将CvPoint分配给CvSeq:
.................
CvMemStorage* storage = cvCreateMemStorage(0);
CvMemStorage* storage1 = cvCreateMemStorage(0);
CvSeq* lines = 0;
CvSeq* coor = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint)*2, storage1);
lines = cvHoughLines2(roiblob, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 20, 10, 5);
ncoor = 0;
CvPoint centers;
CvPoint pt[2];
CvPoint *centerlist = new CvPoint [lines->total];
for(int i = 0; i < lines->total; i++ ) {
CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
pt[0] = line[0];
pt[1] = line[1];
pt[0] = cvPoint(pt[0].x + pointawal.x, pt[0].y + pointawal.y);
pt[1] = cvPoint(pt[1].x + pointawal.x, pt[1].y + pointawal.y);
double theta = atan((double)(pt[1].y - pt[0].y)/(pt[1].x - pt[0].x));
if (cos(theta) > 0.996) {
centers = cvPoint(pt[0].x + (pt[1].x - pt[0].x)/2, pt[0].y + (pt[1].y - pt[0].y)/2);
cvSeqPush(coor,&pt); // here the 1st problem
centerlist[ncoor] = centers; // here the 2nd problem
这里我得到了正确的中心值:128
cout << centerlist[ncoor].x << "\n";
ncoor++;
}
这里我得到了错误的值(每个迭代的负值具有相同的值,例如:-85415)
cout << centerlist[ncoor].x << "\n";
}
我觉得问题出现在1和2
上答案 0 :(得分:0)
最后在搜索到处后,我得到了答案,我使用malloc和realloc来替换new,我仍然不明白如何使用CvSeq所以我也替换它。 这是我的新代码:
................
CvPoint *centerlist,*coor1,*coor2*,tempcenterlist,*tempcoor1,*tempcoor2;
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* lines = 0;
lines = cvHoughLines2(roiblob, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 20, 10, 5);
centerlist = (CvPoint*)malloc(sizeof(CvPoint)); // use malloc here to replace new
coor1 = (CvPoint*)malloc(sizeof(CvPoint));
coor2 = (CvPoint*)malloc(sizeof(CvPoint));
CvPoint pt0,pt1,centers;
ncoor = 0;
for(int i = 0; i<lines->total; i++ ) {
CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
pt0 = line[0];
pt1 = line[1];
pt0 = cvPoint(pt0.x + pointawal.x, pt0.y + pointawal.y);
pt1 = cvPoint(pt1.x + pointawal.x, pt1.y + pointawal.y);
double theta = atan((double)(pt1.y - pt0.y)/(pt1.x - pt0.x));
if (cos(theta) > 0.996) {
centers = cvPoint(pt0.x + (pt1.x - pt0.x)/2, pt0.y + (pt1.y - pt0.y)/2);
centerlist[ncoor] = centers;
coor1[ncoor] = pt0;
coor2[ncoor] = pt1;
//use realloc here
tempcenterlist = (CvPoint*)realloc(centerlist,(i+2)*sizeof(CvPoint));
tempcoor1 = (CvPoint*)realloc(coor1,(i+2)*sizeof(CvPoint));
tempcoor2 = (CvPoint*)realloc(coor2,(i+2)*sizeof(CvPoint));
if (tempcenterlist != NULL ) centerlist = tempcenterlist;
if (tempcoor1 != NULL ) coor1 = tempcoor1;
if (tempcoor2 != NULL ) coor2 = tempcoor2;
else {
free(centerlist);
free(coor1);
free(coor2);
printf("Error allocating memory!\n");
}
ncoor++;
}
}
// check the array value
if (ncoor > 0) cout << centerlist[0].x << centerlist[0].y << "\n";
我不知道我是否使用内存效率与否,但它现在正在工作,而且在我到处搜索后我感到非常高兴。感谢。
答案 1 :(得分:0)
问题在于:
CvPoint *centerlist = new CvPoint [lines->total];
您正在创建引用,但仍需要为每个引用创建一个对象。
centerlist[ncoor] = CvPoint(centers);