You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:07:27