项目中收到7000多张图片需要找到图片中最大的人脸并且裁剪出来,保存到指定的目录下,用python+opencv写的脚本代码如下:
import cv2
import os
class FaceCrop:
#初始化函数
def __init__(self):
self.number = 0
self.face_image_dir = "F:/temp/origin"
self.face_image_path = "F:/temp/result1"
self.face_detector=cv2.CascadeClassifier(
'haarcascade_frontalface_default.xml'
)
list = os.listdir(self.face_image_dir)
for i in range(0, len(list)):
print(list[i])
path = os.path.join(self.face_image_dir, list[i])
img = cv2.imread(path)
myImg, max_face = self.face_collect(img)
if (max_face[0] < 0) or (max_face[1] < 0):
continue
# if max_face == [-80, -80, 160, 300]:
# continue
print(max_face)
self.face_save(myImg, max_face)
#找出面积最大的矩形
def max_matrix(self, matrixs):
max_matrix=[0,0,0,0]
for [x,y,w,h] in matrixs:
if w*h >= max_matrix[2]*max_matrix[3]:
max_matrix=[x,y,w,h]
max_matrix[0] = max_matrix[0] - 80
max_matrix[1] = max_matrix[1] - 80
max_matrix[2] = max_matrix[2] + 160
max_matrix[3] = max_matrix[3] + 300
return max_matrix
# 给图片绘制矩形
# def plot_rectangle(self, img, matrix):
# cv2.rectangle(img, (matrix[0], matrix[1]), (matrix[0] + matrix[2], matrix[1] + matrix[3]),
# (255, 0, 0), 2)
# 人脸检测,标记并返回检测到的最大的人脸,用于人脸识别
def face_collect(self, img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = self.face_detector.detectMultiScale(gray, 1.2, 8)
max_face = self.max_matrix(faces)
# self.plot_rectangle(img, max_face)
return img, max_face
# 保存人脸照片
def face_save(self, img, max_face):
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if max_face[2] > 30:
self.number = self.number + 1
print(self.number)
print(
self.face_image_path + "/" + str(self.number) + ".jpg"
)
cv2.imwrite(
self.face_image_path + '/' + str(self.number) + '.jpg',
img[max_face[1]:max_face[1] + max_face[3], max_face[0]:max_face[0] + max_face[2]]
)
return
if __name__=="__main__":
f=FaceCrop()