graycomatrix 計算(圖像)灰度共生矩陣(CLCM)

matlab函數: graycomatrix()

功           能:創建灰度共生矩陣

Gray-level co-occurrence matrix from an image

圖像的灰度共生矩陣

灰度共生矩陣是像素距離和角度的矩陣函數,它通過計算圖像中一定距離和一定方向的兩點灰度之間的相關性,來反映圖像在方向、間隔、變化幅度及快慢上的綜合信息。

使用方法:
glcm = graycomatrix(I)
glcms = graycomatrix(I,param1,val1,param2,val2,...)
[glcms,SI] = graycomatrix(...)

描述:
glcms = graycomatrix(I) 產生圖像I的灰度共生矩陣GLCM。它是通過計算兩灰度值 i,j 在圖像 I 中水平相鄰的次數而得到的 (你也可以通過調整' Offsets' 參數來指定其它的像素空間關係),GLCM中的每一個元素(i,j)代表灰度 i 與灰度 j 在圖像 I 中水平相鄰的次數。

graycomatrix()先將圖像 I 歸一化到指定的灰度級,再計算GLCM;這是因爲動態地求取圖像的GLCM區間代價過高。如果I是一個二值圖像,那麼灰度共生矩陣就將圖像轉換到二值灰度級(黑和白)。如果I是一個灰度圖像, 那將轉換到8灰度級(默認)。灰度的級數決定了GLCM的大小尺寸,假設灰度級爲L,則GLCM的尺寸是L x L。你可以通過設定參數“NumLevels”來指定灰度級數目,還可以通過設置“GrayLimits"參數來設置灰度共生矩陣的轉換方式。

下圖在一個4x5的圖像I中顯示瞭如何求解灰度共生矩陣,以(1,1)點爲例,在圖像 I 中水平相鄰的像素對的灰度值都爲1的情況只出現了1次,所以GLCM(1,1)的值是1。,同理,在圖像 I 中水平相鄰的像素對的灰度值分別爲 1和2 的情況出現了2次,所以GLCM(1,2)的值是2。 graycomatrix迭代以上過程,就可以計算出GLCM的所有位置(L^2)的取值。

  

glcms = graycomatrix(I,param1,val1,param2,val2,...) 返回一個或多個灰度灰度共生矩陣,根據指定的參數對的值。參數可以簡寫,並且對大小寫不敏感。

參數
下面按照字母的順序列寫了參數:
     'GrayLimits'  是兩個元素的向量[low,high],指明瞭圖像 I 中的灰度值如何線性歸一化到灰度級別。低於或等於low的灰度值置成1,大於或等於high的灰度值置成NumLevels。如果其設爲[],灰度共生矩陣將使用圖像I的最小和最大灰度值分別作爲GrayLimits的low和high,即[min(I(:) , max(I(:)))]。

     'NumLevels'    一個整數,指定灰度級的數目。例如,如果NumLevels爲8,意思就是將圖像I的灰度映射到1到8之間,它也決定了灰度共生矩陣的大小。默認值是8。

     'Offset'   一個p*2的整數矩陣,指定了感興趣像素對之間的距離和方向。矩陣中的每一行是一個兩元素的向量,[row_offset , col_offset],它指定了一對像素之間的關係,或者說是位移。row_offset是感興趣像素對間隔的行的數目;col_offset是感興趣像素對間隔的列的數目。offset通常表示一個角度,下面列寫的offset的值指定了常見角度。D代表是當前像素與鄰居的距離。

Angle        Offset
  0              [0 D]
 45             [-D D]
 90             [-D 0]
135            [-D -D]
     下圖說明了數組:offset = [0 1; -1 1; -1 0; -1 -1]

 

     'Symmetric'  一個布爾型數(邏輯型),指定創建GLCM時像素對中的兩像素的順序是否考慮。例如,當 'Symmetric' 是true時,graycomatrix計算1連接2的次數時,(1,2)和(2,1)這兩種數對都計算在內。當'Symmetric'是false時,graycomatrix只是計算(1,2)或(2,1).

