python openCV获取人脸部分并存储功能

时间:2021-05-22

本文实例为大家分享了python openCV获取人脸部分并存储的具体代码,供大家参考,具体内容如下

#-*- coding:utf-8 -*-import cv2import osimport timeimport base64import numpy as np save_path = 'E:\\opencv\\2018-04-24OpenCv\\RAR\\savetest'faceCascade = cv2.CascadeClassifier( './haarcascade_frontalface_alt.xml') cap = cv2.VideoCapture(0) count = 0 while True: ret,frame = cap.read() gray = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY) rect = faceCascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=9, minSize=(50,50), flags=cv2.CASCADE_SCALE_IMAGE ) if not rect is (): for x,y,w,h in rect: roiImg = frame[y:y+h,x:x+w] # 以时间戳和读取的排序作为文件名称 listStr = [str(int(time.time())), str(count)] fileName = ''.join(listStr) # 图片存储 cv2.imwrite(save_path + os.sep + '%s.jpg' % fileName, roiImg) # print (roiImg) # roiTobase64 = cv2.imencode(roiImg,np.uint8) # print (base64.b64encode(roiTobase64)) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2) count += 1 cv2.imshow('opencvCut',frame) k = cv2.waitKey(30) & 0xff if k == 27: breakcap.release()cv2.destroyAllWindows()

小编再为大家分享一段代码:python用opencv批量检测人脸,并保存:

import cv2import sysimport osfrom PIL import ImagecascPath = "haarcascade_frontalface_default.xml" #训练参数文件faceCascade = cv2.CascadeClassifier(cascPath)#分类器 base = 'new_dir\\'for img in os.listdir(base): image = cv2.imread(base + img)#读取图片 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) #直方图均衡化,提高分类效果 faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(10, 10) ) num = 0 for (x, y, w, h) in faces: cv2.imwrite("face_dir\\" + img,image[y:y+h,x:x+w]) num += 1# cv2.imshow("Faces found", image) cv2.waitKey(0)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章