取现场网络摄像头的平均值

时间:2016-10-06 10:14:19

标签: c++ opencv image-processing

我首先使用此代码捕获网络摄像头帧:

int main(int argc, char** argv)
{
    VideoCapture cap(0); // open the default camera
    if (!cap.isOpened())  // check if we succeeded
        return -1;
    cap.set(CV_CAP_PROP_FPS, 15);

    std::vector<cv::Mat> images(100);
    for (framenumb = 0; framenumb < 100; ++framenumb)
    {
        // this is optional, preallocation so there's no allocation
        // during capture
        images[framenumb].create(480, 640, CV_32FC3);
    }
    for (framenumb = 0; framenumb < 100; ++framenumb)
    {
        Mat frame;
        cap >> frame;
        if (frame.empty()) break; // end of video stream
        imshow("webcam", frame);
        if (waitKey(1) == 27) break; // stop capturing by pressing ESC 
        frame.copyTo(images[framenumb]);
    }

然后尝试使用以下代码来平均捕获的帧:

Mat avgImg;
Mat capturedImg;
for (framenumb = 0; framenumb < 100; ++framenumb)
{
    avgImg.create(480, 640, CV_32FC3);
    capturedImg = images[framenumb];
    cv::accumulate(capturedImg, avgImg);
}
avgImg = avgImg / 100;
avgImg.convertTo(avgImg, CV_8UC3);
imshow("averaged", avgImg);

然而它刚刚打破了程序并给了我一个黑色的图像。任何人都可以帮我确定错误的位置吗?非常感谢你

1 个答案:

答案 0 :(得分:2)

你需要:

  1. 创建零初始化累积图像
  2. 将每张图片添加到其中
  3. 将累积的图像除以图像数
  4. 而是在每一帧重新创建一个空的累积图像。

    代码应更改为:

    Mat avgImg(480, 640, CV_32FC3, Scalar()); // Create and zero initialize
    Mat capturedImg;
    for (framenumb = 0; framenumb < 100; ++framenumb)
    {
        // avgImg.create(480, 640, CV_32FC3); // Don't create each time!
        capturedImg = images[framenumb];
        cv::accumulate(capturedImg, avgImg);
    }
    

    您可以将代码简化为:

    Mat avgImg(480, 640, CV_32FC3, Scalar()); // Create and zero initialize
    for (framenumb = 0; framenumb < 100; ++framenumb)
    {
        avgImg += images[framenumb];
    }