opencv參考手冊裡面有個 [臉部偵測] 的程式

來源:互聯網
上載者:User

opencv參考手冊裡面有個 [臉部偵測]  的程式:

#include "cv.h"#include "highgui.h"#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>#include <math.h>#include <float.h>#include <limits.h>#include <time.h>#include <ctype.h>#ifdef _EiC#define WIN32#endifstatic CvMemStorage* storage = 0;static CvHaarClassifierCascade* cascade = 0;void detect_and_draw( IplImage* image );const char* cascade_name ="haarcascade_frontalface_alt.xml";/* "haarcascade_profileface.xml";*/int main( int argc, char** argv ){    CvCapture* capture = 0;    IplImage *frame, *frame_copy = 0;    int optlen = strlen("--cascade=");    const char* input_name;    if( argc > 1 && strncmp( argv[1], "--cascade=", optlen ) == 0 )    {        cascade_name = argv[1] + optlen;        input_name = argc > 2 ? argv[2] : 0;    }    else    {        cascade_name = "../../data/haarcascades/haarcascade_frontalface_alt2.xml";        input_name = argc > 1 ? argv[1] : 0;    }    cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );    if( !cascade )    {        fprintf( stderr, "ERROR: Could not load classifier cascade\n" );        fprintf( stderr,        "Usage: facedetect --cascade=\"<cascade_path>\" [filename|camera_index]\n" );        return -1;    }    storage = cvCreateMemStorage(0);    if( !input_name || (isdigit(input_name[0]) && input_name[1] == '\0') )    capture = cvCaptureFromCAM( !input_name ? 0 : input_name[0] - '0' );    else    capture = cvCaptureFromAVI( input_name );     cvNamedWindow( "result", 1 );    if( capture )    {        for(;;)        {            if( !cvGrabFrame( capture ))                break;            frame = cvRetrieveFrame( capture );            if( !frame )                break;            if( !frame_copy )                frame_copy = cvCreateImage( cvSize(frame->width,frame->height),                IPL_DEPTH_8U, frame->nChannels );            if( frame->origin == IPL_ORIGIN_TL )                cvCopy( frame, frame_copy, 0 );            else                cvFlip( frame, frame_copy, 0 );            detect_and_draw( frame_copy );            if( cvWaitKey( 10 ) >= 0 )                break;        }        cvReleaseImage( &frame_copy );        cvReleaseCapture( &capture );    }    else    {        const char* filename = input_name ? input_name : (char*)"lena.jpg";        IplImage* image = cvLoadImage( filename, 1 );        if( image )        {            detect_and_draw( image );            cvWaitKey(0);            cvReleaseImage( &image );        }        else        {            /* assume it is a text file containing the            list of the image filenames to be processed - one per line */            FILE* f = fopen( filename, "rt" );            if( f )            {                char buf[1000+1];                while( fgets( buf, 1000, f ) )               {                   int len = (int)strlen(buf);                   while( len > 0 && isspace(buf[len-1]) )                   len--;                   buf[len] = '\0';                   image = cvLoadImage( buf, 1 );                   if( image )                   {                       detect_and_draw( image );                       cvWaitKey(0);                       cvReleaseImage( &image );                   }               }               fclose(f);            }        }    }    cvDestroyWindow("result");    return 0;}void detect_and_draw( IplImage* img ){    static CvScalar colors[] =     {        {{0,0,255}},        {{0,128,255}},        {{0,255,255}},        {{0,255,0}},        {{255,128,0}},        {{255,255,0}},        {{255,0,0}},        {{255,0,255}}    };    double scale = 1.3;    IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );    IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),    cvRound (img->height/scale)),    8, 1 );    int i;    cvCvtColor( img, gray, CV_BGR2GRAY );    cvResize( gray, small_img, CV_INTER_LINEAR );    cvEqualizeHist( small_img, small_img );    cvClearMemStorage( storage );    if( cascade )    {        double t = (double)cvGetTickCount();        CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,        1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,        cvSize(30, 30) );        t = (double)cvGetTickCount() - t;        printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );        for( i = 0; i < (faces ? faces->total : 0); i++ )        {            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );            CvPoint center;            int radius;            center.x = cvRound((r->x + r->width*0.5)*scale);            center.y = cvRound((r->y + r->height*0.5)*scale);            radius = cvRound((r->width + r->height)*0.25*scale);            cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );        }    }    cvShowImage( "result", img );    cvReleaseImage( &gray );    cvReleaseImage( &small_img );}    

運行下,你會發現,好慢好慢~~沒找到一次 人臉,都要用幾乎500ms 左右。。。。。

看了看學長的程式,發現有幾個參數,學長用的參數是~~~~(見下程式),發現只需要10ms左右了。。。。

