OpenCV3.4.14训练自己的Haar级联分类器的代码,用pycharm写代码
时间: 2024-05-01 21:22:28 浏览: 12
以下是使用PyCharm编写OpenCV 3.4.14训练自己的Haar级联分类器的代码示例:
1. 首先,需要安装OpenCV 3.4.14和Python。
2. 创建一个新的PyCharm项目,并创建一个名为“haar_training”的Python文件。
3. 导入必要的库:
```python
import cv2
import os
import numpy as np
```
4. 设置训练数据和目标文件夹:
```python
# 训练数据和目标文件夹
pos_folder = "positive_images"
neg_folder = "negative_images"
pos_img_dir = os.getcwd() + "\\" + pos_folder
neg_img_dir = os.getcwd() + "\\" + neg_folder
```
5. 准备正面和负面图像:
```python
# 准备正面和负面图像
pos_images = [os.path.join(pos_img_dir, f) for f in os.listdir(pos_img_dir)]
neg_images = [os.path.join(neg_img_dir, f) for f in os.listdir(neg_img_dir)]
```
6. 创建正面和负面图像txt文件:
```python
# 创建正面和负面图像txt文件
with open("pos.txt", "w") as f:
for img in pos_images:
f.write(img + "\n")
with open("neg.txt", "w") as f:
for img in neg_images:
f.write(img + "\n")
```
7. 创建vec文件:
```python
# 创建vec文件
vec_command = f"opencv_createsamples -info pos.txt -num 100 -w 24 -h 24 -vec pos.vec"
os.system(vec_command)
```
8. 训练分类器:
```python
# 训练分类器
train_command = f"opencv_traincascade -data classifier -vec pos.vec -bg neg.txt -numPos 80 -numNeg 40 -numStages 10 -w 24 -h 24"
os.system(train_command)
```
9. 运行代码,等待训练完成。
注意:以上代码仅供参考,实际使用时需要根据自己的数据集和需求进行修改。