【原創】使用棋盤格實現攝像頭序號標定

【原創】使用棋盤格實現攝像頭序號標定

Author: chad
Mail: [email protected]

項目中遇到一個問題,通過usb接口在一個工控機上安裝4個相同的攝像頭,但是usb攝像頭卻沒有設備ID等唯一性編碼,導致無法很好的識別每個攝像頭對應的工位序號.

爲此,使用了類似棋盤格的方格實現攝像頭序號標定.使用的序號板如下所示:
這裏寫圖片描述
序號板設計爲外框粗,內框細是爲了方便輪廓查找。

由於序號板相對攝像頭圖像放置如果出現大幅度的旋轉時, 攝像頭無法確定圖片的旋轉方向,所以,程序中不考慮序號板安裝偏轉問題,實際使用時也要求安裝角度必須小於10度.
運行效果如下:
這裏寫圖片描述

如圖所示,程序正確識別出序號板對應的序號.

源碼如下:

/*
    2015-07-24 [email protected]
    編譯命令如下:
    g++ `pkg-config opencv --cflags` cam_seq.c -o cam_seq `pkg-config opencv --libs` 
*/

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <cmath>
#include <opencv/highgui.h>
#include <stdio.h>

using namespace std;
//旋轉,縮放
int WarpAffine(IplImage *src, double angle, double scale )
{
   CvPoint2D32f srcTri[3], dstTri[3];
   CvMat* rot_mat = cvCreateMat(2,3,CV_32FC1);
   IplImage *dst;

   dst = cvCloneImage(src);
   dst->origin = src->origin;
   cvZero(dst);

   //COMPUTE ROTATION MATRIX
   CvPoint2D32f center = cvPoint2D32f(src->width/2,
                                         src->height/2);
   cv2DRotationMatrix(center,angle,scale,rot_mat);
   cvWarpAffine(src,dst,rot_mat);
   cvCopy(dst,src);

   cvReleaseImage(&dst);
   cvReleaseMat(&rot_mat);
   return 0;
}

//獲取4*4棋盤箇中黑色方塊對應的索引
int GetQPIndex(IplImage *srcImage)
{
    int width=srcImage->width;
    int height=srcImage->height;
    int index = 0;       
    for(int row = height/8; row < height; row+=height/4)
    {
        //取圖像的每一行的首地址
        unsigned char* ptr = (unsigned char*)(srcImage->imageData + srcImage->widthStep * row );
        //處理當前行
        for(int col = width/8; col < srcImage->widthStep; col+=width/4)
        {           
            index ++;
            //對當前像素進行判斷
            ptr += col;

            long x,y;
            x = y = 0;
            for( int i= row; i< row+height/8; i++ ) {
                unsigned char* tmptr = (unsigned char*)(srcImage->imageData + srcImage->widthStep * i );
                for( int j = col; j < col+width/8; j++ ) {
                    x ++;
                    y = y + (int)tmptr[j];
                }
            }

            if( y / x < 100 ) {
                return index;
            }
        }
    }

    return 0;
}
//void callTrackbar( int position )
//{

