利用opencv-python实现人脸识别
时间: 2023-05-27 16:05:28 浏览: 245
opencv+python 实现人脸识别
1. 安装OpenCV-Python库
在命令行中输入以下命令:
```python
pip install opencv-python
```
2. 下载Haar级联分类器
在OpenCV源代码中,有一些已经训练好的Haar分类器,可以用于检测人脸、眼睛等。可以从OpenCV的Github仓库中下载。在本例中,我们将使用以下两种分类器:
- haarcascade_frontalface_default.xml:用于检测人脸
- haarcascade_eye.xml:用于检测眼睛
3. 导入库并加载分类器
```python
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
```
4. 加载图像并将其转换为灰度图像
```python
img = cv2.imread('test.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
5. 检测人脸和眼睛
```python
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
```
6. 显示图像并等待用户按键
```python
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```python
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('test.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
运行后,将会显示出识别到的人脸和眼睛的矩形框。
阅读全文