Reprint: LBP Code detailed comment

Source: Internet
Author: User

%LBP returns the local binary pattern image or LBP histogram of an image.
% J = LBP (i,r,n,mapping,mode) returns either a local binary pattern
% coded image or the local binary pattern histogram of an intensity
% Image I. The LBP codes is computed using N sampling points on a
% Circle of radius R and using mapping table defined by mapping.
% See the getmapping function for different mappings and use 0 for
% no mapping. Possible values for MODE is
% ' h ' or ' hist ' to get a histogram of LBP codes
% ' NH ' to get a normalized histogram
% Otherwise An LBP code image is returned.
%
% J = LBP (I) returns the original (basic) LBP histogram of image I
%
% J = LBP (I,sp,mapping,mode) computes the LBP codes using n sampling
% points defined in (n * 2) matrix SP. The sampling points should be
% defined around the origin (coordinates (0,0)).
%
% Examples
% --------
% i=imread (' test1.bmp ');
% mapping=getmapping (8, ' U2 ');
% H1=LBP (i,1,8,mapping, ' H '); %LBP histogram in (8,1) neighborhood
%%using Uniform patterns
% subplot (2,1,1), stem (H1);
%
% H2=LBP (I);
% subplot (2,1,2), stem (H2);
%
% Sp=[-1-1;-1 0;-1 1; 0-1;-0 1; 1-1; 1 0; 1 1];
% I2=LBP (i,sp,0, ' I '); %LBP code image using sampling points in SP
%%and no mapping. Now H2 are equal to histogram
%%of I2.

function result = LBP (varargin)% Image,radius,neighbors,mapping,mode)
% Version 0.3.2
% Authors:marko Heikkil?and Timo Ahonen

% Changelog
% Version 0.3.2:a bug fix to enable using mappings together with A
% predefined spoints array
% Version 0.3.1:changed MAPPING input to be a struct containing the MAPPING
% table and the number of bins to make the function run faster with high number
% of sampling points. Lauge Sorensen is acknowledged for spotting this problem.


The% check number of the input arguments.% percent of the parameter is Nargin, making it greater than 1 less than 5. If it is not in this interval, the error
Error (Nargchk (1,5,nargin));

image=varargin{1};%% percent value assigns the first parameter to an image
D_image=double (image);%% convert image from uint8 to double type for later calculation

%% The default setting is used only when the image to be processed (one parameter) is given.
%% SP defines the relative position of the center point to its nearest neighbor
%% Neighbors Define number of neighbors
%% mapping defined mappings
%% Mode difference histogram type, ' h ' or ' hist ' is histogram, NH is a histogram of the rules
If Nargin==1
spoints=[-1-1;-1 0;-1 1; 0-1;-0 1; 1-1; 1 0; 1 1];
neighbors=8;
mapping=0;
Mode= ' h ';
End

%% gives two parameters, and the second parameter (representing the nearest neighbor radius) is 1 o'clock
%% only gives the radius of neighbors, not the number of neighbors, error
if (Nargin = = 2) && (Length (varargin{2}) = = 1)
Error (' Input arguments ');
End
%% if more than two parameters are given, and the second parameter (which represents the nearest neighbor radius) is 1 of a length
%% of radius set to second parameter
%% Neighbor Number set to third parameter
if (Nargin > 2) && (Length (varargin{2}) = = 1)
RADIUS=VARARGIN{2};
NEIGHBORS=VARARGIN{3};

Spoints=zeros (neighbors,2);

%% divide 360 degrees evenly into neighbors to calculate the relative coordinates of the nearest neighbor to the center
% Angle step.
A = 2*pi/neighbors;

