分享

OpenCV基于自适应背景更新的运动目标检测

 Y忍冬草 2016-12-06


下面这段代码利用OpenCV实现了最为简单的基于自适应背景更新的运动目标检测算法。


即:

运动前景提取——背景减除

foreground = |frame - background| > threshold 

更新背景模型——滑动平均滤波

background = background + (frame - background) *  alpha  = background * (1 - alpha) + frame * alpha 



  1. //运动前景检测——基于自适应背景更新  
  2. //Author: www.icvpr.com  
  3. //Blog:   http://blog.csdn.net/icvpr  
  4.   
  5. #include <iostream>  
  6. #include <string>  
  7.   
  8. #include <opencv2/opencv.hpp>  
  9.   
  10. int main(int argc, char** argv)  
  11. {  
  12.     std::string videoFileName = "../test.avi";  
  13.   
  14.     int threshold = 25 ;    // 二值化阈值  
  15.     float alpha = 0.01;     // 更新速度 [0, 1]  
  16.   
  17.     cv::VideoCapture capture;  
  18.     capture.open(videoFileName);  
  19.     if (!capture.isOpened())  
  20.     {  
  21.         std::cout<<"cannot open video"<<std::endl;  
  22.         return -1;  
  23.     }  
  24.   
  25.   
  26.     cv::Mat foregroundImg;  
  27.     cv::Mat foregroundMat;  
  28.   
  29.     cv::Mat backgroundImg;  
  30.     cv::Mat backgroundMat;  
  31.   
  32.     cv::Mat frame;  
  33.     cv::Mat grayImg;  
  34.     cv::Mat grayMat;  
  35.       
  36.     while (capture.read(frame))  
  37.     {  
  38.         cv::cvtColor(frame, grayImg, CV_BGR2GRAY);  
  39.         grayImg.convertTo(grayMat, CV_32FC1);  
  40.   
  41.         if (backgroundMat.empty())  
  42.         {  
  43.             grayImg.copyTo(backgroundImg);  
  44.             grayImg.convertTo(backgroundMat, CV_32FC1);       
  45.         }  
  46.           
  47.         // 背景减除  
  48.         cv::absdiff(grayMat, backgroundMat, foregroundMat);  
  49.           
  50.         // 自适应背景更新  
  51.         cv::addWeighted(backgroundMat, alpha, foregroundMat, 1-alpha, 0, backgroundMat);  
  52.   
  53.         // 二值化,获取前景像素点  
  54.         cv::threshold(foregroundMat, foregroundMat, threshold, 255, CV_THRESH_BINARY);  
  55.   
  56.   
  57.         // 为了显示用,将CV_32FC1转换为CV_8U  
  58.         cv::convertScaleAbs(foregroundMat, foregroundImg);  
  59.         cv::convertScaleAbs(backgroundMat, backgroundImg);  
  60.   
  61.         cv::imshow("frame", frame);  
  62.         cv::imshow("foreground", foregroundImg);  
  63.         cv::imshow("background", backgroundImg);  
  64.   
  65.         if (cv::waitKey(25) > 0)  
  66.         {  
  67.             break;  
  68.         }  
  69.     }  
  70.   
  71.     return 0;  
  72. }  


--------------------------------------------------------
< 转载请:http://blog.csdn.net/icvpr>

  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多