栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python批量剪裁美女图片输出为相同尺寸

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python批量剪裁美女图片输出为相同尺寸

 今天分享的代码主要功能是剪裁带有人像的图片,剪裁为相同尺寸的正方形,并且要保留图片中人头部分不能被剪裁掉

# encoding=utf8

'''
Python批量剪裁图片输出为相同尺寸
源码地址:
'''

# 导入包
from PIL import Image
import os


# 定义方法
def imageProcessing(imagepath, squarepath):
	'''读取图片并进行批量剪裁'''
	files = os.listdir(imagepath) # 读取指定目录中的所有文件
	for f in files:
		file_p =  os.path.join(imagepath, f) # 图片原始位置
		img = Image.open(file_p) # 打开图片
		w = nw = img.width       #图片的宽
		h = nh = img.height      #图片的高

		# 计算要剪裁图片的x,y,w,h
		if w >= h:
			nx, ny, nw = (w - h) / 2, 0, h
		if h >= w:
			nx, ny, nh = 0, 0, w

		squar_p = os.path.join(squarepath, f) # 新图片保存位置
		if not os.path.exists(squarepath): 
			os.mkdir(squarepath) # 如果目不存在就创建
		cropped = img.crop((nx, ny, nw + nx, nh + ny)) # 剪裁图片
		cropped = cropped.resize((500, 500)) # 宽高调整为500像素
		cropped = cropped.convert("RGB") # 转为jpe格式
		cropped.save(squar_p) # 保存剪裁后图片
		print(file_p, '==>' ,squar_p)


if __name__ == '__main__':

	# 存放待处理图片的目录
	imagepath = r'D:Testimage'

	# 图片处理结果保存目录
	squarepath = r'D:Testsquare'

	# 执行方法
	imageProcessing(imagepath, squarepath)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1038078.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号