python opencv识别年龄性别代码
时间: 2023-07-30 18:04:28 浏览: 164
以下是使用 OpenCV 和深度学习库 Keras 实现年龄和性别识别的 Python 代码:
首先,安装必要的库:
```python
!pip install opencv-python
!pip install keras
!pip install tensorflow
```
然后,导入必要的库:
```python
import cv2
import keras
import numpy as np
```
接下来,加载已经训练好的深度学习模型:
```python
age_model = keras.models.load_model('age_model.h5')
gender_model = keras.models.load_model('gender_model.h5')
```
然后,定义一个函数用于识别年龄和性别:
```python
def predict_age_gender(image_path):
img = cv2.imread(image_path)
img = cv2.resize(img, (224, 224))
img = np.expand_dims(img, axis=0)
img = img / 255.0
age_pred = age_model.predict(img)[0]
age_bins = np.arange(0, 101)
age = int(np.dot(age_pred, age_bins))
gender_pred = gender_model.predict(img)[0]
gender = 'Male' if gender_pred[0] > gender_pred[1] else 'Female'
return age, gender
```
最后,调用该函数并传入图像路径即可得到识别结果:
```python
age, gender = predict_age_gender('test.jpg')
print('Age:', age)
print('Gender:', gender)
```
注意:这里的 `age_model.h5` 和 `gender_model.h5` 是已经训练好的深度学习模型文件,需要提前下载或者自行训练得到。
阅读全文