#include "stdafx.h"#include "cv.h"#include "highgui.h"#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>#include <math.h>#include <float.h>#include <limits.h>#include <time.h>#include <ctype.h>#ifdef _EiC#define WIN32#endifstatic CvMemStorage* storage = 0;static CvHaarClassifierCascade* cascade = 0;void detect_and_draw( IplImage* image );const char* cascade_name ="haarcascade_frontalface_alt.xml";int main( int argc, char** argv ){    CvCapture* capture = 0;    IplImage *frame, *frame_copy = 0;    cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );    if( !cascade )    {       printf("No cascade!!!!\n");        return -1;    }    storage = cvCreateMemStorage(0);    capture = cvCaptureFromCAM(-1);     cvNamedWindow( "result", 1 );    if( capture )    {        for(;;)        {            if( !cvGrabFrame( capture ))                break;            frame = cvRetrieveFrame( capture );            if( !frame )                break;            if( !frame_copy )                frame_copy = cvCreateImage( cvSize(frame->width,frame->height),                IPL_DEPTH_8U, frame->nChannels );            if( frame->origin == IPL_ORIGIN_TL )                cvCopy( frame, frame_copy, 0 );            else                cvFlip( frame, frame_copy, 0 );            detect_and_draw( frame_copy );            if( cvWaitKey( 10 ) >= 0 )                break;        }        cvReleaseImage( &frame_copy );        cvReleaseCapture( &capture );    }    cvDestroyWindow("result");    return 0;}void detect_and_draw( IplImage* img ){    static CvScalar colors[] =     {        {{0,0,255}},        {{0,128,255}},        {{0,255,255}},        {{0,255,0}},        {{255,128,0}},        {{255,255,0}},        {{255,0,0}},        {{255,0,255}}    };    double scale = 8.0;    IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );    IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),    cvRound (img->height/scale)),    8, 1 );    int i;    cvCvtColor( img, gray, CV_BGR2GRAY );    cvResize( gray, small_img, CV_INTER_LINEAR );    cvEqualizeHist( small_img, small_img );    cvClearMemStorage( storage );    if( cascade )    {        double t = (double)cvGetTickCount();        CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,        1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,        cvSize(20, 10) );        t = (double)cvGetTickCount() - t;        printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );        for( i = 0; i < (faces ? faces->total : 0); i++ )        {            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );            CvPoint center;            int radius;            center.x = cvRound((r->x + r->width*0.5)*scale);            center.y = cvRound((r->y + r->height*0.5)*scale);            radius = cvRound((r->width + r->height)*0.25*scale);            cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );        }    }    cvShowImage( "result", img );    cvReleaseImage( &gray );    cvReleaseImage( &small_img );}    

然後又採用

double scale = 8.0;

 cvSize(30, 30) );

發現只需要 3ms 了呀!!!吃驚的改進啊啊啊 。。。。

哈哈~~估計30最大了吧。40的時候,就找不到了吧。。。。檢測視窗太大了,就畫不出來了。

好吧,看下原因吧。

========================

    IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),    cvRound (img->height/scale)),    8, 1 );

scale是圖片縮小的倍數。scale越大,說明small_image 越小,在小圖圖中找人臉當然更簡單了。但是,如果要在已檢測到得人臉中繼續找 鼻子 的話,檢測鼻子所用的 比例 scale_for_nose 反而不能太小,學長說 太小了,導致圖片太小反而找不到了。。。。。【這個,我現在還不是很懂···】

++++++++++++++++++++++++++++++++

cvHaarDetectObjects參數意義

函數原型:

CvHaarClassifierCascade* cascade,
                            CvMemStorage* storage,
                            double scale_factor=1.1,
                            int min_neighbors=3, int flags=0,
                            CvSize min_size=cvSize(0,0) );
         image 被檢映像 
         cascade harr 分類器級聯的內部標識形式 
         storage 用來儲存檢測到的一序列候選目標矩形框的記憶體地區。 
         scale_factor 在前後兩次相繼的掃描中,搜尋視窗的比例係數。例如1.1指將搜尋視窗依次擴大10%。 
          min_neighbors 構成檢測目標的相鄰矩形的最小個數(預設-1)。如果組成檢測目標的小矩形的個數和小於 min_neighbors-1 都會被排除。如果min_neighbors 為 0, 則函數不做任何操作就返回所有的被檢候選矩形框,這種設定值一般用在使用者自訂對檢測結果的組合程式上。 
flags 操作方式。當前唯一可以定義的操作方式是 CV_HAAR_DO_CANNY_PRUNING。如果被設定,函數利用Canny邊緣檢測器來排除一些邊緣很少或者很多的映像地區,因為這樣的地區一般不含被檢目標。臉部偵測中通過設定閾值使用了這種方法,並因此提高了檢測速度。 
         min_size 檢測視窗的最小尺寸。預設的情況下被設為分類器訓練時採用的樣本尺寸(臉部偵測中預設大小是~20×20)。

         函數 cvHaarDetectObjects 使用針對某目標物體訓練的級聯分類器在映像中找到包含目標物體的矩形地區,並且將這些地區作為一序列的矩形框返回。函數以不同比例大小的掃描視窗對映像進行幾次搜尋(察看cvSetImagesForHaarClassifierCascade)。
每次都要對映像中的這些重疊地區利用cvRunHaarClassifierCascade進行檢測。 有時候也會利用某些繼承(heuristics)技術以減少分析的候選地區,例如利用 Canny 裁減 (prunning)方法。 函數在處理和收集到候選的方框(全部通過級聯分類器各層的地區)之後,接著對這些地區進行組合并且返回一系列各個足夠大的組合中的平均矩形。

調節程式中的預設參數(scale_factor=1.1, min_neighbors=3, flags=0)用於對目標進行更精確同時也是耗時較長的進一步檢測。

為了能對視頻映像進行更快的即時檢測,參數設定通常是:scale_factor=1.2, min_neighbors=2, flags=CV_HAAR_DO_CANNY_PRUNING, min_size=<minimum possible face size>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.