使用Python3.9.1与Pillow8.0裁剪图片后调用.show()函数报错求助
问题分析与解决:Pillow裁剪图片调用show()报错
嘿,我一眼就找到你报错的原因啦!问题出在crop()函数的参数上,你写的参数完全不符合Pillow的要求。
Pillow里Image.crop()需要传入一个四元组(left, upper, right, lower),分别对应裁剪区域的左边缘、上边缘、右边缘、下边缘的坐标。必须满足右边缘坐标大于左边缘,下边缘坐标大于上边缘,不然裁剪出来的是一个宽高为0的无效图像,调用show()肯定会报错。
看你这段代码:
img = image.crop((newWidth,newHeight,newWidth,newHeight))
这里的右边缘和左边缘都是newWidth,下边缘和上边缘都是newHeight,等于没框选任何区域,不报错才怪呢!
给你两种常见的修正方案,你可以根据需求选:
方案1:裁剪右下角四分之一区域
如果你想保留原图片右下角的一半大小区域,代码改成这样:
from PIL import Image image = Image.open('image.PNG') width, height = image.size newWidth = int(width/2) newHeight = int(height/2) # 修正裁剪边界:左=newWidth,上=newHeight,右=原宽度,下=原高度 img = image.crop((newWidth, newHeight, width, height)) img.show()
方案2:裁剪中心区域(四分之一大小)
如果想截取图片正中间的一半大小区域,这么写:
from PIL import Image image = Image.open('image.PNG') width, height = image.size crop_width = int(width/2) crop_height = int(height/2) # 计算中心区域的四个边界 left = (width - crop_width) // 2 upper = (height - crop_height) // 2 right = left + crop_width lower = upper + crop_height img = image.crop((left, upper, right, lower)) img.show()
总之,只要保证right > left和lower > upper,裁剪出来的图像就是有效的,调用show()就不会报错啦!
内容的提问来源于stack exchange,提问作者NelcaRed
相关产品推荐
相关产品推荐