[glcm,SI] = graycomatrix(....) 返回歸一化(灰度級的)圖像,SI,它被用來計算灰度共生矩陣(GLCM),SI圖像的取值範圍是[1,NumLevels]。

支持類型

      I可以是數字型或邏輯型,但必須是二維的,實數的,非稀疏的矩陣。SI是一個double型矩陣,它和I的尺寸相同。glcms是一個‘NumLevels’ x ‘NumLevels’ x P的double型矩陣,P是offsets的數目(即‘Offset’參數值的列數)。
說明:

      灰度共生矩陣(GLCM)的另一個名字是灰度空間相關矩陣(gray-level spatial dependence matrix)。另一方面,co-occurrence在文獻中使用時經常不帶連字符,即cooccurrence。

     如果像素對中的一個像素值爲NaN,graycomatrix忽略該像素對。

     graycomatrix用NumLevels值替代positive Inf,用1代替negative Inf。

      如果邊界像素的鄰居落在圖像邊界的外邊,graycomatrix忽略該邊界像素。

     當'Symmetric'設置成'true'時,GLCM 是關於對角線對稱的,就是Haralick (1973)描述的GLCM。下面句法(1)使用'Symmetric'爲'true'時創建了GLCM等於句法(2)和句法(3)使用'Symmetric'爲‘false’時產生的GLCM的和。

 graycomatrix(I, 'offset', [0 1], 'Symmetric', true)    (1)
 graycomatrix(I,'offset',  [0,1], 'Symmetric', false)   (2)
 graycomatrix(I,'offset',  [0,-1], 'Symmetric',false)   (3)

 

示例:

計算灰度共生矩陣,並且返回縮放後的圖像,SI
I = [ 1 1 5 6 8 8; 2 3 5 7 0 2; 0 2 3 5 6 7];     % 生成圖像I矩陣
[glcm,SI] = graycomatrix(I,'NumLevels',9,'G',[])  % 計算灰度共生矩陣(glcm)和歸一化圖像(SI)

計算灰度圖像的灰度共生矩陣
I = imread('circuit.tif');     % 讀入circuit.tif圖像
glcm = graycomatrix(I,'Offset',[2 0]);

參考文獻

Haralick, R.M., K. Shanmugan, and I. Dinstein, "Textural Features for Image Classification", IEEE Transactions on Systems, Man, and Cybernetics, Vol. SMC-3, 1973, pp. 610-621.

Haralick, R.M., and L.G. Shapiro. Computer and Robot Vision: Vol. 1, Addison-Wesley, 1992, p. 459.

 


灰度共生矩陣的特徵:

角二階矩(Angular Second Moment, ASM)

也稱爲 能量
ASM=sum(p(i,j).^2)    p(i,j)指歸一化後的灰度共生矩陣
角二階矩是圖像灰度分佈均勻程度和紋理粗細的一個度量,當圖像紋理絞細緻、灰度分佈均勻時,能量值較大,反之,較小。

