from PIL import Image
def crop_and_save_image(input_path, output_path, left_top, right_bottom):
"""
从输入图像中截取目标区域,并保存为新的图像。
参数:
- input_path: 输入图像路径
- output_path: 输出图像保存路径
- left_top: 左上角点坐标 (x, y)
- right_bottom: 右下角点坐标 (x, y)
"""
try:
# 打开JPEG文件
with Image.open(input_path) as img:
# 使用crop函数截取目标区域
cropped_img = img.crop((left_top[0], left_top[1], right_bottom[0], right_bottom[1]))
# 保存截取的图像
cropped_img.save(output_path)
print(f"截取的图像已保存到 {output_path}")
except Exception as e:
print(f"截取图像时发生错误: {str(e)}")
# 替换 'input_image.jpg' 和 'output_cropped_image.jpg' 为你的实际文件名
# 并设置左上和右下点坐标 (left, top, right, bottom)
crop_and_save_image('1.jpg', '11.jpg', (0, 200), (100, 300))
从图像中截取目标
最新推荐文章于 2024-10-03 09:02:12 发布
这篇文章详细讲解了如何使用Python的PIL库对图片进行区域裁剪,并保存处理后的图片。通过实例展示了如何调用crop_and_save_image函数进行操作。
摘要由CSDN通过智能技术生成