//}
int main(int argc,char *argv[])
{
    char tmpbuf[100];

    CvCapture* capture ;

    cvNamedWindow("cvCanny");
    if( argc != 1 )
        capture = cvCreateCameraCapture( atoi(argv[1]) );       //從視頻設備獲取圖像
    else 
        capture = cvCreateCameraCapture( 0 );       //從視頻設備獲取圖像
    IplImage *frame;
    IplImage *out = NULL;
    IplImage *grayimg = NULL;
    int i = 0;

    double length,area,rectArea;
    double rectDegree = 0.0; //矩形度
    double long2Short = 1.0; //體態比
    int DirectFlag = 0;      //長寬顛倒標準
    //計算邊界序列的參數 長度 面積 矩形 最小矩形 
    //並輸出每個邊界的參數
    CvRect rect;
    CvBox2D box;
    int imageCnt = 1;
    double axisLong = 0.0, axisShort = 0.0;
    double temp;

    frame = cvQueryFrame( capture );  //讀取一幀數據
    if( !frame ) {
        cerr<<"cvQueryFrame fail!"<<endl;
        return -1;
    }
    out = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,1); //深度8bit 單通道
    grayimg = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,1);
    int cannyMax,cannyMin,threshod;
    cannyMax = 0;
    cannyMin = 150;
    threshod = 0;
    while(1)
    {
        frame = cvQueryFrame( capture );  //讀取一幀數據
        if( !frame ) break;     

        WarpAffine( frame, 180, 1.0 );        
        cvCvtColor( frame, grayimg, CV_RGB2GRAY );  //rgb轉換爲灰度圖像
        cvCanny( grayimg, out, cannyMin, cannyMax, 3 );       //邊緣檢測處理
        cvShowImage("cvCanny",out);  //顯示圖像 
        if( !cannyMax ) {
            cannyMax = 250;
            cannyMin = 150;
            cvCreateTrackbar("cannyMax", "cvCanny", &cannyMax, 255, NULL );
            cvSetTrackbarPos( "cannyMax", "cvCanny", cannyMax );
            cvCreateTrackbar("cannyMin", "cvCanny", &cannyMin, 255, NULL );
            cvSetTrackbarPos( "cannyMin", "cvCanny", cannyMin );
        }
        //尋找輪廓
        CvMemStorage *storage = cvCreateMemStorage(0);
        CvSeq * seq = cvCreateSeq(CV_SEQ_ELTYPE_POINT, sizeof(CvSeq), sizeof(CvPoint), storage);
        CvSeq * tempSeq = cvCreateSeq(CV_SEQ_ELTYPE_POINT, sizeof(CvSeq), sizeof(CvPoint), storage);
        int cnt = cvFindContours( out, storage, &seq );//返回輪廓的數目
        //cout<<"number of contours   "<<cnt<<endl;

        int rectCountNum = 0;
        for (tempSeq = seq;tempSeq != NULL; tempSeq = tempSeq->h_next) 
        {
            length = cvArcLength(tempSeq);
            area =  cvContourArea(tempSeq);

            //篩選面積比較大的區域
            if( area > 5000 ) {
                //外接矩形
                rect = cvBoundingRect(tempSeq,1);
                //繪製輪廓和外接矩形
                //cvDrawContours(frame,tempSeq,CV_RGB(255,0,0),CV_RGB(255,0,0),0);
                //cvRectangleR(frame,rect,CV_RGB(0,255,0));
                //cvShowImage("dst",frame);
                //cvWaitKey(0);
                //繪製外接最小矩形
                CvPoint2D32f pt[4];
                box = cvMinAreaRect2(tempSeq,0);
                cvBoxPoints(box,pt);
                //下面開始分析圖形的形狀特徵 
                //長軸 短軸
                axisLong = sqrt(pow(pt[1].x -pt[0].x,2) + pow(pt[1].y -pt[0].y,2));
                axisShort = sqrt(pow(pt[2].x -pt[1].x,2) + pow(pt[2].y -pt[1].y,2));

                DirectFlag = 0;
                if( axisShort > axisLong ) {  
                    temp = axisLong;
                    axisLong = axisShort;
                    axisShort= temp;
                    DirectFlag = 1;
                }
                rectArea = axisLong * axisShort; 
                rectDegree =  area / rectArea;  
                //體態比or長寬比 最下外接矩形的長軸和短軸的比值
                long2Short = axisLong/axisShort;
                //cout<<"long2Short:   "<<long2Short<<endl;
                //cout<<"rectDegree:   "<<rectDegree<<endl;
                //cout<<"rectArea  :   "<<rectArea<<endl;
                if( long2Short> 0.9 && long2Short < 1.1 && rectDegree > 0.9 && rectArea > 5000  )
                {
                    //cout<<"Length:  "<<length<<endl;
                    //cout<<"Area  :  "<<area<<endl;
                    //cout<<"long axis : "<<axisLong<<endl;
                    //cout<<"short axis: "<<axisShort<<endl;
                    //cout<<"long2Short: "<<long2Short<<endl;
                    //cout<<"rectArea  : "<<rectArea<<endl;
                    //cout<<"rectDegree: "<<rectDegree<<endl;
                    //cout<<"rectCountNum: "<<rectCountNum++<<endl;
                    for(int i = 0;i<4;++i) {
                        cvLine(frame,cvPointFrom32f(pt[i]),cvPointFrom32f(pt[((i+1)%4)?(i+1):0]),CV_RGB(255,0,0));
                    }
                    //cvShowImage("out",frame);
                    IplImage *cutimg = NULL;
                    IplImage *cutthreshimg = NULL,*cuttmpimg;

                    cvSetImageROI(frame,rect);

                    cutimg = cvCreateImage(cvSize(rect.width,rect.height),IPL_DEPTH_8U,3);
                    cutthreshimg = cvCreateImage(cvGetSize(cutimg),IPL_DEPTH_8U,1);
                    cuttmpimg = cvCreateImage(cvGetSize(cutimg),IPL_DEPTH_8U,1);

                    cvCopy(frame,cutimg,0);
                    //cvCvtColor( cutimg, cutthreshimg, CV_RGB2GRAY ); //rgb轉換爲灰度圖像
                    //cvThreshold( cuttmpimg, cutthreshimg, threshod, 255, CV_THRESH_BINARY );//圖像二值化
                    //cvAdaptiveThreshold( cuttmpimg, cutthreshimg, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C/*CV_ADAPTIVE_THRESH_MEAN_C*/, 
                    //                     CV_THRESH_BINARY, 3, 5 ); //自適應閾值化
                    //cout<<"box.angle:  "<<abs(box.angle)<<endl;
                    //圖像旋轉
                    //if( abs(box.angle) < 90 ) //旋轉角度在0度附近時會出現0<>90 震盪! 實際使用時旋轉角度也不會超過30度!
                        //WarpAffine( cutimg, DirectFlag ?box.angle:box.angle+90, 1.0 );
                        //WarpAffine( cutthreshimg, DirectFlag ?box.angle:box.angle+90, 1.0 );

                    cvShowImage("cutimg",cutimg);
                    IplImage *cutmpimg = NULL;
                    cutmpimg = cvCreateImage(cvGetSize(cutimg),IPL_DEPTH_8U,1); //深度8bit 單通道

                    cvCvtColor( cutimg, cutmpimg, CV_RGB2GRAY ); //rgb轉換爲灰度圖像

                    cvThreshold( cutmpimg, cutmpimg, 105, 255, CV_THRESH_BINARY );//圖像自適應二值化
                    //cvShowImage("threshold",cutmpimg);
                    cout<<"--------------index="<<GetQPIndex(cutmpimg)<<endl;
                    if( !threshod ) {
                        threshod = 150;
                        cvCreateTrackbar("cvThreshold", "cutimg", &threshod, 255, NULL );
                        cvSetTrackbarPos( "cvThreshold", "cutimg", threshod );
                    }
                    cvResetImageROI(frame);

                    cvReleaseImage( &cutimg );
                    cvReleaseImage( &cuttmpimg );
                    cvReleaseImage( &cutthreshimg );
                }
            }
        }
        char c = cvWaitKey(150);   //等待按鍵輸入
        if( c == 27 ) {
            cvReleaseMemStorage( &storage );
            break;
        }
    }       

    cvReleaseCapture( &capture );
    cvReleaseImage( &frame );
    cvReleaseImage( &out );
    cvReleaseImage( &grayimg );
    cvDestroyWindow("out");

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章