用lbp特征提取人脸python代码
时间: 2023-11-12 08:15:00 浏览: 196
毕业设计 基于python使用LBP算子提取人脸特征,用深度学习训练验证识别人脸 识别率92%+源代码+文档说明
下面是用Python实现LBP特征提取的人脸识别代码:
```python
import numpy as np
import cv2
# 计算LBP值
def calc_lbp(img, x, y):
c = img[x][y]
code = 0
code |= (img[x-1][y-1] >= c) << 7
code |= (img[x-1][y] >= c) << 6
code |= (img[x-1][y+1] >= c) << 5
code |= (img[x][y+1] >= c) << 4
code |= (img[x+1][y+1] >= c) << 3
code |= (img[x+1][y] >= c) << 2
code |= (img[x+1][y-1] >= c) << 1
code |= (img[x][y-1] >= c) << 0
return code
# 计算LBP特征
def calc_lbp_feature(img):
rows, cols = img.shape
feature = np.zeros((rows-2)*(cols-2), dtype=np.uint8)
cnt = 0
for i in range(1, rows-1):
for j in range(1, cols-1):
feature[cnt] = calc_lbp(img, i, j)
cnt += 1
return feature
# 加载人脸数据集
def load_face_dataset(path):
images = []
labels = []
label = 0
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('.jpg'):
img = cv2.imread(os.path.join(dirpath, filename), cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (64, 64))
feature = calc_lbp_feature(img)
images.append(feature)
labels.append(label)
label += 1
return images, labels
# 训练分类器
def train_classifier(images, labels):
model = cv2.face.LBPHFaceRecognizer_create()
model.train(images, np.array(labels))
return model
# 测试分类器
def test_classifier(model, img):
img = cv2.resize(img, (64, 64))
feature = calc_lbp_feature(img)
label, confidence = model.predict(feature)
return label, confidence
# 加载人脸数据集
images, labels = load_face_dataset('face_dataset')
# 训练分类器
model = train_classifier(images, labels)
# 加载测试图片并进行识别
img = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE)
label, confidence = test_classifier(model, img)
# 显示识别结果
cv2.imshow('test', img)
cv2.waitKey()
cv2.destroyAllWindows()
print(f'label: {label}, confidence: {confidence}')
```
这段代码用到了OpenCV库,需要先安装。代码中的calc_lbp函数实现了LBP值的计算,calc_lbp_feature函数实现了LBP特征的计算,load_face_dataset函数用于加载人脸数据集,train_classifier函数用于训练分类器,test_classifier函数用于测试分类器。最后,加载测试图片并进行识别,输出识别结果。
阅读全文