%% calculates coordinates, each dimension represents Y, and the second dimension represents X
%% Spoints line I represents the i nearest neighbor
For i = 1:neighbors
Spoints (i,1) =-radius*sin ((i-1) *a);
Spoints (i,2) = Radius*cos ((i-1) *a);
End
%% If the number of parameters is greater than or equal to 4, the fourth parameter is assigned to the mapping mapping; otherwise, no mapping.
if (Nargin >= 4)
MAPPING=VARARGIN{4};
if (isstruct (mapping) && mapping.samples ~= Neighbors)
Error (' incompatible mapping ');
End
Else
mapping=0;
End
%% fifth parameter determines the properties of a histogram
if (Nargin >= 5)
MODE=VARARGIN{5};
Else
Mode= ' h ';
End
End
%% If the number of arguments is greater than 1, and the length of the second parameter is greater than 1. The second parameter gives the relative position of the nearest neighbor to the center point.
if (Nargin > 1) && (Length (varargin{2}) > 1)
SPOINTS=VARARGIN{2};
Neighbors=size (spoints,1);
%% If there is a third parameter, assign it to the map mapping
if (Nargin >= 3)
MAPPING=VARARGIN{3};
if (isstruct (mapping) && mapping.samples ~= Neighbors)
Error (' incompatible mapping ');
End
Else
mapping=0;
End

if (Nargin >= 4)
MODE=VARARGIN{4};
Else
Mode= ' h ';
End
End

% determine the dimensions of the input image. The size of the image, the first dimension is Y, the second dimension is X
[ysize xsize] = size (image);

%% to determine block's top left and right bottom two points
Miny=min (Spoints (:, 1));
Maxy=max (Spoints (:, 1));
Minx=min (Spoints (:, 2));
Maxx=max (Spoints (:, 2));

% block size, each LBP code is computed within a Block of size
% Bsizey*bsizex
%% block Size
Bsizey=ceil (Max (maxy,0))-floor (min (miny,0)) +1;
Bsizex=ceil (Max (maxx,0))-floor (min (minx,0)) +1;

% coordinates of origin (0,0) in the block
%% of center point coordinates in block
Origy=1-floor (min (miny,0));
Origx=1-floor (min (minx,0));

% Minimum allowed size for the input image depends
% on the radius of the used LBP operator.
%% Check the size of block and img
if (Xsize < Bsizex | | Ysize < Bsizey)
Error (' Too small input image. Should is at least (2*radius+1) x (2*radius+1) ');
End

% Calculate dx and dy;
DX = Xsize-bsizex;
dy = Ysize-bsizey;

% Fill the center pixel matrix C.
%% all pixel collections that can be the center point of a template
C = Image (ORIGY:ORIGY+DY,ORIGX:ORIGX+DX);
D_c = double (C);

bins = 2^neighbors;

% Initialize The result matrix with zeros.
Result=zeros (dy+1,dx+1);
%% of initialization result matrix


%compute The LBP code image This section is beautifully written!!!!
%% for each neighbor, first align the points you want to compare with the center point, and then use D = N >= C to compare their sizes.
For i = 1:neighbors
y = spoints (i,1) +origy;
x = spoints (i,2) +ORIGX;
% Calculate floors, ceils and rounds for the X and Y.
FY = Floor (y); cy = ceil (y); ry = round (y);
FX = floor (x); CX = ceil (x); Rx = round (x);
% Check if interpolation is needed.
if (ABS (X-RX) < 1e-6) && (ABS (Y-ry) < 1e-6)
% interpolation isn't needed, use original datatypes
N = Image (RY:RY+DY,RX:RX+DX);
D = N >= C;
Else
% interpolation needed, use double type images
ty = Y-fy;
tx = X-FX;

% Calculate the interpolation weights.
W1 = (1-TX) * (1-ty);
W2 = tx * (1-ty);
W3 = (1-tx) * TY;
W4 = tx * TY;
% Compute interpolated pixel values
N = W1*d_image (FY:FY+DY,FX:FX+DX) + w2*d_image (FY:FY+DY,CX:CX+DX) + ...
W3*d_image (CY:CY+DY,FX:FX+DX) + w4*d_image (CY:CY+DY,CX:CX+DX);
D = N >= d_c;
End
% Update the result matrix.
%% Update result Matrix
V = 2^ (i-1);
result = result + V*d;
End

%apply mapping if it is defined
%% if mapping already exists, then take advantage of this mapping.
If isstruct (mapping)
bins = Mapping.num;
For i = 1:size (result,1)
for j = 1:size (result,2)
Result (I,J) = mapping.table (Result (i,j) +1);
End
End
End
%% if you want the parameter list to specify the properties of the histogram, calculate the histogram
if (strcmp (mode, ' h ') | | | strcmp (mode, ' hist ') | | strcmp (mode, ' NH '))
% Return with LBP histogram if mode equals ' hist '.
Result=hist (Result (:), 0: (bins-1));
if (strcmp (mode, ' NH '))
Result=result/sum (result);
End
Else
%otherwise return a matrix of unsigned integers
%% If no attribute of the histogram is specified, the value matrix is returned
if ((bins-1) <=intmax (' uint8 '))
Result=uint8 (result);
ElseIf ((bins-1) <=intmax (' UInt16 '))
Result=uint16 (result);
Else
Result=uint32 (result);
End
End

