一、LBP介绍
LBP(Local Binary Pattern, 局部二值模式) , 是一种用来描述图像局部纹理特征的算子; 它具有旋转不变性和灰度不变性等显著的优点;
作者: T. Ojala, M.Pietikäinen, 和 D. Harwood ;
提出时间: 1994年
二、LBP原理
LBP算子定义在一个 3 × 3 的窗口内, 以窗口中心像素为阈值, 与相邻的8个像素的灰度值比较, 若周围的像素值大于中心像素值, 则该位置被标记为1; 否则标记为0。如此可以得到一个8位二进制数(通常还要转换为10进制, 即LBP码, 共256种) , 将这个值作为窗口中心像素点的LBP值, 以此来反应这个3× 3区域的纹理信息。
用数学公式表示:
其中, p表示 3 × 3 窗口中除中心像素点外的第p个像素点;I( c )表示中心像素点的灰度值, I( p )表示领域内第p个像素点的灰度值;s(x)公式如下:
- LBP记录的是中心像素点与领域像素点之间的差值;
- 当光照变化引起像素灰度值同增同减时, LBP变化并不明显;
- LBP对与光照变化不敏感, LBP检测的仅仅是图像的纹理信息;
三、代码应用
import cv2
import numpy as np
def LBP(src):
'''
:param src:灰度图像
:return:
'''
height = src.shape[0]
width = src.shape[1]
dst = src.copy()
lbp_value = np.zeros((1, 8), dtype=np.uint8)
# print(lbp_value)
neighbours = np.zeros((1, 8), dtype=np.uint8)
# print(neighbours)
for x in range(1, width - 1):
for y in range(1, height - 1):
neighbours[0, 0] = src[y - 1, x - 1]
neighbours[0, 1] = src[y - 1, x]
neighbours[0, 2] = src[y - 1, x + 1]
neighbours[0, 3] = src[y, x - 1]
neighbours[0, 4] = src[y, x + 1]
neighbours[0, 5] = src[y + 1, x - 1]
neighbours[0, 6] = src[y + 1, x]
neighbours[0, 7] = src[y + 1, x + 1]
center = src[y, x]
for i in range(8):
if neighbours[0, i] > center:
lbp_value[0, i] = 1
else:
lbp_value[0, i] = 0
lbp = lbp_value[0, 0] * 1 + lbp_value[0, 1] * 2 + lbp_value[0, 2] * 4 + lbp_value[0, 3] * 8 \
+ lbp_value[0, 4] * 16 + lbp_value[0, 5] * 32 + lbp_value[0, 6] * 64 + lbp_value[0, 7] * 128
# print(lbp)
dst[y, x] = lbp
return dst
img = cv2.imread('image/people.jpg', 0)
print(img.shape)
cv2.imshow('src', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
new_img = LBP(img)
cv2.imshow('dst', new_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
输入的图像(灰度变化后的):
LBP特征变化后的结果:
ps:这个特征提取的过程稍微有点慢。。。