tameraslan

BScThesis - panopticon.h

Dec 19th, 2011
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 10.50 KB | None | 0 0
  1. #ifndef PANOPTICON_H
  2. #define PANOPTICON_H
  3.  
  4. #endif // PANOPTICON_H
  5.  
  6.  
  7. #include <cv.h>
  8. #include <cxcore.h>
  9. #include <highgui.h>
  10. #include <QtGui/QApplication>
  11. #include <fstream>
  12. #include <stdio.h>
  13. #include <math.h>
  14. #include <sys/stat.h>
  15. using namespace std;
  16.  
  17. //global parameters
  18. const int bgLength=100;
  19. const int bgThreshold=8;
  20. const int MaxBlobNum=6;
  21. bool has_BG_Model=true;
  22.  
  23.  
  24. // Dir of video file
  25. #define VideoDir "/seq1.avi"
  26.  
  27.  
  28.  
  29. int compare(const void *a,const void *b){
  30.  
  31.     // Returns -1 if elem1 < elem2
  32.     //          0 if elem1 == elem2
  33.     //         +1 if elem1 > elem2
  34.  
  35.  
  36.     if (*(double*)a < *(double*)b) {
  37.         return -1;
  38.     } else if (*(double*)a > *(double*)b) {
  39.         return +1;
  40.     }
  41.     return 0;
  42.  
  43. }
  44.  
  45. double FindMedian(IplImage* data)
  46. {
  47.     int w = data->width, h=data->height;
  48.     double *arr;
  49.     int size;
  50.  
  51.  
  52.     arr = new double[w*h];
  53.     if (w==1 || h==1)
  54.     {
  55.         size = (w > h ? w : h );
  56.         for (int i=0;i<size;i++)
  57.         {
  58.             arr[i]=cvGet1D(data,i).val[0];
  59.         }
  60.     }
  61.     else
  62.     {
  63.         size =(w * h );
  64.         for(int row=0;row<h;row++)
  65.             for(int col=0;col<w;col++)
  66.             {
  67.  
  68.             arr[row*w + col] = cvGetReal2D(data,row,col);
  69.         }
  70.     }
  71.  
  72.  
  73.     qsort(arr,size,sizeof(double),compare); // using qsort for sorting or u can see bubble sort, selection sort...
  74.     //for (int i=0;i<size;i++) cout<<arr[i]<<endl;
  75.     int middle = size/2;
  76.     double average;
  77.     if (size%2==0) average = static_cast<double>(arr[middle-1]+arr[middle])/2;
  78.     else average = static_cast<double>(arr[middle]);
  79.     return average;
  80.  
  81. }
  82.  
  83. // take the frame array, fill pixelwise vectors, calculate median and stddev, return median & stddev matrices
  84. void bgInitStats(IplImage * StddevFrame, IplImage * BGFrameArray[], IplImage * MedianFrame, IplImage * bgmFrame, IplImage * bgnFrame, IplImage * bgdFrame)
  85. {
  86.  
  87.     CvScalar  stddev;
  88.     CvScalar  median;
  89.     CvScalar  mean;
  90.  
  91.     IplImage* temp=cvCreateImage(cvSize(bgLength,1),BGFrameArray[0]->depth,1);
  92.     IplImage* stemp=cvCreateImage(cvSize(bgLength,1),BGFrameArray[0]->depth,1);
  93.     //temp: vector store values taken in time for pixelwise calculations
  94.     //stemp: stationary degerleri tutmak icin
  95.  
  96.     //pixelwise calculations: median, stdDev,  (min,max,max diff) matrices
  97.     for (int row=0;row<BGFrameArray[0]->height ;row++)
  98.         for(int col =0; col<BGFrameArray[0]->width;col++)
  99.         {
  100.  
  101.         //put pixel values in vector,  BGframe array => temp
  102.         for(int n=0; n<bgLength;n++)
  103.         {
  104.             cvSet1D(temp,n,cvGet2D(BGFrameArray[n],row,col));
  105.         }
  106.  
  107.  
  108.         //median,stddev to be calculated here
  109.         {
  110.             cvAvgSdv(temp,&mean,&stddev);
  111.             median.val[0] = FindMedian(temp);
  112.             cvSet2D(StddevFrame,row,col,stddev);
  113.             cvSet2D(MedianFrame,row,col,median);
  114.         }
  115.  
  116.  
  117.         //varible declarations (for stationary pixel test and maxdiff)
  118.         int bgCounter =0;
  119.         CvScalar sPix;
  120.         CvScalar Maxdiff= cvScalar(0);
  121.         int prevVal=0;
  122.         int diff=0;
  123.  
  124.  
  125.         //detection of stationary pixels
  126.         for(int n=0; n<bgLength;n++)
  127.         {
  128.             sPix=cvGet1D(temp,n);
  129.  
  130.             if(abs(sPix.val[0]-median.val[0])<(2*stddev.val[0]))
  131.             {
  132.                 //case for stationary pixels
  133.                 cvSet1D(stemp,bgCounter,sPix);
  134.                 bgCounter++;
  135.             }
  136.         }
  137.  
  138.  
  139.         //tranfer the stationary pixel values to a smaller vector
  140.         //min, max, dif calculated from the stemp2 vector
  141.         IplImage* stemp2=cvCreateImage(cvSize(bgCounter,1),stemp->depth,stemp->nChannels);
  142.         cvSetImageROI(stemp,cvRect(0,0,bgCounter,1));
  143.         cvCopy(stemp,stemp2);
  144.         cvResetImageROI(stemp);
  145.  
  146.         //find max diff
  147.         for (int n=0;n<bgCounter;n++)
  148.         {
  149.             sPix=cvGet1D(stemp2,n);
  150.  
  151.             if(n==0)
  152.                 prevVal=sPix.val[0];
  153.             else
  154.             {
  155.                 diff=abs(sPix.val[0]-prevVal);
  156.  
  157.                 if(diff>Maxdiff.val[0])
  158.                     Maxdiff.val[0]=diff;
  159.  
  160.                 prevVal=sPix.val[0];
  161.             }
  162.  
  163.         }
  164.  
  165.         //find min, max
  166.         double min, max;
  167.         CvPoint min_loc, max_loc;
  168.         cvMinMaxLoc(stemp2,&min,&max,&min_loc,&max_loc);
  169.  
  170.  
  171.         CvScalar smin= cvScalar(min);
  172.         CvScalar smax= cvScalar(max);
  173.  
  174.  
  175.  
  176.         // record min, max, dif to their own matrices of (row x column)
  177.         {
  178.             //m(x) - max frame
  179.             cvSet2D(bgmFrame,row,col,smax);
  180.  
  181.             //n(x) - min frame
  182.             cvSet2D(bgnFrame,row,col,smin);
  183.  
  184.             //d(x) - abs max difference
  185.             cvSet2D(bgdFrame,row,col,Maxdiff);
  186.             //cvSet1D(bgdFrame,row*(BGFrameArray[0]->height)+col,Maxdiff);
  187.         }
  188.  
  189.  
  190.     }
  191.  
  192.  
  193.     //cvReleaseImage(&temp);
  194.  
  195. }
  196.  
  197.  
  198.  
  199. //connected component parameters
  200. /*////////////////////////////////////////////////////////////////
  201. // void find_connected_components(IplImage *mask, int poly1_hull0,
  202. //                            float perimScale, int *num,
  203. //                            CvRect *bbs, CvPoint *centers)
  204. // This cleans up the foreground segmentation mask derived from calls
  205. // to backgroundDiff
  206. //
  207. // mask          Is a grayscale (8-bit depth) “raw” mask image that
  208. //               will be cleaned up
  209. //
  210. // OPTIONAL PARAMETERS:
  211. // poly1_hull0   If set, approximate connected component by
  212. //               (DEFAULT) polygon, or else convex hull (0)
  213. // perimScale    Len = image (width+height)/perimScale. If contour
  214. //               len < this, delete that contour (DEFAULT: 4)
  215. // num           Maximum number of rectangles and/or centers to
  216. //               return; on return, will contain number filled
  217. //               (DEFAULT: NULL)
  218. // bbs          Pointer to bounding box rectangle vector of
  219. //              length num. (DEFAULT SETTING: NULL)
  220. // centers      Pointer to contour centers vector of length
  221. //              num (DEFAULT: NULL)
  222. */
  223. void find_connected_components( IplImage* mask, int poly1_hull0 = 1, float perimScale = 4, int* num = NULL, CvRect* bbs = NULL, CvPoint* centers = NULL )
  224. {
  225.     // For connected components:
  226.     // Approx.threshold - the bigger it is, the simpler is the boundary
  227.     //
  228. #define CVCONTOUR_APPROX_LEVEL 2
  229.     // How many iterations of erosion and/or dilation there should be
  230.     //
  231. #define CVCLOSE_ITR 1
  232.     static CvMemStorage* mem_storage = NULL;
  233.     static CvSeq* contours = NULL;
  234.     //CLEAN UP RAW MASK
  235.     //
  236.     cvMorphologyEx( mask, mask, 0, 0, CV_MOP_OPEN, CVCLOSE_ITR );
  237.     cvMorphologyEx( mask, mask, 0, 0, CV_MOP_CLOSE, CVCLOSE_ITR );
  238.     //FIND CONTOURS AROUND ONLY BIGGER REGIONS
  239.     //
  240.     //cvNamedWindow("After Morphology",CV_WINDOW_AUTOSIZE);
  241.     //cvShowImage("After Morphology",mask);
  242.     //cvWaitKey();
  243.     //cvDestroyWindow("After Morphology");
  244.     if( mem_storage==NULL ) {
  245.         mem_storage = cvCreateMemStorage(0);
  246.     } else {
  247.         cvClearMemStorage(mem_storage);
  248.     }
  249.     CvContourScanner scanner = cvStartFindContours(mask,mem_storage,sizeof(CvContour),CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);
  250.     CvSeq* c;
  251.     int numCont = 0;
  252.     while( (c = cvFindNextContour( scanner )) != NULL ) {
  253.         double len = cvContourPerimeter( c );
  254.         // calculate perimeter len threshold:
  255.         //
  256.         double q = (mask->height + mask->width)/perimScale;
  257.         //Get rid of blob if its perimeter is too small:
  258.         //
  259.         if( len < q ) {
  260.             cvSubstituteContour( scanner, NULL );
  261.         } else {
  262.             // Smooth its edges if its large enough
  263.             //
  264.             CvSeq* c_new;
  265.             if( poly1_hull0 ) {
  266.                 // Polygonal approximation
  267.                 //
  268.                 c_new = cvApproxPoly(c,sizeof(CvContour),mem_storage,CV_POLY_APPROX_DP,CVCONTOUR_APPROX_LEVEL,0);
  269.             } else {
  270.                 // Convex Hull of the segmentation
  271.                 //
  272.                 c_new = cvConvexHull2(c,mem_storage,CV_CLOCKWISE,1);
  273.             }
  274.             cvSubstituteContour( scanner, c_new );
  275.             numCont++;
  276.         }
  277.     }
  278.     contours = cvEndFindContours( &scanner );
  279.     // Just some convenience variables
  280.     const CvScalar CVX_WHITE = CV_RGB(0xff,0xff,0xff);
  281.     const CvScalar CVX_BLACK = CV_RGB(0x00,0x00,0x00);
  282.     // PAINT THE FOUND REGIONS BACK INTO THE IMAGE
  283.     //
  284.     cvZero( mask );
  285.     IplImage *maskTemp;
  286.     // CALC CENTER OF MASS AND/OR BOUNDING RECTANGLES
  287.     //
  288.     if(num != NULL) {
  289.         //User wants to collect statistics
  290.         //
  291.         int N = *num, numFilled = 0, i=0;
  292.         CvMoments moments;
  293.         double M00, M01, M10;
  294.         maskTemp = cvCloneImage(mask);
  295.         for(i=0, c=contours; c != NULL; c = c->h_next,i++ ) {
  296.             if(i < N) {
  297.                 // Only process up to *num of them
  298.                 //
  299.                 cvDrawContours(maskTemp,c,CVX_WHITE,CVX_WHITE,-1,CV_FILLED,8);
  300.                 // Find the center of each contour
  301.                 //
  302.                 if(centers != NULL) {
  303.                     cvMoments(maskTemp,&moments,1);
  304.                     M00 = cvGetSpatialMoment(&moments,0,0);
  305.                     M10 = cvGetSpatialMoment(&moments,1,0);
  306.                     M01 = cvGetSpatialMoment(&moments,0,1);
  307.                     centers[i].x = (int)(M10/M00);
  308.                     centers[i].y = (int)(M01/M00);
  309.                 }
  310.                 //Bounding rectangles around blobs
  311.                 //
  312.                 if(bbs != NULL) {
  313.                     bbs[i] = cvBoundingRect(c);
  314.                 }
  315.                 cvZero(maskTemp);
  316.                 numFilled++;
  317.             }
  318.             // Draw filled contours into mask
  319.             //
  320.             cvDrawContours(mask,c,CVX_WHITE,CVX_WHITE,-1,CV_FILLED,8);
  321.         } //end looping over contours
  322.         *num = numFilled;
  323.         cvReleaseImage( &maskTemp);
  324.     }
  325.     // ELSE JUST DRAW PROCESSED CONTOURS INTO THE MASK
  326.     //
  327.     else {
  328.         // The user doesn’t want statistics, just draw the contours
  329.         //
  330.         for( c=contours; c != NULL; c = c->h_next ) {
  331.             cvDrawContours(mask,c,CVX_WHITE,CVX_BLACK,-1,CV_FILLED,8);
  332.         }
  333.     }
  334.  
  335. }
  336.  
  337. void PrintMatrix(CvMat* Mat)
  338. {
  339.    CvSize Size = cvGetSize(Mat);
  340.    for (int i = 0;i<Size.height;i++)
  341.    {
  342.        for(int j = 0;j<Size.width;j++)
  343.        {
  344.            CvScalar El = cvGet2D(Mat, i, j);
  345.            printf("%f |" , El.val[0]);
  346.            //printf("%f |" , cvmGet(Mat, i, j));
  347.        }
  348.        printf("||\n");
  349.    }
  350. }
Advertisement
Add Comment
Please, Sign In to add comment