人数识别(转)

步骤: 
1.视频图像灰度化img 
2,选取第一帧图像first_img,视频每帧和第一帧相减,得到src 
3,对src图片进行 阈值,滤波处理 
4,查找处理好图片的边界findContours; 
5,对边界区域进行统计,满足条件的进行计数

如果把前景提取出来,再对比再找,这样的话效果比较好!

代码实 现:

using namespace std;
using namespace cv;


int main(){
    Mat img, src, frame, frame_gray, first_frame, threshold_src, gass_src, dilate_src;

    VideoCapture cap("m.avi");
    cap >> first_frame;
    cvtColor(first_frame, first_frame, CV_BGR2GRAY);
    int num=0;
    int zz = 1;
    while (1){
        cap >> frame;
        if (frame.empty())
            break;
        vector<Vec4i> hierarchy;
        vector<vector<Point> > contour;
        cvtColor(frame, frame_gray, CV_BGR2GRAY);
        absdiff(frame_gray,first_frame,src);
        threshold(src, threshold_src,50,255,THRESH_BINARY);
        GaussianBlur(threshold_src, gass_src,Size(5,5),1.5);
        //blur(threshold_src, gass_src, Size(5, 5));
    //  medianBlur(threshold_src, gass_src,1);

        dilate(gass_src, dilate_src,Mat());
        findContours(dilate_src,contour, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);
        //drawContours(frame, contour, -1, Scalar(0, 0, 255),2);
        for (int i = 0; i < contour.size();i++){
            Rect bndRect = boundingRect(contour.at(i));
            Point p1,p2;
            p1.x = bndRect.x;
            p1.y = bndRect.y;
            p2.x = bndRect.x + bndRect.width;
            p2.y = bndRect.y + bndRect.height;
            if (bndRect.area()>3000){
                rectangle(frame, p1, p2, Scalar(0, 0, 255));
                num++;
            }
        }
        string font = "Current number:";
        putText(frame,font+to_string(num),Point(100,50),FONT_HERSHEY_COMPLEX_SMALL,1,Scalar(0,0,255));
    //  cout << "人数统计:" << num<<endl;
        num = 0;
        imshow("dilate_src", dilate_src);
        imshow("frame", frame);
        imshow("first_frame", first_frame);
        waitKey(20);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/necp-zwl/p/6551432.html