如何用Python PIL按比例坐标裁剪图片?解决坐标报错问题
解决PIL裁剪时"Coordinate 'right' is less than 'left'"报错问题
报错原因
PIL的crop()方法要求传入的参数格式为**(left, top, right, bottom)**,且必须满足left < right、top < bottom。你的代码存在两个核心问题:
- 图片尺寸赋值错误:
img.size返回的是(宽度width, 高度height),你写成了h, w = img.size,导致宽高颠倒,坐标计算完全错误。 - 裁剪框坐标逻辑错误:根据文档定义,
x1、y1是检测框左上角坐标,x0、y0是右下角坐标,但你传入crop的顺序是(x0*h, y0*w, x1*h, y1*w),直接导致right(x1h)小于left(x0h),bottom(y1w)小于top(y0w),触发报错。
修正后的代码
from PIL import Image import requests def img_crop(url, box): img = Image.open(requests.get(url, stream=True).raw) w, h = img.size # 正确获取图片宽、高 # 将比例坐标转换为绝对坐标,匹配crop的(left, top, right, bottom)格式 left = box['x1'] * w top = box['y1'] * h right = box['x0'] * w bottom = box['y0'] * h # 增加鲁棒性处理,确保坐标顺序正确 left, right = sorted([left, right]) top, bottom = sorted([top, bottom]) return img.crop((left, top, right, bottom))
关键修正点
- 纠正了图片尺寸的赋值顺序,保证坐标计算基于正确的宽高。
- 按照
crop()的参数要求,正确映射检测框的左上角/右下角坐标到left/top和right/bottom。 - 加入
sorted()处理,避免因检测框比例异常(比如坐标定义颠倒)再次触发同类报错。
内容的提问来源于stack exchange,提问作者Erlich Bachman
相关产品推荐
相关产品推荐

