天天看點

matlab/opencv圖像處理之模闆比對

如果要在一幅圖像中尋找已知物體,最常用且最簡單的方法之一就是比對。

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  基于最小距離分類器的模闆比對
%  尋找圖檔中與已知模闆的比對區域
%  date:--
%  author:fengyun
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%清空變量,讀取圖
clear;close all
template_rgb = imread('C:\Users\Administrator\Desktop\Evernote/4.jpg');
src_rgb = imread('C:\Users\Administrator\Desktop\Evernote/5.jpg');

%轉換為灰階圖
template=rgb2gray(template_rgb);    template = im2double(template);
src=rgb2gray(src_rgb);  src = im2double(src);

figure('name','模闆比對結果'),
subplot(,,),imshow(template_rgb),title('模闆'),

%球的模闆與原始圖像的大小
tempSize=size(template);
tempHeight=tempSize(); tempWidth=tempSize();
srcSize=size(src);
srcHeight=srcSize(); srcWidth=srcSize();

%在圖檔的右側與下側補
%By default, paddarray adds padding before the first element and after the last element along the specified dimension.
srcExpand=padarray(src,[tempHeight- tempWidth-],'post');

%初始化一個距離數組 tmp:mj  template:x
%參見《數字圖像處理》 Page561
distance=zeros(srcSize);
for height=:srcHeight
   for width= :srcWidth
      tmp=srcExpand(height:(height+tempHeight-),width:(width+tempWidth-));
      %diff= template-tmp;
      %distance(height,width)=sum(sum(diff.^));
      %計算決策函數
      distance(height,width)=sum(sum(template'*tmp-0.5.*(tmp'*tmp)));
   end
end

%尋找決策函數最大時的索引
maxDis=max(max(distance));
[x, y]=find(distance==maxDis);

%繪制比對結果
subplot(,,),imshow(src_rgb);title('比對結果'),hold on
rectangle('Position',[x y tempWidth tempHeight],'LineWidth',,'LineStyle','--','EdgeColor','r'),
hold off
           

由于運作速度實在太慢,改用opencv來實作,代碼如下:

//--------------------------------------【程式說明】-------------------------------------------
//      程式描述:模闆比對示例
//      開發測試所用作業系統: Windows 7 64bit
//      開發測試所用IDE版本:Visual Studio 2010
//------------------------------------------------------------------------------------------------



//---------------------------------【頭檔案、命名空間包含部分】----------------------------
//      描述:包含程式所使用的頭檔案和命名空間
//------------------------------------------------------------------------------------------------
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;


//-----------------------------------【宏定義部分】-------------------------------------------- 
//  描述:定義一些輔助宏 
//------------------------------------------------------------------------------------------------ 
#define WINDOW_NAME1 "【原始圖檔】"        //為視窗标題定義的宏 
#define WINDOW_NAME2 "【比對視窗】"        //為視窗标題定義的宏 

//-----------------------------------【全局變量聲明部分】------------------------------------
//          描述:全局變量的聲明
//-----------------------------------------------------------------------------------------------
Mat g_srcImage; Mat g_templateImage; Mat g_resultImage;
int g_nMatchMethod;
int g_nMaxTrackbarNum = ;

//-----------------------------------【全局函數聲明部分】--------------------------------------
//          描述:全局函數的聲明
//-----------------------------------------------------------------------------------------------
void on_Matching( int, void* );
static void ShowHelpText( );


//-----------------------------------【main( )函數】--------------------------------------------
//          描述:控制台應用程式的入口函數,我們的程式從這裡開始執行
//-----------------------------------------------------------------------------------------------
int main(  )
{
    //【0】改變console字型顔色
    system("color 1F"); 

    //【0】顯示幫助文字
    ShowHelpText();

    //【1】載入原圖像和模闆塊
    g_srcImage = imread( "3.jpg",  );
    g_templateImage = imread( "4.jpg",  );

    //【2】建立視窗
    namedWindow( WINDOW_NAME1, WINDOW_AUTOSIZE );
    namedWindow( WINDOW_NAME2, WINDOW_AUTOSIZE );

    //【3】建立滑動條并進行一次初始化
    createTrackbar( "方法", WINDOW_NAME1, &g_nMatchMethod, g_nMaxTrackbarNum, on_Matching );
    on_Matching( ,  );

    waitKey();
    return ;

}

