我想做一個簡單的程序,將從OpenCV和C++的背景中減去一個對象。OpenCV C++ videocapture圖像背景減去
的想法是使用VideoCapture到:
- 捕捉靜態背景(沒有物體)
- 然後連續捕捉當前幀和減去從背景
然而,將捕獲的數據發送到我的BackgroundSubtraction()函數時遇到問題。它給我一個錯誤:
Unhandled exception at 0x77d815 in OpenCV_BackgroundSubtraction.exe: 0xC000005: Acces violation regarding location 0x04e30050
然而,有時似乎工作(在Windows 7 64位使用Visual Studio 2010 C++),其他時間不。
我有一種感覺,它與內存分配和功能的優先級有關。在將視頻發送給BackgroundSubtraction()之前,看起來VideoCapture抓取器的抓取/寫入幀可能不夠快。
我的筆記本電腦中的內置攝像頭工作正常(即它顯示圖片),但我的代碼中的東西是錯誤的。我嘗試過拖延時間,但似乎沒有影響。
這裏是我的代碼:
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。儘管可能有一些內置函數來完成這項工作,但我寧願自己製作算法。
你在哪一行得到錯誤? –