赞
踩
1、cv2入门函数imread及其相关操作
2、(详解)opencv里的cv2.resize改变图片大小Python
3、机器学习之人脸识别face_recognition使用
4、使用face_recognition进行人脸校准
5、简单的人脸识别通用流程示意图(这个看着写的挺好的)
6、face_recognition和图像处理中left、top、right、bottom解释
7、使用pillow库对图片进行裁剪
def facecrop(picture_path):
"替换原图"
# step0:读取图片
# imread为image read的缩写,即图像读取的意思
# picture_path:传入参数为文件名字
# cv2.IMREAD_COLOR:默认参数,读入一副彩色图片,忽略alpha通道
demo_image = cv2.imread(picture_path, cv2.IMREAD_COLOR)
# demo_image:是源图像
# dst:目标图像参数没有写。dst图像与src图像的类型相同。
# dsize:目标图像的大小。
# fx :水平轴上的比例因子。即是图像的行的大小乘以2
# fy :竖直轴上的比例因子。即是图像的列的大小乘以2
# interpolation:插值方法 INTER_NEAREST:最近邻插值法
demo_image = cv2.resize(demo_image, dsize=(960, 540), dst=None, fx=0, fy=0, interpolation=cv2.INTER_NEAREST)
# demo_image.shape:图像的w,h,c
image_h, image_w = demo_image.shape[0], demo_image.shape[1]
margin = 0.01
# step1:识别人脸位置
# face_locations:能定位所有图像中识别出的人脸位置信息,返回值是列表形式,列表中每一行是一张人脸的位置信息,包括[top, right, bottom, left],也可理解为每个人脸是一个tuple存储,分别代表框住人脸的矩形中左上角和右下角的坐标(x1,y1,x2,y2)。可遍历列表打印出每张脸的位置信息,也可以通过位置信息截出识别出的人脸的图像显示出来
# [(246, 501, 308, 439), (180, 448, 223, 405), (217, 761, 440, 538), (202, 132, 356, 0)]
face_locations = face_recognition.face_locations(demo_image, model='hog')
print("face_locations", face_locations)
# step2:挑出图片中最大的人脸,返回人脸的位置
face_locations = max_area(face_locations)
print("face_locations(最大):", face_locations)
num = len(face_locations) # 图片中人脸的个数
# step3:裁剪出图片中最大的人脸
# (4, 200, 200, 3)
face_batch = np.empty((len(face_locations), 200, 200, 3))
# face_batch = np.empty((len(face_locations), 300, 300, 3))
print(face_batch)
# i:0 1 2 3
# [top, right, bottom, left]
# rect:(246, 501, 308, 439),
# (180, 448, 223, 405),
# (217, 761, 440, 538),
# (202, 132, 356, 0)
# 以第一个人脸为例
# 目标图片的宽和高分别为(960, 540) 即image_h = 960,image_w = 540
# i=0
# rect = (246, 501, 308, 439)
# top = 246, right = 501, bottom = 308, left = 439
# top: top- image_h * margin = 246 - 960 * 0.01 = 246 - 9.6 = 236.4
# left: left - image_w * margin = 439-540*0.01 = 439 - 5.4 = 433.6
# bottom: bottom + image_h * margin = 308 + 960* 0.01 = 908 + 9.6 =917.6
# right: right + image_w * margin = 501 + 540*0.01 = 501 + 5.4 =505.4
for i, rect in enumerate(face_locations): # rect:中文意思为矩形
top, bottom, left, right = rect[0], rect[2], rect[3], rect[1]
print(top, bottom, left, right)
top = max(int(top - image_h * margin), 0) # image_h = 1080, image_w = 1920
left = max(int(left - image_w * margin), 0)
bottom = min(int(bottom + image_h * margin), image_h - 1)
right = min(int(right + image_w * margin), image_w - 1)
face_img = demo_image[top:bottom, left:right, :]
# face_img = cv2.resize(face_img, (200, 200))
face_img = cv2.resize(face_img, (300, 400))
face_batch[i, :, :, :] = face_img
face_batch = preprocess_input(face_batch)
for rect in face_locations:
cv2.rectangle(demo_image, (rect[3], rect[0]), (rect[1], rect[2]), (255, 0, 0), 2)
cv2.imshow('image', demo_image)
# time.sleep(5)
if cv2.waitKey(0) & 0xff == ord("q"):
cv2.destroyAllWindows()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。