我这里用的是笔记本自带的摄像头作为图像来源,数据集是以前学习的时候老师提供的(在此求一下.txt数据集转.xml数据集的方法).说实话,没啥技术含量,真正的技术含量都在制作数据集以及优化上.加油吧!!!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/31 0031 11:00
# @Author : joker-syc
# @Site :
# @File : test1.py
# @Software: PyCharm
import cv2
def test():
'''
调用摄像头,捕捉图像
'''
import time
# 读取摄像头,0表示系统默认摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取图像
ret, photo = cap.read()
# 转换颜色空间
img_gray = cv2.cvtColor(photo, cv2.COLOR_BGR2GRAY)
#装载数据集
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
rects = detector.detectMultiScale(img_gray, scaleFactor=1.05, minNeighbors=9,
minSize=(30,30), flags=cv2.CASCADE_SCALE_IMAGE)
# 将脸部用绿色框框住标记出来
for (x, y, w, h) in rects:
cv2.rectangle(photo, (x,y), (x+w, y+h), (0,255,0), 2)
# 将图像传送至窗口
cv2.imshow('Please Take Your Photo!!', photo)
# 设置等待时间,若数字为0则图像定格
key = cv2.waitKey(2)
# 按空格获取图像
if key == ord(" "):
# 以当前时间存储
filename = time.strftime('%Y%m%d-%H%M%S') + ".jpg"
# 保存位置
cv2.imwrite(filename, photo)
# 按“q”退出程序
if key == ord("q"):
cap.release()
break
pass
if __name__ == '__main__':
test()
数据集链接:https://pan.baidu.com/s/1rlaGHrx8c84E9N_pIRGGkw
提取码:4iua