OpenCV4.5.4训练级联分类器的代码,用pycharm写代码
时间: 2024-04-30 09:21:00 浏览: 103
opencv_traincascade.rar
以下是使用PyCharm编写OpenCV 4.5.4级联分类器训练的代码:
1. 安装OpenCV 4.5.4和numpy库
```
pip install opencv-python==4.5.4.58 numpy
```
2. 准备训练数据
将正样本和负样本图片分别放入两个文件夹中,并将文件夹路径记录下来。
3. 编写代码
```python
import cv2
import numpy as np
# 设置正样本和负样本文件夹路径
pos_path = "path/to/positive/folder"
neg_path = "path/to/negative/folder"
# 设置输出文件夹路径和级联分类器名称
output_folder_path = "path/to/output/folder"
cascade_name = "my_cascade.xml"
# 设置级联分类器的宽度和高度
width, height = 24, 24
# 准备训练数据
pos_images = []
neg_images = []
# 加载正样本
for filename in os.listdir(pos_path):
image = cv2.imread(os.path.join(pos_path, filename), cv2.IMREAD_GRAYSCALE)
if image is not None:
pos_images.append(image)
# 加载负样本
for filename in os.listdir(neg_path):
image = cv2.imread(os.path.join(neg_path, filename), cv2.IMREAD_GRAYSCALE)
if image is not None:
neg_images.append(image)
# 设置正样本和负样本的标签
pos_labels = np.ones(len(pos_images), np.int32)
neg_labels = np.zeros(len(neg_images), np.int32)
# 将正样本和负样本合并
images = np.concatenate((pos_images, neg_images))
labels = np.concatenate((pos_labels, neg_labels))
# 创建Haar特征分类器
haar_cascade = cv2.CascadeClassifier("path/to/haarcascade_frontalface_default.xml")
# 计算Haar特征
features = []
for image in images:
feature = haar_cascade.detectMultiScale(image, 1.1, 5)
if len(feature) > 0:
feature = feature[0]
feature = cv2.resize(image[feature[1]:feature[1]+feature[3], feature[0]:feature[0]+feature[2]], (width, height))
features.append(feature)
# 将Haar特征转换为numpy数组
features = np.array(features)
# 将Haar特征和标签分为训练集和测试集
train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size=0.2)
# 创建级联分类器
cascade = cv2.CascadeClassifier()
# 训练级联分类器
cascade.train(train_features, train_labels, width=width, height=height)
# 评估级联分类器
accuracy = cascade.evaluate(test_features, test_labels)
# 保存级联分类器
cascade.save(os.path.join(output_folder_path, cascade_name))
# 打印准确度
print("Accuracy:", accuracy)
```
以上代码中,我们首先设置了正样本和负样本的文件夹路径,并设置了输出文件夹路径和级联分类器名称。然后,我们加载了正样本和负样本的图片,并将它们分别存储在两个列表中。接下来,我们将正样本和负样本的标签设置为1和0,并将它们合并为一个标签列表。然后,我们使用Haar特征分类器计算Haar特征,并将其转换为numpy数组。最后,我们将Haar特征和标签分为训练集和测试集,并使用级联分类器训练数据。在训练完成后,我们评估了级联分类器的准确度,并将其保存到指定的文件夹中。
阅读全文