训练数据是opencv GitHub官方地址的模型,数据是五六年前的,小demo试用
opencv官方xml的老格式数据模型
我也觉得比较老了,毕竟好多年前的了,后面再使用主流的模型,也想自己训练模型数据
main.py
from kgOpencv import opencvBase
from kgOpencv import utils
# 图片存在的文件夹
IMAGE_FOLDER_PATH = "image/"
MODE_FOLDER_PATH = "mode/"
if __name__ == '__main__':
print("程序测试")
# 获取图片资源
imagePaths = utils.getFileAllPathOnFolder(r'image')
# 获取训练模型资源
modePaths = utils.getFileAllPathOnFolder(r'mode')
for mode in modePaths:
print(mode)
for i in imagePaths:
opencvBase.recognitionPersion(IMAGE_FOLDER_PATH+i,mode=MODE_FOLDER_PATH+mode,width=500,height=500)
utils.py
import os
# 获取一个目录下所有文件的路径
def getFileAllPathOnFolder(folder):
if not os.path.exists(folder):
raise ("请检查你的文件夹路径是否完整")
filesName = os.listdir(folder)
if filesName.__len__() <= 0:
raise ("该目录下没有任何文件,请检查路径是否完整")
return filesName
opencvBase.py
import cv2
import os
#读取图片
def __loadImage(path,width = 0 , height = 0):
# 判断文件是否存在
if os.path.exists(path) == False:
raise RuntimeError("错误!文件不存在,请检查路径是否完整!")
# 加载图片
img = cv2.imread(path,1)
# 调节图片大小,较上一个版本改进,可以单独传一个参数width或者height
if width != 0 or height != 0:
size = img.shape
if width == 0:
width = size[0]
if height == 0:
height = size[1]
tmpImg = cv2.resize(img, (width, height))
img = tmpImg
# 判空
if img is None:
raise RuntimeError("img 对象不存在")
return img
#显示一种图片
#colorful=1 表示加载彩色图片 0表示黑白图片
def showImageByPath(path,width = 0, height = 0):
img = __loadImage(path,width,height)
cv2.imshow("show image",img)
#0表示任意键退出
cv2.waitKey(0)
cv2.destroyAllWindows()
#单纯显示图片,注意传入参数
def showImage(img,sleep = 0):
if img is None:
pass
else :
cv2.imshow("face Recognition",img)
# 0表示任意键退出
cv2.waitKey(sleep)
cv2.destroyAllWindows()
#识别人体特征,默认识别人脸
def recognitionPersion(path,mode = "mode/haarcascade_frontalface_alt.xml",height = 0,width = 0):
faceImg = __loadImage(path,width,height)
grayImg = cv2.cvtColor(faceImg,cv2.COLOR_BGR2GRAY)
#联级分类器,提取面部特征
faceClassifier = cv2.CascadeClassifier(mode)
faces = faceClassifier.detectMultiScale(grayImg,scaleFactor=1.05,minNeighbors=2)
for x,y,w,h in faces:
faceImg=cv2.rectangle(faceImg,(x,y),(x+w,y+h),(0,255,0),3)
showImage(faceImg,2000)
后面更新打算同过小爬虫爬取图片