python 截图图片中的一部分_Python文件夹中的所有图片进行面部截图显示在一张图中(代码教程)...

使用Python结合OpenCV库,从指定文件夹中的所有图片中检测面部,并将这些面部截图拼接成一张新的图片展示。教程中涉及了图像处理、面部检测和图片拼接的代码实现。
摘要由CSDN通过智能技术生成

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

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)

120282_0.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值