talk is cheep,show you the code
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib import animation
import paddlehub as hub
from PIL import Image, ImageSequence
import numpy as np
import os
import cv2# 定义人脸识别和人物识别的paddlehub函数
face_landmark = hub.Module(name="face_landmark_localization")
human_seg = hub.Module(name="deeplabv3p_xception65_humanseg")# 抠图
def seg_face(img):result = human_seg.segmentation(images=[cv2.imread(img)],visualization=True)print(result[0]['save_path'])test_img_path = result[0]['save_path']img = mpimg.imread(test_img_path)plt.figure(figsize=(10,10))plt.imshow(img) plt.axis('off') plt.show()return test_img_path# 裁剪成为1寸大小的图片
def crop_face(pic_path,rate=1.3):# 人脸识别result = face_landmark.keypoint_detection(paths=[pic_path])face=np.array(result[0]['data'][0],dtype=np.int64)# 剪裁left = face[:,0].min()right= face[:,0].max()w = right-leftcw=int((right+left)/2)upper = face[:,1].min()lower = face[:,1].max()h= lower-upperch=int((lower+upper)/2)h = int(413*w/295)box=(cw-rate*w, ch-rate*h, cw+rate*w, ch+rate*h)img=Image.open(pic_path)img=img.crop(box)img=img.resize((295, 413),Image.ANTIALIAS)return img# 改变颜色
def change_color(img,save_path,thresh=100):def cut_person(img,num=[255,255,255]):img=np.array(img).transpose((2,0,1))person=[]for i in range(3):a=img[i]mask=np.array((img[3]<thresh),dtype=np.uint8)# mask=cv2.erode(mask,None,iterations=1)mask=cv2.dilate(mask,None,iterations=2)mask=np.array(mask,dtype=np.bool)a[mask]=num[i]person.append(a)img=np.array(person).transpose((1,2,0))im=Image.fromarray(img)return imcut=cut_person(img,num=[255,255,255])cut=cut_person(img,num=[255,0,0])cut=cut_person(img,num=[0,0,255])return cut# 生成三种底色的登记照片
def id_photo(pic_path,rate=1.3,thresh=2):pic=seg_face(pic_path)img=crop_face(pic,rate)image = change_color(img,pic,thresh)image.save(pic, quality=95)for pic in ["1.jpg","2.jpg"]:id_photo(pic,rate=1.5,thresh=50)
实验环境
python: 3.7.9
pip: 21.0.1
paddlehub: 2.0.4
paddlepaddle: 2.0.2
有关百度paddlehub的安装请参阅:开始使用_飞桨-源于产业实践的开源深度学习平台
准备工作
1.创建一个.py扩展名文件,如zhengjianzhao.py,将上面的代码拷贝至该文件中;
2.准备两张单人照片,分别命名位:1.jpg、2.jpg(根据自身情况命名,记得修改代码倒数第二行里文件夹);
3.照片与py脚本文件放在同一个文件夹中;
4.使用python IDLE或者visual studio code等工具打开脚本文件,点击运行。也可以在脚本所在文件夹下打开命令行输入:
python zhengjianzhao.py
5.脚本运行起来后你会先看到一张去除了其他背景的人像抠图,点击关闭后,当前文件夹下会生成一个名为humanseg_output的文件夹,生成的一寸照就放在这个文件夹下。
实验效果:
原图:
一寸照:
原图
一寸照
祝实验成功!
欢迎来我的个人网站逛逛:往后码生