Advertisement
rajhlinux

Untitled

Sep 9th, 2022 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.09 KB | Software | 0 0
  1. // How to run code after c++ compilation:
  2. // ./ufacedetect --cascade=/home/user/opencv/data/haarcascades/haarcascade_frontalface_alt.xml /dev/video5 --scale=1.3
  3.  
  4. #include "opencv2/objdetect.hpp"
  5. #include "opencv2/highgui.hpp"
  6. #include "opencv2/imgproc.hpp"
  7. #include "opencv2/core/ocl.hpp"
  8. #include <iostream>
  9.  
  10. using namespace std;
  11. using namespace cv;
  12.  
  13. static void help()
  14. {
  15.     cout << "\nThis program demonstrates the cascade recognizer. Now you can use Haar or LBP features.\n"
  16.             "This classifier can recognize many kinds of rigid objects, once the appropriate classifier is trained.\n"
  17.             "It's most known use is for faces.\n"
  18.             "Usage:\n"
  19.             "./ufacedetect [--cascade=<cascade_path> this is the primary trained classifier such as frontal face]\n"
  20.                "   [--nested-cascade[=nested_cascade_path this an optional secondary classifier such as eyes]]\n"
  21.                "   [--scale=<image scale greater or equal to 1, try 1.3 for example>]\n"
  22.                "   [--try-flip]\n"
  23.                "   [filename|camera_index]\n\n"
  24.             "see facedetect.cmd for one call:\n"
  25.             "./ufacedetect --cascade=\"../../data/haarcascades/haarcascade_frontalface_alt.xml\" --nested-cascade=\"../../data/haarcascades/haarcascade_eye_tree_eyeglasses.xml\" --scale=1.3\n\n"
  26.             "During execution:\n\tHit any key to quit.\n"
  27.             "\tUsing OpenCV version " << CV_VERSION << "\n" << endl;
  28. }
  29.  
  30. void detectAndDraw( UMat& img, Mat& canvas, CascadeClassifier& cascade,
  31.                     CascadeClassifier& nestedCascade,
  32.                     double scale, bool tryflip );
  33.  
  34. int main( int argc, const char** argv )
  35. {
  36.     ocl::setUseOpenCL(true);
  37.  
  38.     VideoCapture capture;
  39.     UMat frame, image;
  40.     Mat canvas;
  41.  
  42.     string inputName;
  43.     bool tryflip;
  44.  
  45.     CascadeClassifier cascade, nestedCascade;
  46.     double scale;
  47.  
  48.     cv::CommandLineParser parser(argc, argv,
  49.         "{cascade|data/haarcascades/haarcascade_frontalface_alt.xml|}"
  50.         "{nested-cascade|data/haarcascades/haarcascade_eye_tree_eyeglasses.xml|}"
  51.         "{help h ||}{scale|1|}{try-flip||}{@filename||}"
  52.     );
  53.     if (parser.has("help"))
  54.     {
  55.         help();
  56.         return 0;
  57.     }
  58.     string cascadeName = samples::findFile(parser.get<string>("cascade"));
  59.     string nestedCascadeName = samples::findFileOrKeep(parser.get<string>("nested-cascade"));
  60.     scale = parser.get<double>("scale");
  61.     tryflip = parser.has("try-flip");
  62.     inputName = parser.get<string>("@filename");
  63.     if ( !parser.check())
  64.     {
  65.         parser.printErrors();
  66.         help();
  67.         return -1;
  68.     }
  69.  
  70.     if ( !nestedCascade.load( nestedCascadeName ) )
  71.         cerr << "WARNING: Could not load classifier cascade for nested objects: " << nestedCascadeName << endl;
  72.     if( !cascade.load( cascadeName ) )
  73.     {
  74.         cerr << "ERROR: Could not load classifier cascade: " << cascadeName << endl;
  75.         help();
  76.         return -1;
  77.     }
  78.  
  79.     cout << "old cascade: " << (cascade.isOldFormatCascade() ? "TRUE" : "FALSE") << endl;
  80.  
  81.     if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) )
  82.     {
  83.         int camera = inputName.empty() ? 0 : inputName[0] - '0';
  84.         if(!capture.open(camera))
  85.             cout << "Capture from camera #" <<  camera << " didn't work" << endl;
  86.     }
  87.     else
  88.     {
  89.         inputName = samples::findFileOrKeep(inputName);
  90.         imread(inputName, IMREAD_COLOR).copyTo(image);
  91.         if( image.empty() )
  92.         {
  93.             if(!capture.open( inputName ))
  94.                 cout << "Could not read " << inputName << endl;
  95.         }
  96.     }
  97.  
  98.     if( capture.isOpened() )
  99.     {
  100.         cout << "Video capturing has been started ..." << endl;
  101.         for(;;)
  102.         {
  103.             capture >> frame;
  104.             if( frame.empty() )
  105.                 break;
  106.  
  107.             detectAndDraw( frame, canvas, cascade, nestedCascade, scale, tryflip );
  108.  
  109.             char c = (char)waitKey(10);
  110.             if( c == 27 || c == 'q' || c == 'Q' )
  111.                 break;
  112.         }
  113.     }
  114.     else
  115.     {
  116.         cout << "Detecting face(s) in " << inputName << endl;
  117.         if( !image.empty() )
  118.         {
  119.             detectAndDraw( image, canvas, cascade, nestedCascade, scale, tryflip );
  120.             waitKey(0);
  121.         }
  122.         else if( !inputName.empty() )
  123.         {
  124.             /* assume it is a text file containing the
  125.             list of the image filenames to be processed - one per line */
  126.             FILE* f = fopen( inputName.c_str(), "rt" );
  127.             if( f )
  128.             {
  129.                 char buf[1000+1];
  130.                 while( fgets( buf, 1000, f ) )
  131.                 {
  132.                     int len = (int)strlen(buf);
  133.                     while( len > 0 && isspace(buf[len-1]) )
  134.                         len--;
  135.                     buf[len] = '\0';
  136.                     cout << "file " << buf << endl;
  137.                     imread(samples::findFile(buf), IMREAD_COLOR).copyTo(image);
  138.                     if( !image.empty() )
  139.                     {
  140.                         detectAndDraw( image, canvas, cascade, nestedCascade, scale, tryflip );
  141.                         char c = (char)waitKey(0);
  142.                         if( c == 27 || c == 'q' || c == 'Q' )
  143.                             break;
  144.                     }
  145.                     else
  146.                     {
  147.                         cerr << "Aw snap, couldn't read image " << buf << endl;
  148.                     }
  149.                 }
  150.                 fclose(f);
  151.             }
  152.         }
  153.     }
  154.  
  155.     return 0;
  156. }
  157.  
  158. void detectAndDraw( UMat& img, Mat& canvas, CascadeClassifier& cascade,
  159.                     CascadeClassifier& nestedCascade,
  160.                     double scale, bool tryflip )
  161. {
  162.     double t = 0;
  163.     vector<Rect> faces, faces2;
  164.     const static Scalar colors[] =
  165.     {
  166.         Scalar(255,0,0),
  167.         Scalar(255,128,0),
  168.         Scalar(255,255,0),
  169.         Scalar(0,255,0),
  170.         Scalar(0,128,255),
  171.         Scalar(0,255,255),
  172.         Scalar(0,0,255),
  173.         Scalar(255,0,255)
  174.     };
  175.     static UMat gray, smallImg;
  176.  
  177.     t = (double)getTickCount();
  178.  
  179.     cvtColor( img, gray, COLOR_BGR2GRAY );
  180.     double fx = 1 / scale;
  181.     resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR_EXACT );
  182.     equalizeHist( smallImg, smallImg );
  183.  
  184.     cascade.detectMultiScale( smallImg, faces,
  185.         1.1, 3, 0
  186.         //|CASCADE_FIND_BIGGEST_OBJECT
  187.         //|CASCADE_DO_ROUGH_SEARCH
  188.         |CASCADE_SCALE_IMAGE,
  189.         Size(30, 30) );
  190.     if( tryflip )
  191.     {
  192.         flip(smallImg, smallImg, 1);
  193.         cascade.detectMultiScale( smallImg, faces2,
  194.                                  1.1, 2, 0
  195.                                  //|CASCADE_FIND_BIGGEST_OBJECT
  196.                                  //|CASCADE_DO_ROUGH_SEARCH
  197.                                  |CASCADE_SCALE_IMAGE,
  198.                                  Size(30, 30) );
  199.         for( vector<Rect>::const_iterator r = faces2.begin(); r != faces2.end(); ++r )
  200.         {
  201.             faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height));
  202.         }
  203.     }
  204.     t = (double)getTickCount() - t;
  205.     img.copyTo(canvas);
  206.  
  207.     double fps = getTickFrequency()/t;
  208.     static double avgfps = 0;
  209.     static int nframes = 0;
  210.     nframes++;
  211.     double alpha = nframes > 50 ? 0.01 : 1./nframes;
  212.     avgfps = avgfps*(1-alpha) + fps*alpha;
  213.  
  214.     putText(canvas, cv::format("OpenCL: %s, fps: %.1f", ocl::useOpenCL() ? "ON" : "OFF", avgfps), Point(50, 30),
  215.             FONT_HERSHEY_SIMPLEX, 0.8, Scalar(0,255,0), 2);
  216.  
  217.     for ( size_t i = 0; i < faces.size(); i++ )
  218.     {
  219.         Rect r = faces[i];
  220.         vector<Rect> nestedObjects;
  221.         Point center;
  222.         Scalar color = colors[i%8];
  223.         int radius;
  224.  
  225.         double aspect_ratio = (double)r.width/r.height;
  226.         if( 0.75 < aspect_ratio && aspect_ratio < 1.3 )
  227.         {
  228.             center.x = cvRound((r.x + r.width*0.5)*scale);
  229.             center.y = cvRound((r.y + r.height*0.5)*scale);
  230.             radius = cvRound((r.width + r.height)*0.25*scale);
  231.             circle( canvas, center, radius, color, 3, 8, 0 );
  232.         }
  233.         else
  234.             rectangle( canvas, Point(cvRound(r.x*scale), cvRound(r.y*scale)),
  235.                        Point(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)),
  236.                        color, 3, 8, 0);
  237.         if( nestedCascade.empty() )
  238.             continue;
  239.         UMat smallImgROI = smallImg(r);
  240.         nestedCascade.detectMultiScale( smallImgROI, nestedObjects,
  241.             1.1, 2, 0
  242.             //|CASCADE_FIND_BIGGEST_OBJECT
  243.             //|CASCADE_DO_ROUGH_SEARCH
  244.             //|CASCADE_DO_CANNY_PRUNING
  245.             |CASCADE_SCALE_IMAGE,
  246.             Size(30, 30) );
  247.  
  248.         for ( size_t j = 0; j < nestedObjects.size(); j++ )
  249.         {
  250.             Rect nr = nestedObjects[j];
  251.             center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale);
  252.             center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale);
  253.             radius = cvRound((nr.width + nr.height)*0.25*scale);
  254.             circle( canvas, center, radius, color, 3, 8, 0 );
  255.         }
  256.     }
  257.     imshow( "result", canvas );
  258. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement