1方法:从摄像头中直接获取(成功的)
import cv2
import os
videos_src_path = 'E:/video'
videos_save_path = 'E:/video'
videos = os.listdir(videos_src_path) #用于返回指定的文件夹包含的文件或文件夹的名字的列表。
videos = filter(lambda x: x.endswith('mp4'), videos)
for each_video in videos:
print(each_video)
# get the name of each video, and make the directory to save frames
each_video_name, _ = each_video.split('.')
os.mkdir(videos_save_path + '/' + each_video_name)
each_video_save_full_path = os.path.join(videos_save_path, each_video_name) + '/'
# get the full path of each video, which will open the video tp extract frames
each_video_full_path = os.path.join(videos_src_path, each_video)
cap = cv2.VideoCapture(each_video_full_path)
frame_count = 1
success = True
while (success):
success, frame = cap.read()
print('Read a new frame: ', success)
params = []
params.append(1)
#if len(frame) > 0:
#if success:
if frame is not None:
cv2.imwrite(each_video_save_full_path + each_video_name + "_%d.jpg" % frame_count, frame, params)
frame_count = frame_count + 1
cap.release()
2.方法从
视频文件中:
import os
import cv2
import dlib
import random
import sys
output_dir = os.path.dirname(os.getcwd()) + '/result'
input_dir = os.path.dirname(os.getcwd()) + '/video1'
size = 64
if not os.path.exists(output_dir):
os.makedirs(output_dir)
def count_dirs(path):
count = 0
for dir in os.listdir(path):
count += 1
return count
def relight(img, light=1, bias=0):
w = img.shape[1]
h = img.shape[0]
for i in range(0,w):
for j in range(0,h):
for c in range(3):
tmp = int(img[j,i,c]*light + bias)
if tmp > 255:
tmp = 255
elif tmp < 0:
tmp = 0
img[j,i,c] = tmp
return img
index=1
detector = dlib.get_frontal_face_detector()
def get_faces_from_video(src_video_path, out_path):
camera = cv2.VideoCapture(src_video_path)
global index
while True:
try:
if os.path.exists(out_path + '/' + str(index) + '.jpg'):
index += 1
print('picture %s is already exit' % index)
pass
key = cv2.waitKey(1) & 0xff
if key == 27:
sys.exit(0)
success, img = camera.read()
if success is not None:
if img is not None:
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dets = detector(gray_img, 1)
cv2.imshow('img', img)
for i, d in enumerate(dets):
x1 = d.top() if d.top() > 0 else 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
face = img[x1:y1,x2:y2]
face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))
face = cv2.resize(face, (size,size))
cv2.imshow('image', face)
cv2.imwrite(out_path+'/'+str(index)+'.jpg', face)
index += 1
else:
print("本个视频结束")
break
except:
print("Error!")
break
for dir in os.listdir(input_dir):
each_video_full_path = os.path.join(input_dir, dir)
print(each_video_full_path)
get_faces_from_video(each_video_full_path,output_dir)
3.从采集的图片集中获取:成功的。
import cv2
import dlib
import os
import sys
import random
input_path = os.path.dirname(os.getcwd()) + '/input_img'
output_path = os.path.dirname(os.getcwd()) + '/training_material'
print(os.path.dirname(os.getcwd()))
size = 64
def count_dirs(path):
count = 0
for dir in os.listdir(path):
count += 1
return count
# 改变图片亮度与对比度
def relight(img, light=1, bias=0):
w = img.shape[1]
h = img.shape[0]
# image=[]
for i in range(0, w):
for j in range(0, h):
for c in range(3):
tmp = int(img[j, i, c] * light + bias)
if tmp > 255:
tmp = 255
elif tmp < 0:
tmp = 0
img[j, i, c] = tmp
return img
# 使用dlib自带的frontal_face_detector作为特征提取器
detector = dlib.get_frontal_face_detector()
def get_faces_from_photos(photo_path, out_path, name):
img = cv2.imread(photo_path)
try:
# 转为灰度图
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用detector进行人脸检测
dets = detector(gray_img, 1)
if not len(dets):
print('Can`t get face.')
pass
for i, d in enumerate(dets):
x1 = d.top() if d.top() > 0 else 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
face = img[x1:y1, x2:y2]
# 调整图片的尺寸与对比度
face = cv2.resize(face, (size, size))
face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))
if not os.path.exists(out_path):
os.makedirs(out_path)
if i == 0:
cv2.imwrite(out_path + '/' + name, face)
print('Being processed %s' % name)
else:
cv2.imwrite(out_path + '/' + name + str(i) + '.jpg', face)
print('Being processed %s' % name + str(i))
except:
print('Error!')
pass
for dir in os.listdir(input_path):
dirs = output_path + '/' + dir
for name in os.listdir(input_path + '/' + dir):
photo_path = input_path + '/' + dir + '/' + name
get_faces_from_photos(photo_path, dirs, name)
4,从网上爬虫:
import re
import requests
import cv2
import dlib
import os
index = 1# 定义索引
detector = dlib.get_frontal_face_detector()# 从网络上获取人像
def dowmloadPic(html, keyword, input_dir, output_dir):
global index
pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
print(pic_url)
print('找到关键词:' + keyword + '的图片,现在开始下载图片...')
for each in pic_url:
print('正在下载第' + str(index) + '张图片,图片地址:' + str(each))
try:
pic = requests.get(each, timeout=10)
except requests.exceptions.ConnectionError:
print('【错误】当前图片无法下载')
continue
dir = os.path.dirname(os.getcwd()) + '/DownLoad_picture/' + keyword + '.jpg' # 存放到临时文件夹
fp = open(dir, 'wb')
fp.write(pic.content)
fp.close()
try: # 从文件读取图片
img = cv2.imread(dir)
while (os.path.exists(output_dir + '/' + str(index) + '.jpg')):
index += 1 # 避免重复
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 转为灰度图片
dets = detector(gray_img, 1)# 使用detector进行人脸检测 dets为返回的结果
if not len(dets):
print("找不到人脸!")
os.remove(dir)
pass
# 使用enumerate 函数遍历序列中的元素以及它们的下标
# 下标i为人脸序号
# left:人脸左边距离图片左边界的距离 ;right:人脸右边距离图片左边界的距离
# top:人脸上边距离图片上边界的距离 ;bottom:人脸下边距离图片上边界的距离
for i, d in enumerate(dets):
x1 = d.top() if d.top() > 0 else 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
face = img[x1:y1, x2:y2]
face = cv2.resize(face, (size, size))
cv2.imwrite(output_dir + '/' + str(index) + '.jpg', face)
index += 1
os.remove(dir)
except:
pass
input_dir = os.path.dirname(os.getcwd()) + '/DownLoad_picture'
size = 64
if not os.path.exists(input_dir):
os.makedirs(input_dir)
def main():
word= input("Input key word: ")
picture_dir = os.path.dirname(os.getcwd()) + '/training_material/' + str(word)
if not os.path.exists(picture_dir):
os.makedirs(picture_dir)
for pn in range(0, 1000, 20):
url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn=' + str(
pn) + '&gsm=3c&ct=&ic=0&lm=-1&width=0&height=0'
result = requests.get(url)
dowmloadPic(result.text, word, input_dir, picture_dir)
main()