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

opencv-python如何根据bounding box坐标完成图像指定区域裁剪

PIL裁剪图像拆分上下区域的正确实现方法

错误原因

你之前的代码问题出在crop参数设置错误:

  • PIL的Image.crop()方法接收的参数格式为(左边界x, 上边界y, 右边界x, 下边界y),四个参数分别对应裁剪区域的左上角和右下角坐标
  • 你误将裁剪区域的右边界设为50,没有保留原图完整宽度,因此得到宽度异常的输出结果

正确实现代码

from PIL import Image

# 读取输入图像
img = Image.open("img.png")
# 获取原图的宽度、总高度
img_width, img_height = img.size

# 粉色木材区域的bounding box参数
x, y, w, h = 50, 1034, 119, 72
# 计算粉色木材区域的底部y坐标
bbox_end_y = y + h

# 裁剪得到上半部分image1:范围从原点到粉色木材起始位置
image1 = img.crop((0, 0, img_width, y))
image1.save("image1.png")

# 裁剪得到下半部分image2:范围从粉色木材结束位置到图像末尾
image2 = img.crop((0, bbox_end_y, img_width, img_height))
image2.save("image2.png")

参数说明

  • 裁剪两个区域时都保留了原图的完整宽度,因此输出图像宽度和原图一致
  • 上下区域自动跳过了粉色木材所在的y坐标区间,符合需求

内容的提问来源于stack exchange,提问作者Miladfa7

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:36:01