利用python截取图片

使用的库

  • PIL pip install pillow
  • os 内置

code

from PIL import Image
import os
def cut_image(src,point, dst):
    """
    src:图片路径
    point:坐标 左上,右下(x1,y1,x2,y2)
    dst:保存路径
    """
    img = Image.open(src)
    region = img.crop(point)
    region.save(dst)



def create_point(x, y):
    # 10*2
    x1 = [i + int(x / 10) * i for i in range(10)]
    x2 = x1[1:]
    x2.append(x)
    point_1 = [(x1[i], 0, x2[i], int(y / 2)) for i in range(10)]
    point_2 = [(x1[i], int(y / 2), x2[i], y) for i in range(10)]
    return point_1 + point_2
source_image = "1.png"
img = Image.open(source_image)
x,y = img.size
point = create_point(x,y)
save_dir = "./img"
if not os.path.exists(save_dir):
    os.mkdir(save_dir)
for index, po in enumerate(point, start=1):
    save = os.path.join(save_dir,f"_{str(index)}.png")
    print(f"save to {save}")
    cut_image(source_image,po,save)

截取的图片

截取结果

posted @ 2022-08-30 16:18  love_water  阅读(50)  评论(0)    收藏  举报