Python文件夹中的所有图片进行面部截图显示在一张图中(代码教程)
程序员文章站
2022-04-24 18:20:49
Python文件夹中的所有图片进行面部截图显示在一张图中(代码教程)
# coding:utf-8
import os
import cv2
fro...
Python文件夹中的所有图片进行面部截图显示在一张图中(代码教程)
# coding:utf-8 import os import cv2 from PIL import Image #选择分类器模型(下载地址:https://github.com/opencv/opencv/tree/master/data/haarcascades) classifier = cv2.CascadeClassifier(r'./opencv-master/data/haarcascades/haarcascade_frontalface_default.xml') #加载文件中的所有图片 def load_images_from_folder(folder): imgs = [] for filename in os.listdir(folder): img = cv2.imread(os.path.join(folder,filename)) if img is not None: imgs.append(img) return imgs #将所有图片进行面部截图 def get_images_faces(imglist): imgs = [] for i in range(len(imglist)): faces = classifier.detectMultiScale(imglist[i],minNeighbors=5,minSize=(30, 30)) for (x, y, w, h) in faces: imgs.append(imglist[i][y:y+h,x:x+w]) return imgs #重置图片大小 def images_resize(imglist,width, height): imgs = [] for i in range(len(imglist)): imgs.append(cv2.resize(imglist[i], (width, height)) ) return imgs #拼接多图到一张新图片中 def images_joint(imglist,col,width,height): imgnum = len(imglist) row = col if (imgnum%col == 0): row = int(imgnum/col) else: row = int(imgnum/col) + 1 newimg = Image.new('RGBA',(width*col,height*row),(255,255,255)) for i in range(row): for j in range(col): if (col*i+j<imgnum): loc = (int(j*height),int(i*width)) img = Image.fromarray(cv2.cvtColor(imglist[col*i+j],cv2.COLOR_BGR2RGB)) newimg.paste(img,loc) return newimg if __name__=='__main__': images_col = 6 #拼接图片列数(行数则根据图片数量自定义) img_i_width,img_i_height = 100,100 #拼接图片大小 images = load_images_from_folder(r'D:/Python35/mypy/') images = get_images_faces(images) images = images_resize(images,img_i_width,img_i_height) newimage = images_joint(images,images_col,img_i_width,img_i_height) newimage.show() cv2.waitKey(0)