OpenCV と C++ を使用して、背景からオブジェクトを差し引く簡単なプログラムを作成しようとしています。
アイデアは、VideoCapture を使用して次のことを行うことです。
- 静的な背景をキャプチャします (オブジェクトなし)
- 次に、現在のフレームを継続的にキャプチャし、それを背景から差し引きます
ただし、キャプチャしたデータを BackgroundSubtraction() 関数に送信するときに問題が発生します。それは私にエラーを与えます:
OpenCV_BackgroundSubtraction.exe の 0x77d815 で未処理の例外: 0xC000005: 場所 0x04e30050 に関するアクセス違反
ただし、動作するように見える場合とそうでない場合があります (Windows 7 64 ビットで Visual Studio 2010 C++ を使用)。
メモリ割り当てと関数の優先度に関係があるような気がします。VideoCapture グラバーは、BackgroundSubtraction() に送信する前にフレームをグラブ/書き込みするには十分に高速ではないようです。
ラップトップの内蔵 Web カメラは正常に動作します (画像が表示されます) が、コードに何か問題があります。遅延をいじってみましたが、影響はないようです。
これが私のコードです:
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。作業を行うための組み込み関数がいくつかあるかもしれませんが、アルゴリズムを自分で作成したいと思います。