python——将一张图像分割为九张

本文介绍如何使用Python进行图像处理,通过代码演示将一张图片分割成9个等份的小图,适合用于创建九宫格效果或进一步的图像分析。


附:python3.6.4+sublime Text安装及配置 点击打开链接
这个编译器真是相见恨晚啊啊啊啊啊
from PIL import Image
import sys

def fill_image(image):

	width,height=image.size
	print(width,height)

	new_image_length=width if width>height else height

	print(new_image_length)

#new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')
	new_image=Image.new(image.mode,(new_image_length,new_image_length),color='white')
	
	if width>height:

		new_image.paste(image,(0,int((new_image_length-height)/2)))
	else:
		new_image.paste(image,(int((new_image_length-width)/2),0))
	return new_image

def cut_image(image):
	width,height=image.size
	item_width=int(width/3)
	box_list=[]
	count=0
	for j in range(0,3):
		for i in range(0,3):
			count+=1
			box=(i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width)
			box_list.append(box)
	print(count)
	image_list=[image.crop(box) for box in box_list]
	return image_list

def save_images(image_list):
	index=1
	for image in image_list:
		image.save('result/'+str(index)+'.png')
		index+=1
if __name__ == '__main__':
	file_path="001.jpg"
	#打开图像
	image=Image.open(file_path)
	#将图像转为正方形,不够的地方补充为白色底色
	image=fill_image(image)
	#分为图像
	image_list=cut_image(image)
	#保存图像
	save_images(image_list)

结果:


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值