End

function to generate mapping

%getmapping returns a structure containing a mapping table for LBP codes.
% MAPPING = getmapping (samples,mappingtype) returns a
% structure containing a mapping table for
% LBP codes in a neighbourhood of SAMPLES sampling
% points. Possible values for MappingType is
% ' U2 ' for uniform LBP
% ' ri ' for rotation-invariant LBP
% ' riu2 ' for uniform rotation-invariant LBP.
%
% Example:
% i=imread (' rice.tif ');
% mapping=getmapping (+, ' riu2 ');
% LBPHIST=LBP (i,2,16,mapping, ' hist ');
% now Lbphist contains a rotation-invariant uniform LBP
% histogram in a (16,2) neighbourhood.
%

function mapping = getmapping (Samples,mappingtype)
% Version 0.1.1
% Authors:marko Heikkil?and Timo Ahonen

% Changelog
% 0.1.1 Changed output to is a structure
% Fixed a bug causing out of memory errors when generating rotation
% invariant mappings with high number of sampling points.
% Lauge Sorensen is acknowledged for spotting this problem.

Table = 0:2^samples-1;
Newmax = 0; %number of patterns in the resulting LBP code
index = 0;

If strcmp (MappingType, ' U2 ')%uniform 2
Newmax = samples* (samples-1) + 3;
For i = 0:2^samples-1
% j is the result of I cyclic left shift
J = bitset (Bitshift (i,1, ' uint8 '), 1,bitget (I,samples)); %% calculation of the number of hops
Numt = SUM (Bitget (Bitxor (i,j), 1:samples)),%number of 1->0 and
%0->1 transitions
%in Binar Y string
%x equal to the
%number of 1-bits in
%xor (x,rotate Left (x))
% if the number of hops is not greater than 2, create a new tag index; Put the last class of
if NUMT <= 2
Table (i+1) = index;
Index = index + 1;
Else
table (i+1) = newMax-1;
END
end
End

If strcmp (mappingtype, ' ri ')%rotation invariant
Tmpmap = Zeros (2^samples,1)-1;
For i = 0:2^samples-1
RM = i;
R = i;
%% calculates the smallest of all rotate
for j = 1:samples-1
R = Bitset (Bitshift (r,1, ' uint8 '), 1,bitget (R,samples)); %rotate
%left
If R < RM
RM = R;
End
End
%% Ibid.
If Tmpmap (rm+1) < 0
Tmpmap (rm+1) = Newmax;
Newmax = Newmax + 1;
End
Table (i+1) = Tmpmap (rm+1);
End
End

If strcmp (MappingType, ' Riu2 ')%uniform & Rotation invariant
Newmax = samples + 2;
For i = 0:2^samples-1
j = Bitset (Bitshift (i,1, ' uint8 '), 1,bitget (I,samples)); %rotate Left
NUMT = SUM (Bitget (Bitxor (i,j), 1:samples));
If NUMT <= 2
Table (i+1) = SUM (Bitget (i,1:samples));
Else
Table (i+1) = samples+1;
End
End
End

mapping.table=table;
Mapping.samples=samples;
Mapping.num=newmax;

Main function:

Clear;clc;close All
I=imread (' test1.bmp ');
Mapping=getmapping (8, ' U2 ');

H1=LBP (i,1,8,mapping, ' a ');%%% if you want to display the LBP feature as an image, the fifth parameter is arbitrarily set to a value, but cannot be set. H1=LBP (i,1,8,mapping,1);
Figure;imshow (H1)


H1=LBP (i,1,8,mapping, ' H '); %LBP histogram in (8,1) neighborhood
%using Uniform patterns
Figure
Subplot (2,1,1), stem (H1);
H2=LBP (I);
Subplot (2,1,2), stem (H2);

Reprint: LBP Code detailed comment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.