我试图制作一个简单的程序,用OpenCV和C++从背景中减去一个对象。
其想法是使用VideoCapture来:
但是,当将捕获的数据发送到我的BackgroundSubtraction()函数时,我遇到了问题。它给了我一个错误:
OpenCV_BackgroundSubtraction.exe: 0xC000005中0x77d815处的未处理异常:访问与0x04e30050位置的冲突
然而,有时它似乎起作用,有时则不起作用(在Windows 7 64位上使用Visual 2010 C++ )。
我觉得这与内存分配和函数的优先级有关。看起来,VideoCapture抓取器可能不够快,在我将它发送到BackgroundSubtraction()之前,抓取/写入框架。
在我的笔记本电脑内置摄像头工作良好(即,它显示一张图片),但在我的代码中有些地方是错误的。我试过拖延一些时间,但这似乎没有什么影响。
这是我的代码:
Mat BackgroundSubtraction(Mat background, Mat current);
int main()
{
Mat colorImage;
Mat gray;
// Background subtraction
Mat backgroundImage;
Mat currentImage;
Mat object; // the object to track
VideoCapture capture, capture2;
capture2.open(0);
// Initial frame
while (backgroundImage.empty())
{
capture2 >> backgroundImage;
cv::imshow("Background", backgroundImage);
waitKey(100);
capture2.release();
}
capture.open(0);
// Tracking the object
while (true)
{
capture >> currentImage;
if ((char)waitKey(300) == 'q') // Small delay
break;
// The problem happens when calling BackgroundSubtraction()
object = BackgroundSubtraction(backgroundImage, backgroundImage);
cv::imshow("Current frame", currentImage);
cv::imshow("Object", object);
}
Mat BackgroundSubtraction(Mat background, Mat current)
{
// Convert to black and white
Mat background_bw;
Mat current_bw;
cvtColor(background, background_bw, CV_RGB2GRAY);
cvtColor(current, current_bw, CV_RGB2GRAY);
Mat newObject(background_bw.rows, background_bw.cols, CV_8UC1);
for (int y = 0; y < newObject.rows; y++)
{
for (int x = 0; x < newObject.cols; x++)
{
// Subtract the two images
newObject.at<uchar>(y, x) = background_bw.at<uchar>(y, x)
- current_bw.at<uchar>(y, x);
}
}
return newObject;
}提前感谢!
Ps。尽管可能有一些内置的函数来完成这项工作,但我宁愿自己制作算法。
发布于 2012-10-06 15:39:03
有几件事,你可以尝试改变,以确定你的问题。但是我猜你传递给减法器函数的一幅图像是无效的。在处理它们之前,请确认两者都是有效的。
最后,您应该尝试调试您的程序,以确定代码中抛出异常的确切位置。
https://stackoverflow.com/questions/12759911
复制相似问题