熵(Entropy, ENT)
ENT=sum(p(i,j)*(-ln(p(i,j)))    
是描述圖像具有的信息量的度量,表明圖像的複雜程序,當複雜程序高時,熵值較大,反之則較小。

反差分矩陣(Inverse Differential Moment, IDM)
IDM=sum(p(i,j)/(1+(i-j)^2))
反映了紋理的清晰程度和規則程度,紋理清晰、規律性較強、易於描述的,值較大;雜亂無章的,難於描述的,值較小。

************************************************************************************************************************************************************************

  *************************************************************  graycomatrix源程序代碼  *****************************************************************************

 ************************************************************************************************************************************************************************

function [GLCMS,SI] = graycomatrix(varargin)
%GRAYCOMATRIX Create gray-level co-occurrence matrix.
%   GLCMS = GRAYCOMATRIX(I) analyzes pairs of horizontally adjacent pixels
%   in a scaled version of I.  If I is a binary image, it is scaled to 2
%   levels. If I is an intensity image, it is scaled to 8 levels. In this
%   case, there are 8 x 8 = 64 possible ordered combinations of values for
%   each pixel pair. GRAYCOMATRIX accumulates the total occurrence of each
%   such combination, producing a 8-by-8 output array, GLCMS. The row and
%   column subscripts in GLCMS correspond respectively to the first and
%   second (scaled) pixel-pair values.
%
%   GLCMS = GRAYCOMATRIX(I,PARAM1,VALUE1,PARAM2,VALUE2,...) returns one or
%   more gray-level co-occurrence matrices, depending on the values of the
%   optional parameter/value pairs. Parameter names can be abbreviated, and
%   case does not matter.
%   
%   Parameters include:
%  
%   'Offset'         A p-by-2 array of offsets specifying the distance 
%                    between the pixel-of-interest and its neighbor. Each 
%                    row in the array is a two-element vector, 
%                    [ROW_OFFSET COL_OFFSET], that specifies the 
%                    relationship, or 'Offset', between a pair of pixels. 
%                    ROW_OFFSET is the number of rows between the 
%                    pixel-of-interest and its neighbor.  COL_OFFSET is the
%                    number of columns between the pixel-of-interest and 
%                    its neighbor. For example, if you want the number of
%                    occurrences where the pixel of interest is one pixel 
%                    to the left of its neighbor, then 
%                    [ROW_OFFSET COL_OFFSET] is [0 1].
%  
%                    Because this offset is often expressed as an angle, 
%                    the following table lists the offset values that 
%                    specify common angles, given the pixel distance D.
%                            
%                    Angle     OFFSET
%                    -----     ------  
%                    0         [0 D]   
%                    45        [-D D]
%                    90        [-D 0]
%                    135       [-D -D]  
%  
%                    ROW_OFFSET and COL_OFFSET must be integers. 
%
%                    Default: [0 1]
%            
%   'NumLevels'      An integer specifying the number of gray levels to use when
%                    scaling the grayscale values in I. For example, if
%                    'NumLevels' is 8, GRAYCOMATRIX scales the values in I so
%                    they are integers between 1 and 8.  The number of gray levels
%                    determines the size of the gray-level co-occurrence matrix
%                    (GLCM).
%
%                    'NumLevels' must be an integer. 'NumLevels' must be 2 if I
%                    is logical.
%  
%                    Default: 8 for numeric
%                             2 for logical
%   
%   'GrayLimits'     A two-element vector, [LOW HIGH], that specifies how 
%                    the grayscale values in I are linearly scaled into 
%                    gray levels. Grayscale values less than or equal to 
%                    LOW are scaled to 1. Grayscale values greater than or 
%                    equal to HIGH are scaled to HIGH.  If 'GrayLimits' is 
%                    set to [], GRAYCOMATRIX uses the minimum and maximum 
%                    grayscale values in I as limits, 
%                    [min(I(:)) max(I(:))].
%  
%                    Default: the LOW and HIGH values specified by the
%                    class, e.g., [LOW HIGH] is [0 1] if I is double and
%                    [-32768 32767] if I is int16.
%
%   'Symmetric'      A Boolean that creates a GLCM where the ordering of
%                    values in the pixel pairs is not considered. For
%                    example, when calculating the number of times the
%                    value 1 is adjacent to the value 2, GRAYCOMATRIX
%                    counts both 1,2 and 2,1 pairings, if 'Symmetric' is
%                    set to true. When 'Symmetric' is set to false,
%                    GRAYCOMATRIX only counts 1,2 or 2,1, depending on the
%                    value of 'offset'. The GLCM created in this way is
%                    symmetric across its diagonal, and is equivalent to
%                    the GLCM described by Haralick (1973).
%
%                    The GLCM produced by the following syntax, 
%
%                    graycomatrix(I, 'offset', [0 1], 'Symmetric', true)
%
%                    is equivalent to the sum of the two GLCMs produced by
%                    these statements.
%
%                    graycomatrix(I, 'offset', [0 1], 'Symmetric', false) 
%                    graycomatrix(I, 'offset', [0 -1], 'Symmetric', false) 
%
%                    Default: false
%  
%  
%   [GLCMS,SI] = GRAYCOMATRIX(...) returns the scaled image used to
%   calculate GLCM. The values in SI are between 1 and 'NumLevels'.
%
%   Class Support
%   -------------             
%   I can be numeric or logical.  I must be 2D, real, and nonsparse. SI is
%   a double matrix having the same size as I.  GLCMS is an
%   'NumLevels'-by-'NumLevels'-by-P double array where P is the number of
%   offsets in OFFSET.
%  
%   Notes
%   -----
%   Another name for a gray-level co-occurrence matrix is a gray-level
%   spatial dependence matrix.
%
%   GRAYCOMATRIX ignores pixels pairs if either of their values is NaN. It
%   also replaces Inf with the value 'NumLevels' and -Inf with the value 1.
%
%   GRAYCOMATRIX ignores border pixels, if the corresponding neighbors
%   defined by 'Offset' fall outside the image boundaries.
%
%   References
%   ----------
%   Haralick, R.M., K. Shanmugan, and I. Dinstein, "Textural Features for
%   Image Classification", IEEE Transactions on Systems, Man, and
%   Cybernetics, Vol. SMC-3, 1973, pp. 610-621.
%
%   Haralick, R.M., and L.G. Shapiro. Computer and Robot Vision: Vol. 1,
%   Addison-Wesley, 1992, p. 459.
%
%   Example 1
%   ---------      
%   Calculate the gray-level co-occurrence matrix (GLCM) and return the
%   scaled version of the image, SI, used by GRAYCOMATRIX to generate the
%   GLCM.
%
%        I = [1 1 5 6 8 8;2 3 5 7 0 2; 0 2 3 5 6 7];
%       [GLCMS,SI] = graycomatrix(I,'NumLevels',9,'G',[])
%     
%   Example 2
%   ---------  
%   Calculate the gray-level co-occurrence matrix for a grayscale image.
%  
%       I = imread('circuit.tif');
%       GLCMS = graycomatrix(I,'Offset',[2 0])
%
%   Example 3
%   ---------
%   Calculate gray-level co-occurrences matrices for a grayscale image
%   using four different offsets.
%  
%       I = imread('cell.tif');
%       offsets = [0 1;-1 1;-1 0;-1 -1];
%       [GLCMS,SI] = graycomatrix(I,'Of',offsets); 
%
%   Example 4
%   ---------  
%   Calculate the symmetric gray-level co-occurrence matrix (the Haralick
%   definition) for a grayscale image.
%  
%       I = imread('circuit.tif');
%       GLCMS = graycomatrix(I,'Offset',[2 0],'Symmetric', true)
%  
%   See also GRAYCOPROPS.
  
%   Copyright 1993-2008 The MathWorks, Inc.
%   $Revision.1 $  $Date: 2008/04/03 03:10:53 $

[I, Offset, NL, GL, makeSymmetric] = ParseInputs(varargin{:});

% Scale I so that it contains integers between 1 and NL.
if GL(2) == GL(1)
  SI = ones(size(I));
else
  slope = (NL-1) / (GL(2) - GL(1));
  intercept = 1 - (slope*(GL(1)));
  SI = round(imlincomb(slope,I,intercept,'double'));
end

% Clip values if user had a value that is outside of the range, e.g.,
% double image = [0 .5 2;0 1 1]; 2 is outside of [0,1]. The order of the
% following lines matters in the event that NL = 0.
SI(SI > NL) = NL;
SI(SI < 1) = 1;

numOffsets = size(Offset,1);

if NL ~= 0

  % Create vectors of row and column subscripts for every pixel and its
  % neighbor.
  s = size(I);
  [r,c] = meshgrid(1:s(1),1:s(2));
  r = r(:);
  c = c(:);

  % Compute GLCMS
  GLCMS = zeros(NL,NL,numOffsets);
  for k = 1 : numOffsets
    GLCMS(:,:,k) = computeGLCM(r,c,Offset(k,:),SI,NL);
    
    if makeSymmetric 
        % Reflect glcm across the diagonal
        glcmTranspose = GLCMS(:,:,k).';
        GLCMS(:,:,k) = GLCMS(:,:,k) + glcmTranspose;
    end
  end

else
  GLCMS = zeros(0,0,numOffsets);
end

%-----------------------------------------------------------------------------
function oneGLCM = computeGLCM(r,c,offset,si,nl)
% computes GLCM given one Offset

r2 = r + offset(1);
c2 = c + offset(2);

[nRow nCol] = size(si);
% Determine locations where subscripts outside the image boundary
outsideBounds = find(c2 < 1 | c2 > nCol | r2 < 1 | r2 > nRow);

% Create vector containing si(r1,c1)
v1 = shiftdim(si,1);
v1 = v1(:);
v1(outsideBounds) = [];

% Create vector containing si(r2,c2). Not using sub2ind for performance
% reasons
r2(outsideBounds) = []; %#ok
c2(outsideBounds) = []; %#ok
Index = r2 + (c2 - 1)*nRow;
v2 = si(Index);

% Remove pixel and its neighbor if their value is NaN.
bad = isnan(v1) | isnan(v2);
if any(bad)
    wid = sprintf('Images:%s:scaledImageContainsNan',mfilename);
    warning(wid, ...
        'GLCM does not count pixel pairs if either of their values is NaN.');
end

Ind = [v1 v2];
Ind(bad,:) = [];

if isempty(Ind)
    oneGLCM = zeros(nl);
else
    % Tabulate the occurrences of pixel pairs having v1 and v2.
    oneGLCM = accumarray(Ind, 1, [nl nl]);
end

%-----------------------------------------------------------------------------
function [I, offset, nl, gl, sym] = ParseInputs(varargin)

iptchecknargin(1,9,nargin,mfilename);

% Check I
I = varargin{1};
iptcheckinput(I,{'logical','numeric'},{'2d','real','nonsparse'}, ...
              mfilename,'I',1);

% Assign Defaults
offset = [0 1];
if islogical(I)
  nl = 2;
else
  nl = 8;
end
gl = getrangefromclass(I);
sym = false;

% Parse Input Arguments
if nargin ~= 1
 
  paramStrings = {'Offset','NumLevels','GrayLimits','Symmetric'};
  
  for k = 2:2:nargin

    param = lower(varargin{k});
    inputStr = iptcheckstrs(param, paramStrings, mfilename, 'PARAM', k);
    idx = k + 1;  %Advance index to the VALUE portion of the input.
    if idx > nargin
      eid = sprintf('Images:%s:missingParameterValue', mfilename);
      error(eid,'Parameter ''%s'' must be followed by a value.', inputStr);        
    end
    
    switch (inputStr)
     
     case 'Offset'
      
      offset = varargin{idx};
      iptcheckinput(offset,{'logical','numeric'},...
                    {'2d','nonempty','integer','real'},...
                    mfilename, 'OFFSET', idx);
      if size(offset,2) ~= 2
        eid = sprintf('Images:%s:invalidOffsetSize',mfilename);
        error(eid, 'OFFSET must be an N-by-2 array.');
      end
      offset = double(offset);

     case 'NumLevels'
      
      nl = varargin{idx};
      iptcheckinput(nl,{'logical','numeric'},...
                    {'real','integer','nonnegative','nonempty','nonsparse'},...
                    mfilename, 'NL', idx);
      if numel(nl) > 1
        eid = sprintf('Images:%s:invalidNumLevels',mfilename);
        error(eid, 'NL cannot contain more than one element.');
      elseif islogical(I) && nl ~= 2
        eid = sprintf('Images:%s:invalidNumLevelsForBinary',mfilename);
        error(eid, 'NL must be two for a binary image.');
      end
      nl = double(nl);      
     
     case 'GrayLimits'
      
      gl = varargin{idx};
      iptcheckinput(gl,{'logical','numeric'},{'vector','real'},...
                    mfilename, 'GL', idx);
      if isempty(gl)
        gl = [min(I(:)) max(I(:))];
      elseif numel(gl) ~= 2
        eid = sprintf('Images:%s:invalidGrayLimitsSize',mfilename);
        error(eid, 'GL must be a two-element vector.');
      end
      gl = double(gl);
    
      case 'Symmetric'
        sym = varargin{idx};
        iptcheckinput(sym,{'logical'}, {'scalar'}, mfilename, 'Symmetric', idx);
        
    end
  end
end


 

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