使用PIL库对图像进行裁切

首先需要导入Pillow包
在这里插入图片描述


#####图像路径
basicpath = r'/Users/PycharmProjects/代码及图像/inputs'  # 这个地址换成您自己的文件地址
styleImg = Image.open(basicpath + r'/style/starry_night.jpg')  # 风格图
contentImg = Image.open(basicpath + r'/content/Dipping-Sun.jpg')  # 内容图
#对图像进行尺寸统一的裁切
def ImageResize(styleImg,contentImg):

    if(contentImg.width<=styleImg.width):
        width = contentImg.width
    else:
        width = styleImg.width
    if(contentImg.height<=styleImg.height):
        height = contentImg.height
    else:
        height = styleImg.height

    outStyle = styleImg.resize((width, height), Image.ANTIALIAS)
    outContent = contentImg.resize((width, height), Image.ANTIALIAS)
    outContent.save('/Users/PycharmProjects/代码及图像/inputs/CutContent/outContent.jpg')
    outStyle.save('/Users/PycharmProjects/代码及图像/inputs/CutStyle/outStyle.jpg')
    return 1

  • 先用Image.open(‘文件绝对路径+后缀名’) 赋值给一个变量styleImg,它就代表了打开了这个图像。
  • 然后使用Image.resize()函数,作用是裁切图像长宽,参数是 (width,height),Image.ANTIALIAS
  • 返回值是一个图像,在PIL中,使用save函数可以保存到指定路径(前提是路径的文件夹必须存在)(也可以使用python的os根据路径自动创建原本不存在的文件夹)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值