Advertisement
szarlotkas

Untitled

May 30th, 2015
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.69 KB | None | 0 0
  1. //Written by  Kyle Hounslow 2013
  2.  
  3. // modified by: Ahmad Kaifi, Hassan Althobaiti
  4.  
  5. //Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software")
  6. //, to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  7. //and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. //The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  9. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  10. //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11. //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  12. //IN THE SOFTWARE.
  13.  
  14. #include <sstream>
  15. #include <string>
  16. #include <iostream>
  17. #include <vector>
  18.  
  19. #include "Object.h"
  20.  
  21.  
  22. //initial min and max HSV filter values.
  23. //these will be changed using trackbars
  24. int H_MIN = 0;
  25. int H_MAX = 256;
  26. int S_MIN = 0;
  27. int S_MAX = 256;
  28. int V_MIN = 0;
  29. int V_MAX = 256;
  30. //default capture width and height
  31. const int FRAME_WIDTH = 640;
  32. const int FRAME_HEIGHT = 480;
  33. //max number of objects to be detected in frame
  34. const int MAX_NUM_OBJECTS=50;
  35. //minimum and maximum object area
  36. const int MIN_OBJECT_AREA = 20*20;
  37. const int MAX_OBJECT_AREA = FRAME_HEIGHT*FRAME_WIDTH/1.5;
  38. //names that will appear at the top of each window
  39. const string windowName = "Original Image";
  40. const string windowName1 = "HSV Image";
  41. const string windowName2 = "Thresholded Image";
  42. const string windowName3 = "After Morphological Operations";
  43. const string trackbarWindowName = "Trackbars";
  44.  
  45. //The following for canny edge detec
  46. Mat dst, detected_edges;
  47. Mat src, src_gray;
  48. int edgeThresh = 1;
  49. int lowThreshold;
  50. int const max_lowThreshold = 100;
  51. int ratio = 3;
  52. int kernel_size = 3;
  53. char* window_name = "Edge Map";
  54.  
  55. void on_trackbar( int, void* )
  56. {//This function gets called whenever a
  57.     // trackbar position is changed
  58.  
  59. }
  60.  
  61. string intToString(int number){
  62.  
  63.     std::stringstream ss;
  64.     ss << number;
  65.     return ss.str();
  66. }
  67.  
  68. void createTrackbars(){
  69.     //create window for trackbars
  70.     namedWindow(trackbarWindowName,0);
  71.     //create memory to store trackbar name on window
  72.     char TrackbarName[50];
  73.     sprintf( TrackbarName, "H_MIN", H_MIN);
  74.     sprintf( TrackbarName, "H_MAX", H_MAX);
  75.     sprintf( TrackbarName, "S_MIN", S_MIN);
  76.     sprintf( TrackbarName, "S_MAX", S_MAX);
  77.     sprintf( TrackbarName, "V_MIN", V_MIN);
  78.     sprintf( TrackbarName, "V_MAX", V_MAX);
  79.     //create trackbars and insert them into window
  80.     //3 parameters are: the address of the variable that is changing when the trackbar is moved(eg.H_LOW),
  81.     //the max value the trackbar can move (eg. H_HIGH),
  82.     //and the function that is called whenever the trackbar is moved(eg. on_trackbar)
  83.     //                                  ---->    ---->     ---->      
  84.     createTrackbar( "H_MIN", trackbarWindowName, &H_MIN, H_MAX, on_trackbar );
  85.     createTrackbar( "H_MAX", trackbarWindowName, &H_MAX, H_MAX, on_trackbar );
  86.     createTrackbar( "S_MIN", trackbarWindowName, &S_MIN, S_MAX, on_trackbar );
  87.     createTrackbar( "S_MAX", trackbarWindowName, &S_MAX, S_MAX, on_trackbar );
  88.     createTrackbar( "V_MIN", trackbarWindowName, &V_MIN, V_MAX, on_trackbar );
  89.     createTrackbar( "V_MAX", trackbarWindowName, &V_MAX, V_MAX, on_trackbar );
  90. }
  91.  
  92. void drawObject(vector<Object> theObjects,Mat &frame, Mat &temp, vector< vector<Point> > contours, vector<Vec4i> hierarchy){
  93.  
  94.     for(int i =0; i<theObjects.size(); i++){
  95.     cv::drawContours(frame,contours,i,theObjects.at(i).getColor(),3,8,hierarchy);
  96.     cv::circle(frame,cv::Point(theObjects.at(i).getXPos(),theObjects.at(i).getYPos()),5,theObjects.at(i).getColor());
  97.     cv::putText(frame,intToString(theObjects.at(i).getXPos())+ " , " + intToString(theObjects.at(i).getYPos()),cv::Point(theObjects.at(i).getXPos(),theObjects.at(i).getYPos()+20),1,1,theObjects.at(i).getColor());
  98.     cv::putText(frame,theObjects.at(i).getType(),cv::Point(theObjects.at(i).getXPos(),theObjects.at(i).getYPos()-20),1,2,theObjects.at(i).getColor());
  99.     }
  100. }
  101.  
  102. void morphOps(Mat &thresh){
  103.  
  104.     //create structuring element that will be used to "dilate" and "erode" image.
  105.     //the element chosen here is a 3px by 3px rectangle
  106.     Mat erodeElement = getStructuringElement( MORPH_RECT,Size(3,3));
  107.     //dilate with larger element so make sure object is nicely visible
  108.     Mat dilateElement = getStructuringElement( MORPH_RECT,Size(8,8));
  109.  
  110.     erode(thresh,thresh,erodeElement);
  111.     erode(thresh,thresh,erodeElement);
  112.  
  113.     dilate(thresh,thresh,dilateElement);
  114.     dilate(thresh,thresh,dilateElement);
  115. }
  116.  
  117. void trackFilteredObject(Object theObject,Mat threshold,Mat HSV, Mat &cameraFeed){
  118.  
  119.     vector <Object> objects;
  120.     Mat temp;
  121.     threshold.copyTo(temp);
  122.     //these two vectors needed for output of findContours
  123.     vector< vector<Point> > contours;
  124.     vector<Vec4i> hierarchy;
  125.     //find contours of filtered image using openCV findContours function
  126.     findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE );
  127.     //use moments method to find our filtered object
  128.     double refArea = 0;
  129.     bool objectFound = false;
  130.     if (hierarchy.size() > 0) {
  131.         int numObjects = hierarchy.size();
  132.         //if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter
  133.         if(numObjects<MAX_NUM_OBJECTS){
  134.             for (int index = 0; index >= 0; index = hierarchy[index][0]) {
  135.  
  136.                 Moments moment = moments((cv::Mat)contours[index]);
  137.                 double area = moment.m00;
  138.  
  139.         //if the area is less than 20 px by 20px then it is probably just noise
  140.         //if the area is the same as the 3/2 of the image size, probably just a bad filter
  141.         //we only want the object with the largest area so we safe a reference area each
  142.                 //iteration and compare it to the area in the next iteration.
  143.                 if(area>MIN_OBJECT_AREA){
  144.  
  145.                     Object object;
  146.                    
  147.                     object.setXPos(moment.m10/area);
  148.                     object.setYPos(moment.m01/area);
  149.                     object.setType(theObject.getType());
  150.                     object.setColor(theObject.getColor());
  151.  
  152.                     objects.push_back(object);
  153.  
  154.                     objectFound = true;
  155.  
  156.                 }else objectFound = false;
  157.             }
  158.             //let user know you found an object
  159.             if(objectFound ==true){
  160.                 //draw object location on screen
  161.                 drawObject(objects,cameraFeed,temp,contours,hierarchy);}
  162.  
  163.         }else putText(cameraFeed,"TOO MUCH NOISE! ADJUST FILTER",Point(0,50),1,2,Scalar(0,0,255),2);
  164.     }
  165. }
  166.  
  167. Mat trackingOranges(Mat cameraFeed)
  168. {
  169.     //if we would like to calibrate our filter values, set to true.
  170.     bool calibrationMode = true;
  171.    
  172.     //Matrix to store each frame of the webcam feed
  173.     Mat threshold;
  174.     Mat HSV;
  175.  
  176.     if(calibrationMode){
  177.         //create slider bars for HSV filtering
  178.         createTrackbars();
  179.     }
  180.    
  181.     calibrationMode = false;
  182.  
  183.         //convert frame from BGR to HSV colorspace
  184.         //cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);
  185.        
  186.             //create some temp fruit objects so that
  187.             //we can use their member functions/information
  188.             Object orange("orange");
  189.            
  190.             //orange
  191.             cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);
  192.             inRange(HSV,orange.getHSVmin(),orange.getHSVmax(),threshold);
  193.             morphOps(threshold);
  194.             trackFilteredObject(orange,threshold,HSV,cameraFeed);
  195.            
  196.     return cameraFeed ;
  197.  
  198. }
  199.  
  200. int main(int argc, char* argv[])
  201. {
  202.     VideoCapture cap("C:/Users/Dominika/Documents/STUDIA/compvis/FINAL/video-tp2.avi");  // open the video file for reading
  203.  
  204.  
  205.     if ( !cap.isOpened() )   // if not success, exit program
  206.     {
  207.         cout << "Cannot open the video file" << endl;
  208.         return -1;
  209.     }
  210.  
  211.     cap.set(CV_CAP_PROP_POS_MSEC, 3000);  //start the video at 300ms
  212.  
  213.     double fps = cap.get(CV_CAP_PROP_FPS);  //get the frames per seconds of the video
  214.  
  215.     cout << "Frame per seconds : " << fps << endl;
  216.  
  217.     namedWindow("MyVideo",CV_WINDOW_AUTOSIZE);  //create a window called "MyVideo"
  218.  
  219.     while(1)
  220.     {
  221.         //Matrix to store each frame of the cam feed
  222.         Mat frame;
  223.  
  224.         bool bSuccess = cap.read(frame);  // read a new frame from video
  225.  
  226.         if (!bSuccess)  //if not success, break loop
  227.         {
  228.             cout << "Cannot read the frame from video file" << endl;
  229.             break;
  230.         }
  231.  
  232.         // process here!
  233.         imshow("MyVideo", trackingOranges(frame));
  234.  
  235.  
  236.        
  237.         //vc_gray_gaussian_filter(gray,dst);
  238.         //vc_gray_highpass_filter(gray,dst);
  239.  
  240.  
  241.  
  242.  
  243.  
  244.        
  245.         //imshow("Highpass", dst); // highpass video
  246.  
  247.  
  248.         if(waitKey(30) == 27) // wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
  249.         {
  250.             cout << "esc key is pressed by user" << endl;
  251.             break;
  252.         }
  253.     }
  254.  
  255.     return 0;
  256. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement