#coding:utf-8
import cv2
import os
import random
from PIL import Image
from time import sleep
#import training
class FaceCollection(object):
def __init__(self,subfile_num,person_name):
self.subfile_num = subfile_num
self.person_name = person_name
#判断目录
def findDir(self):
name_file = os.listdir('raw_data') #读取目录下文件,返回无序列表
list = [] #建列表重新排序
for i in name_file:
list.append(int(i.split('_')[0]))
list.sort() #排序
#检测异常,判断目录是否为空 ,空写入0 否则按照顺序添加
if list == []:
os.mkdir('raw_data\\%s_%s' %(self.subfile_num,self.person_name))
else:
self.subfile_num = str(int(list[-1]+1))
os.mkdir('raw_data\\%s_%s' %(self.subfile_num,self.person_name))
return self.subfile_num
#-----收集人脸
def caption(self,window_name,camera_idx,path_name,max_num):
#摄像头窗口名
cv2.namedWindow(window_name)
face_model = cv2.CascadeClassifier('face.xml')
#开摄像头
face_capture = cv2.VideoCapture(camera_idx)
num = 0
while face_capture.isOpened:
flag,frame = face_capture.read()
if not flag:
break
gray = cv2.cvtColor(src=frame,code=cv2.COLOR_BGR2GRAY)
#人脸检测,1.2和3分别为图片缩放比例和需要检测的有效点数
face_detect = face_model.detectMultiScale(gray, scaleFactor = 1.2,
minNeighbors = 3, minSize = (32, 32))
if len(face_detect) > 0:
for face_detects in face_detect:
x,y,w,h = face_detects
#将当前帧保存为图片
img_name = '%s/%s_%d.jpg'%(path_name,
os.path.basename(path_name).split('_')[0],num)
image = frame[y-20: y + h+20 , x-20: x + w+20]
SaveImg = Image.fromarray(image) #PIL直接读取 数组 然后存图片
SaveImg.save(fp=img_name)
img_open = Image.open(fp=img_name)
conv_RGB = img_open.convert('L') #统一转换一下RGB格式 统一化
new_img = conv_RGB.resize((100,100),Image.BILINEAR)
new_img.save(img_name)
#image = cv2.cvtColor(src=image,code=cv2.COLOR_BGR2GRAY) # gray
#cv2.imwrite(img_name, new_img)
num += 1
if num > (max_num): #如果超过指定最大保存数量退出循环for
break
cv2.rectangle(frame,(x-20,y-20),(x+w+20,y+h+20),color=(0,255,0),thickness=2)
cv2.putText(frame,'num:%d' % (num),(x - 30, y - 30),fontScale=1,
fontFace=cv2.FONT_HERSHEY_COMPLEX,color=(0,255,0),thickness=1)
cv2.imshow(window_name,frame)
if num > (max_num): #如果超过指定最大保存数量退出while
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#释放摄像头并销毁所有窗口
face_capture.release()
cv2.destroyAllWindows()
def MAIN():
#PersonName=input('请输入姓名:-->')
personName = 'lgl'
subfile_num = '0'
fc = FaceCollection(subfile_num,personName)
# subfile_num = fc.findDir()#注释掉,不再判断和新建目录
# print(subfile_num)
fc.caption('save...',0,r'F:\jupyternb\keras\zhengzhengclass\faceDetect\raw_data\2_lgl',20)
if __name__ == '__main__':
MAIN()
摄像头收集保存图片(人脸),opencv
最新推荐文章于 2023-04-10 10:48:38 发布