✨✨✨
感谢优秀的你打开了小白的文章
“希望在看文章的你今天又进步了一点点,离美好生活更近一步!”🌈
🚀往期回顾
图像的基本处理(一) | (1条消息) 图像基本处理(一)_am_student的博客-CSDN博客 |
图像的基本处理(二) | (1条消息) 图片的基本处理(二)_am_student的博客-CSDN博客 |
图像的基本处理(三) | (1条消息) 图像的基本处理(三)_am_student的博客-CSDN博客 |
图像的基本处理(四) 图像的基本处理(五)ImageDraw 模块的使用 |
🍉绘制色块九宫格
利用PIL的imagedraw库进行颜色的分配。
基本思路:
建立一个300*300的正方形,对两边进行分割操作,分成九份,分别对颜色进行填充。
from PIL import Image,ImageDraw
width,height=300,300
img=Image.new('RGB',(width,height),(255,255,255))
draw_obj=ImageDraw.Draw(img)
def get_color(x,y):
a=x//100+y//100
if a==0:
return (255,0,0)
elif a==1:
return (255,255,0)
elif a==2:
return (255,255,255)
elif a==3:
return (0,0,255)
elif a==4:
return (0,255,255)
else:
return (0,0,0)
for x in range(width):
for y in range(height):
draw_obj.point((x,y),fill=get_color(x,y))
img.show()
结果展示:
🍉 对照片进行九宫格操作
基本思路:
1、打开要处理的图片
2、判断打开的图片是否为正方形
3、如果是正方形,就进行九等分,如果不是正方形,先用白色填充为正方形,再进行九等分
4、保存处理完的图片
from PIL import Image
def cutNine(im):
w = int(im.width/3)
boxList = []
for i in range(0,3):
for j in range(0,3):
box = (j*w, i*w, (j+1)*w, (i+1)*w)
boxList.append(box)
imageList = [im.crop(box) for box in boxList]
return imageList
def fillSquare(im):
w = im.width if im.width>im.height else im.height
newImage = Image.new(im.mode, (w,w), color='white')
if im.width>im.height:
newImage.paste(im, (0,int((w-im.height)/2)))
else:
newImage.paste(im, (int((w-im.width)/2),0))
return newImage
def save_images(imList):
index = 1
for image in imList:
image.save(r'./result/f'+str(index)+'.png', 'PNG')
index += 1
im = Image.open(r'f1.jpg')
if(im.width == im.height):
imageList = cutNine(im)
else:
new_im = fillSquare(im)
imageList = cutNine(new_im)
save_images(imageList)
结果展示:
代码也可关注公众号获取: