opencv_createsample.exe
opencv_traincascade.exe
数据准备
1、pos文件夹 (正样本)
2、neg文件夹 (负样本 训练时所需文件)
3、xml (分类器保存的位置)
4、pos.txt (正样本图片路径和图片大小说明)
5、 neg.txt (负样本图片路径说明 训练时所需文件)
6、pos.vec (pos.txt->pos.vec 训练时所需文件)
7、create_sample.bat (pos.txt->pos.vec的命令)
8、treain.bat (训练的命令)
(ps:当然也可通过本地视频搜集人脸图像,代码作简单修改即可)
python代码如下:
# 注意使用的时候,地址作相应变化
from PIL import ImageGrab
import cv2
import numpy as np
import time
def collect_img(filepath):
k = 1
# 识别出人脸后要画的边框的颜色,RGB格式
color = (0, 255, 0)
while 1:
time.sleep(0.5)
img = ImageGrab.grab()
img = np.array(img, dtype=np.uint8)
# 将当前帧转换成灰度图像
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 人脸检测,1.1和2分别为图片缩放比例和需要检测的有效点数
faceRects = classfier.detectMultiScale(img_gray, scaleFactor=1.1, minNeighbors=3, minSize=(40, 40))
if len(faceRects) > 0: # 大于0则检测到人脸
for faceRect in faceRects: # 单独框出每一张人脸
x, y, w, h = faceRect
if w>100 and h>100:
# cv2.rectangle(img, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
filename = filepath + "\\" + str(k) + ".jpg"
k = k+1
# cv2.imwrite(filename, img)
cv2.imwrite(filename, img[y:y+h, x:x+w, :])
# filename = filepath + "\\" + str(k+1) + ".jpg"
# cv2.imwrite(filename, img)
if k>10000:
break
# 主函数
classfier = cv2.CascadeClassifier(r"D:\Program Files\Abacibda36\Lib\site-packages\cv2\data\haarcascade_frontalface_alt_tree.xml")
filepath = r"G:\img\face\pos"
collect_img(filepath)
(ps:注意pos.txt中的数据格式)
# 将图片的信息保存成txt信息
import numpy as np
import cv2
import matplotlib as plt
import os
import time
def save_imginfo_to_txt(filepath, txtpath):
files = os.listdir(filepath)
res = []
for file in files:
filename = filepath + "\\" + file
img = cv2.imread(filename)
# 数据的格式
res.append([filename, 1, 0, 0, img.shape[0], img.shape[1]])
save_txt = txtpath + "\\" + "file_name.txt"
file = open(save_txt, 'a')
for i in res:
file.write(' '.join([str(j) for j in i]))
file.write("\n")
file.close()
# 主函数
filepath = r"G:\img\face\pos"
txtpath = r"G:\img\face"
save_imginfo_to_txt(filepath, txtpath)
(PS:负样本的格式注意)
负样本只需要保存路径即可
在进行这一个步骤的时候,python的工具opencv_createsamples.exe需要复制到当前的文件夹下
写一个bat文件
create_sample.bat
内容如下:
cd C:\Users\Administrator\Desktop\machine_learning\face_study
opencv_createsamples.exe -info pos.txt -vec pos.vec -num 250 -w 35 -h 35
pause
在进行这一个步骤的时候,python的工具opencv_traincascade.exe需要复制到当前的文件夹下
训练需要的东西:pos.vec(源文件 正样本)
负样本(neg.txt)
训练的时候,也写一个bat文件
内容如下:
cd C:\Users\Administrator\Desktop\machine_learning\face_study
opencv_traincascade.exe -data xml -vec pos.vec -bg neg.txt -numPos 100 -numNeg 300 -numStages 15 -precalcValbufSize 200 -precalcdxBufSize 1000 -featureType LBP -w 35 -h 35 -minHitRate 0.99 -maxFalseAlarmRate 0.4 -weightTrimRate 0.95 -maxDepth 1 -maxWeakCount 100 -mode ALL
pause
如果想知道具体参数
可以在cmd目录下,输入
C:\Users\Administrator>opencv_traincascade.exe
Usage: opencv_traincascade.exe
-data <cascade_dir_name> //保存文件
-vec <vec_file_name> //正样本 pos.vec
-bg <background_file_name> //负样本 neg.txt
[-numPos <number_of_positive_samples = 2000>]
[-numNeg <number_of_negative_samples = 1000>]
[-numStages <number_of_stages = 20>]
[-precalcValBufSize <precalculated_vals_buffer_size_in_Mb = 1024>]
[-precalcIdxBufSize <precalculated_idxs_buffer_size_in_Mb = 1024>]
[-baseFormatSave]
[-numThreads <max_number_of_threads = 9>]
[-acceptanceRatioBreakValue <value> = -1>]
--cascadeParams--
[-stageType <BOOST(default)>]
[-featureType <{HAAR(default), LBP, HOG}>]
[-w <sampleWidth = 24>]
[-h <sampleHeight = 24>]
--boostParams--
[-bt <{DAB, RAB, LB, GAB(default)}>]
[-minHitRate <min_hit_rate> = 0.995>]
[-maxFalseAlarmRate <max_false_alarm_rate = 0.5>]
[-weightTrimRate <weight_trim_rate = 0.95>]
[-maxDepth <max_depth_of_weak_tree = 1>]
[-maxWeakCount <max_weak_tree_count = 100>]
--haarFeatureParams--
[-mode <BASIC(default) | CORE | ALL
--lbpFeatureParams--
--HOGFeatureParams--
import cv2
import numpy as np
window_name = "figure"
cap = cv2.VideoCapture("./1.mp4")
# 告诉OpenCv使用人脸识别分类器
haar_xml = r"C:\Users\Administrator\Desktop\machine_learning\face_study\xml\cascade.xml"
classfier = cv2.CascadeClassifier(haar_xml)
# 识别出人脸后要画的边框的颜色,RGB格式
color = (0, 255, 0)
while(1):
# get a frame
ret, frame = cap.read()
if not ret:
break
# 将当前帧转换成灰度图像
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 人脸检测,1.1和2分别为图片缩放比例和需要检测的有效点数
faceRects = classfier.detectMultiScale(grey, scaleFactor=1.1, minNeighbors=3,minSize=(20,20))
if len(faceRects) > 0: # 大于0则检测到人脸
for faceRect in faceRects: # 单独框出每一张人脸q
x, y, w, h = faceRect
cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
# 显示图像
cv2.imshow(window_name, frame)
if cv2.waitKey(100) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
若有疏漏之处,再完善!