python怎么利用opencv边缘检测 进行人脸检测
时间: 2023-11-23 09:49:33 浏览: 85
要利用OpenCV进行人脸检测,可以使用以下步骤:
1. 导入OpenCV库和numpy库:
```python
import cv2
import numpy as np
```
2. 加载人脸分类器:
```python
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
```
3. 加载图像并将其转换为灰度图像:
```python
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
4. 进行边缘检测:
```python
edges = cv2.Canny(gray, 100, 200)
```
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)
```
6. 显示图像:
```python
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码示例:
```python
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 200)
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)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文