感谢前辈的资料,这里做搬运工整合了下
对当前文件夹下所有图片,识别图片中的人脸,并按比例切割后保存
——————————————————————————
#coding=utf-8
# 2020 03 11 zhanghu
import requests,cv2
import re
import os
import bs4
#安装bs4 pip3 install Beautifulsoup4
def cuttingImage(sourceimg="1.jpg",exportImg="1_new.jpg"):
#.读取图片
curpath = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(curpath, sourceimg)
image = cv2.cv2.imread(filename)
#竖屏照片 480*640 960*1280
#print(image.shape)
new_w=480
new_h=int((image.shape[0])*new_w/(image.shape[1]))
image=cv2.cv2.resize(image,(new_w,new_h))
#.加载人脸模型 级联分类器
facemodelPath= os.path.join(curpath, "facemodel.xml")
face_moel = cv2.cv2.CascadeClassifier(facemodelPath)
#.对图片进行灰度处理
gray = cv2.cv2.cvtColor(image, cv2.cv2.COLOR_RGB2GRAY)
#.检查人脸
faces = face_moel.detectMultiScale(gray)
#.标记人脸(椭圆形、三角形、矩形)
for (x,y,w,h) in faces:
print("x,y,w,h",x,y,w,h)
c_x=int(x+w/2)
c_y=int(y+h/2)
n_w=w*3
n_h=int(n_w*4/3)
n_x1= 0 if c_x-int(n_w/2)<0 else c_x-int(n_w/2)
n_y1= 0 if c_y-int(n_h/2)<0 else c_y-int(n_h/2)
n_x2= new_w if (n_x1+n_w)>new_w else (n_x1+n_w)
n_y2= new_h if (n_y1+n_h)>new_h else (n_y1+n_h)
print("n_w,n_h,n_x1,n_y1,n_x2,n_y2",n_w,n_h,n_x1,n_y1,n_x2,n_y2)
#.原始图片 2.左上角坐标 3.右下角坐标 4.颜色值 5.线宽
#cv2.cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
#。裁剪线
#cv2.cv2.rectangle(image,(n_x1,n_y1),(n_x2,n_y2),(0,255,0),2)
#裁剪图片
image=image[n_y1:n_y2,n_x1:n_x2 ]
#调整图片分辨率
new_w=480
new_h=int((image.shape[0])*new_w/(image.shape[1]))
image=cv2.cv2.resize(image,(new_w,new_h))
#save image
saveImgPath=os.path.join(curpath, exportImg)
if os.path.isfile(saveImgPath):
os.remove(saveImgPath)
cv2.cv2.imwrite(saveImgPath,image)
#.显示图片
#cv2.cv2.imshow('face',image)
#.暂停窗口
#cv2.cv2.waitKey(0)
#.销毁窗口
#cv2.cv2.destroyAllWindows()
#----------------------------------------------------------------------------------------------
#-------------------------------------------main-----------------------------------------------
#----------------------------------------------------------------------------------------------
if __name__ == '__main__':
curpath = os.path.dirname(os.path.realpath(__file__))
dirs=os.listdir(curpath)
for file in dirs:
if file.find(".jpg")>3 and -1==file.find("_new.jpg"):
print("--------------->"+file+".....")
s_img= os.path.join(curpath, file)
e_img= os.path.join(curpath, file.replace(".jpg","_new.jpg"))
cuttingImage(s_img,e_img)
print("\r\n")
print("script complete!")