⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 motiondetect.cpp

📁 face detecting motion and color of moving object in webcam
💻 CPP
字号:
// motiondetect.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "motiondetect.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "iostream"
#include "stdlib.h"

// OpenCV includes.
#include "cv.h"
#include "highgui.h"
#pragma comment(lib,"cv.lib")
#pragma comment(lib,"cxcore.lib")
#pragma comment(lib,"highgui.lib")
using namespace std;
/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;


int _tmain(int argc, char* argv[])
{
        //Create a new window.
        cvNamedWindow("My Window", CV_WINDOW_AUTOSIZE);
        
        //Create a new movie capture object.
        CvCapture *input;
        
        //Assign the movie to capture.
        //inputMovie = cvCaptureFromAVI("vinoth.avi");
        
        //char *fileName = "C:\\optical_flow_input.avi";
        //char *fileName = "D:\\Profile\\AVI\\cardriving.wmv";
        input = cvCaptureFromCAM(0);
        if (!input)
        {
              //"Can't open file" 
        }
           
        //Size of the image.
        CvSize imgSize;
        imgSize.width = 320;
        imgSize.height = 240;
        
        //Images to use in the program.
        IplImage* greyImage = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);
        IplImage* colourImage;
        IplImage* movingAverage = cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
        IplImage* difference;
        IplImage* temp;
        IplImage* motionHistory = cvCreateImage( imgSize, IPL_DEPTH_8U, 3);
        
        //Rectangle to use to put around the people.
        CvRect bndRect = cvRect(0,0,0,0);
        
        //Points for the edges of the rectangle.
        CvPoint pt1, pt2;
        
        //Create a font object.
        CvFont font;
        
        
       
        //Capture the movie frame by frame.
        int prevX = 0;
        int numPeople = 0;
        
        //Buffer to save the number of people when converting the integer
        //to a string.
        char wow[65];
        
        //The midpoint X position of the rectangle surrounding the moving objects.
        int avgX = 0;
        
        //Indicates whether this is the first time in the loop of frames.
        bool first = true;
        
        //Indicates the contour which was closest to the left boundary before the object
        //entered the region between the buildings.
        int closestToLeft = 0;
        //Same as above, but for the right.
        int closestToRight = 320;
        
        //Keep processing frames...
        for(;;)
        {
                //Get a frame from the input video.
                colourImage = cvQueryFrame(input);
                
                //If there are no more frames, jump out of the for.
               // if( !colourImage )
                //{
                    //    break;
                //}
                
                //If this is the first time, initialize the images.
                if(first)
                {
                        difference = cvCloneImage(colourImage);
                        temp = cvCloneImage(colourImage);
                        cvConvertScale(colourImage, movingAverage, 1.0, 0.0);
                        first = false;
                }
                //else, make a running average of the motion.
                else
                {
                        cvRunningAvg(colourImage, movingAverage, 0.020, NULL);
                }
                
                //Convert the scale of the moving average.
                cvConvertScale(movingAverage,temp, 1.0, 0.0);
                
                //Minus the current frame from the moving average.
                cvAbsDiff(colourImage,temp,difference);
                
                //Convert the image to grayscale.
                cvCvtColor(difference,greyImage,CV_RGB2GRAY);
                
                //Convert the image to black and white.
                cvThreshold(greyImage, greyImage, 90, 255, CV_THRESH_BINARY);
                
                //Dilate and erode to get people blobs
                cvDilate(greyImage, greyImage, 0, 18);
                cvErode(greyImage, greyImage, 0, 10);
                
                //Find the contours of the moving images in the frame.
                CvMemStorage* storage = cvCreateMemStorage(0);
                CvSeq* contour = 0;
                cvFindContours( greyImage, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
                
                //Process each moving contour in the current frame...
                for( ; contour != 0; contour = contour->h_next )
                {
                        //Get a bounding rectangle around the moving object.
                        bndRect = cvBoundingRect(contour, 0);
                        
                        pt1.x = bndRect.x;
                        pt1.y = bndRect.y;
                        pt2.x = bndRect.x + bndRect.width;
                        pt2.y = bndRect.y + bndRect.height;
                        
                        //Get an average X position of the moving contour.
                        avgX = (pt1.x + pt2.x) / 2;
                     /////////////////////////////////////////////////
					  if (1.5*(pt2.x-pt1.x)< (pt2.y-pt1.y))
                      {
					  cvRectangle(colourImage, pt1, pt2, CV_RGB(0,255,0), 8);
				     	////////////////////////////////////////////////////
						  //八祸等 荤阿屈吝 吝埃何盒狼 10x10 农扁狼 拿矾  
                          int centerX=(pt1.x+pt2.x)/2;
						  int centerY=(pt1.y+pt2.y)/2;	  
							  
						  int i, j;
                          unsigned char r, g, b;

                          double var_R=0;
                          double var_G=0;
                          double var_B=0;
                          //double del_R, del_G, del_B;
                          //int cnt =0;

                          for(i=centerY-5; i<centerY+5; i++){
                          for(j=centerX-5; j<centerX+5; j+=temp->nChannels){

                          b = temp->imageData[i * temp->widthStep + j + 0];//0,1,2 channel
                          g = temp->imageData[i * temp->widthStep + j + 1];
                          r = temp->imageData[i * temp->widthStep + j + 2];
    
                          var_R =(int)(255* (double)r/255);
                          var_G =(int)(255* (double)g/255);//(double)g/255;
                          var_B =(int)(255* (double)b/255);//(double)b/255;
						  
               
						  }}	
						 cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.6, 0.6, 0, 3);
                         cvPutText(colourImage, _itoa(var_R, wow, 10), cvPoint(pt1.x,pt1.y), &font, cvScalar(0, 0, 300));	
							
						///////////////////////////////////////////////////

                      }


                                
                                //Draw the bounding rectangle around the moving object.
                            else
							{
						      ;	
							}
                }        
                        //If the current object is closer to the left boundary but still not across
                        //it, then change the closest to the left counter to this value.
                      /*  if(avgX > closestToLeft && avgX <= 90)
                        {
                                closestToLeft = avgX;
                        }
                        
                        //If the current object is closer to the right boundary but still not across
                        //it, then change the closest to the right counter to this value.
                        if(avgX < closestToRight && avgX >= 250)
                        {
                                closestToRight = avgX;
                        }
                        
                        //Save the current X value to use as the previous in the next iteration.
                        prevX = avgX;   
        }
                */
                
                //Write the number of people counted at the top of the output frame.
                
                
                //Show the frame.
                cvShowImage("My Window", colourImage);

                //Wait for the user to see it.
                cvWaitKey(10);

                //Write the frame to the output movie.
                //cvWriteFrame(outputMovie, colourImage);
         }
 
         // Destroy the image, movies, and window.
        cvReleaseImage(&temp);
        cvReleaseImage(&difference);
        cvReleaseImage(&greyImage);
        cvReleaseImage(&movingAverage);
        cvDestroyWindow("My Window");
 
        cvReleaseCapture(&input);
        //cvReleaseVideoWriter(&outputMovie);
 
 
        return 0;
 
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -