opencv-093-对象检测(LBP特征介绍)

知识点

局部二值模式(Local Binary Pattern)主要用来实现2D图像纹理分析。其基本思想是用每个像素跟它周围的像素相比较得到局部图像结构,假设中心像素值大于相邻像素值则则相邻像素点赋值为1,否则赋值为0,最终对每个像素点都会得到一个二进制八位的表示,比如11100111。假设3x3的窗口大小,这样对每个像素点来说组合得到的像素值的空间为[0~2^8]。这种结果称为图像的局部二值模式或者简写为了LBP。

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;
CascadeClassifier faceDetector;
String haar_data_file = "D:/opencv-4.0.0/opencv/build/etc/lbpcascades/lbpcascade_frontalface_improved.xml";
int main(int artc, char** argv) {
Mat frame, gray;
vector<Rect> faces;
VideoCapture capture(0);
faceDetector.load(haar_data_file);
namedWindow("frame", WINDOW_AUTOSIZE);
while (true) {
capture.read(frame);
cvtColor(frame, gray, COLOR_BGR2GRAY);
equalizeHist(gray, gray);
faceDetector.detectMultiScale(gray, faces, 1.2, 1, 0, Size(30, 30), Size(400, 400));
for (size_t t = 0; t < faces.size(); t++) {
rectangle(frame, faces[t], Scalar(0, 0, 255), 2, 8, 0);
}
char c = waitKey(10);
if (c == 27) {
break;
}
imshow("frame", frame);
}

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""
对象检测(LBP特征介绍)
"""

import cv2 as cv

capture = cv.VideoCapture(0)
detector = cv.CascadeClassifier("D:/software/opencv4/build/etc/lbpcascades/lbpcascade_frontalface_improved.xml")

while True:
ret, image = capture.read()
if not ret:
break

faces = detector.detectMultiScale(image, scaleFactor=1.05,
minNeighbors=1, minSize=(30, 30), maxSize=(300, 300))
for x, y, width, height in faces:
cv.rectangle(image, (x, y), (x + width, y + height), (0, 0, 255),
2, cv.LINE_8, 0)
cv.imshow("faces", image)

c = cv.waitKey(50)
if c == 27:
break

cv.destroyAllWindows()

结果

代码地址

github