我有一个具有局部变量(posX和posY)的函数(trackObject)。
并且在该函数内部有两个依赖于这两个变量的函数调用。(checkIntersection和checkHit)。
如果我编译程序,该程序运行良好但有点滞后。
我想在trackObject之外调用那两个函数,但是无法访问这两个局部变量。 我想访问它,但我不知道如何。
我尝试将这些变量设为全局变量,但是将这些变量设为全局使得另一个变量(时刻,时刻10,时刻01和区域)也必须设置为全局变量。
但是当我这样做时,我得到了Heap Corruption例外。
任何人都知道该怎么做?或者还有另一种解决方案吗?
这是我的代码
void trackObject(IplImage* imgThresh){
// Calculate the moments of 'imgThresh'
CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
cvMoments(imgThresh, moments, 1);
double moment10 = cvGetSpatialMoment(moments, 1, 0);
double moment01 = cvGetSpatialMoment(moments, 0, 1);
double area = cvGetCentralMoment(moments, 0, 0);
// if the area<1000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
if(area>1000){
// calculate the position of the ball
int posX = moment10/area;
int posY = moment01/area;
if(lastX>=0 && lastY>=0 && posX>=0 && posY>=0)
{
// Draw a yellow line from the previous point to the current point
cvLine(imgTracking, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,0,255), 4);
}
checkIntersection(300, lastY, posY);
checkHit(posX,posY,lastX,lastY,startLineX, startLineY, endLineX, endLineY);
lastX = posX;
lastY = posY;
}
cvLine(imgTracking,cv::Point(100,300) , cv::Point(600,300),cv::Scalar(0,200,0),2,8);
cvLine(imgTracking,cv::Point(100,400) , cv::Point(168,400),cv::Scalar(255,0,122),8,8);
cvLine(imgTracking,cv::Point(171,400) , cv::Point(239,400),cv::Scalar(255,0,122),8,8);
cvLine(imgTracking,cv::Point(241,400) , cv::Point(309,400),cv::Scalar(255,0,122),8,8);
cvLine(imgTracking,cv::Point(312,400) , cv::Point(380,400),cv::Scalar(255,0,122),8,8);
cvLine(imgTracking,cv::Point(383,400) , cv::Point(451,400),cv::Scalar(255,0,122),8,8);
cvLine(imgTracking,cv::Point(454,400) , cv::Point(522,400),cv::Scalar(255,0,122),8,8);
cvLine(imgTracking,cv::Point(525,400) , cv::Point(600,400),cv::Scalar(255,0,122),8,8);
free(moments);
}
答案 0 :(得分:2)
使用指针将它们复制到调用函数的变量中:
void trackObject(IplImage* imgThresh, int *pX, int *pY)
{
...
*pX = moment10 / area;
*pY = moment01 / area;
...
}
调用函数需要一些int
来存储这些值:
IplImage imgThresh;
int copyX, copyY;
trackObject(&imgThresh, ©X, ©Y);
答案 1 :(得分:1)
减少&#34;滞后&#34;通过删除对malloc()和free()的调用:
void trackObject(IplImage* imgThresh){
CvMoments moments;
cvMoments(imgThresh, &moments, 1);
double moment10 = cvGetSpatialMoment(&moments, 1, 0);
double moment01 = cvGetSpatialMoment(&moments, 0, 1);
double area = cvGetCentralMoment(&moments, 0, 0);
//...
注意CvMoments局部变量的声明,然后所需要的只是将此局部变量的地址传递给需要指向CvMoments的指针的函数。
答案 2 :(得分:0)
如果您遇到性能问题,可能是由于以下行:
CvMoments moments =(CvMoments )malloc(sizeof(CvMoments));
如果频繁调用trackObject()
,则malloc
重复调用会很昂贵。