利用opencv查看文件夹下文件夹中的图片实现人脸识别
时间: 2023-08-13 12:02:36 浏览: 150
可以使用以下步骤来实现利用OpenCV查看文件夹下文件夹中的图片实现人脸识别:
1.首先导入必要的库:
```python
import cv2
import os
```
2.加载已经训练好的人脸识别分类器:
```python
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
```
3.设置主文件夹路径并循环遍历每个文件夹:
```python
main_folder_path = 'your_main_folder_path'
for foldername in os.listdir(main_folder_path):
folder_path = os.path.join(main_folder_path, foldername)
if os.path.isdir(folder_path):
```
4.在每个文件夹中循环遍历每张图片:
```python
for filename in os.listdir(folder_path):
if filename.endswith('.jpg') or filename.endswith('.png'):
img = cv2.imread(os.path.join(folder_path, filename))
```
5.将图片转换成灰度图像:
```python
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
6.使用分类器检测人脸:
```python
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
```
7.在图片中标记人脸位置:
```python
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
```
8.显示标记后的图片:
```python
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下所示:
```python
import cv2
import os
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
main_folder_path = 'your_main_folder_path'
for foldername in os.listdir(main_folder_path):
folder_path = os.path.join(main_folder_path, foldername)
if os.path.isdir(folder_path):
for filename in os.listdir(folder_path):
if filename.endswith('.jpg') or filename.endswith('.png'):
img = cv2.imread(os.path.join(folder_path, filename))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:在运行代码前,需要将主文件夹路径和分类器路径修改成自己的路径。
阅读全文