//-----------------------------------【on_Matching( )函數】--------------------------------
//          描述:回調函數
//-------------------------------------------------------------------------------------------
void on_Matching( int, void* )
{
    //【1】給局部變量初始化
    Mat srcImage;
    g_srcImage.copyTo( srcImage );

    //【2】初始化用于結果輸出的矩陣
    int resultImage_cols =  g_srcImage.cols - g_templateImage.cols + ;
    int resultImage_rows = g_srcImage.rows - g_templateImage.rows + ;
    g_resultImage.create( resultImage_cols, resultImage_rows, CV_32FC1 );

    //【3】進行比對和标準化
    matchTemplate( g_srcImage, g_templateImage, g_resultImage, g_nMatchMethod );
    normalize( g_resultImage, g_resultImage, , , NORM_MINMAX, -, Mat() );

    //【4】通過函數 minMaxLoc 定位最比對的位置
    double minValue; double maxValue; Point minLocation; Point maxLocation;
    Point matchLocation;
    minMaxLoc( g_resultImage, &minValue, &maxValue, &minLocation, &maxLocation, Mat() );

    //【5】對于方法 SQDIFF 和 SQDIFF_NORMED, 越小的數值有着更高的比對結果. 而其餘的方法, 數值越大比對效果越好
    //此句代碼的OpenCV2版為:
    //if( g_nMatchMethod  == CV_TM_SQDIFF || g_nMatchMethod == CV_TM_SQDIFF_NORMED )
    //此句代碼的OpenCV3版為:
    if( g_nMatchMethod  == TM_SQDIFF || g_nMatchMethod == TM_SQDIFF_NORMED )
    { matchLocation = minLocation; }
    else
    { matchLocation = maxLocation; }

    //【6】繪制出矩形,并顯示最終結果
    rectangle( srcImage, matchLocation, Point( matchLocation.x + g_templateImage.cols , matchLocation.y + g_templateImage.rows ), Scalar(,,), , ,  );
    rectangle( g_resultImage, matchLocation, Point( matchLocation.x + g_templateImage.cols , matchLocation.y + g_templateImage.rows ), Scalar(,,), , ,  );

    imshow( WINDOW_NAME1, srcImage );
    imshow( WINDOW_NAME2, g_resultImage );

}



//-----------------------------------【ShowHelpText( )函數】----------------------------------
//          描述:輸出一些幫助資訊
//----------------------------------------------------------------------------------------------
static void ShowHelpText()
{
    //輸出歡迎資訊和OpenCV版本
    printf("\n\n\t\t\t   目前使用的OpenCV版本為:" CV_VERSION );
    printf("\n\n  ----------------------------------------------------------------------------\n");
    //輸出一些幫助資訊
    printf("\t歡迎來到【模闆比對】示例程式~\n"); 
    printf("\n\n\t請調整滑動條觀察圖像效果\n\n");
    printf(  "\n\t滑動條對應的方法數值說明: \n\n" 
        "\t\t方法【0】- 平方差比對法(SQDIFF)\n" 
        "\t\t方法【1】- 歸一化平方差比對法(SQDIFF NORMED)\n" 
        "\t\t方法【2】- 相關比對法(TM CCORR)\n" 
        "\t\t方法【3】- 歸一化相關比對法(TM CCORR NORMED)\n" 
        "\t\t方法【4】- 相關系數比對法(TM COEFF)\n" 
        "\t\t方法【5】- 歸一化相關系數比對法(TM COEFF NORMED)\n" );  
}
           

運作結果如下:

模闆圖像1:

matlab/opencv圖像處理之模闆比對

原圖1:

matlab/opencv圖像處理之模闆比對

比對結果1:

matlab/opencv圖像處理之模闆比對

模闆圖像2:

matlab/opencv圖像處理之模闆比對

原圖2:

matlab/opencv圖像處理之模闆比對

比對結果2:

matlab/opencv圖像處理之模闆比對

繼續閱讀