在图片中截取一段中心事物代码python
时间: 2024-10-21 10:08:52 浏览: 26
在Python中,可以使用PIL(Pillow)库来方便地处理图像,包括截取图像的一部分。假设你想截取一张图片的中心部分,你可以这样做:
```python
from PIL import Image
def crop_center(image_path, output_path, size):
# 打开图片
with Image.open(image_path) as img:
width, height = img.size
# 计算并获取中心区域
left = (width - size[0]) // 2
top = (height - size[1]) // 2
right = left + size[0]
bottom = top + size[1]
# 截取中心区域
cropped_img = img.crop((left, top, right, bottom))
# 保存到新文件
cropped_img.save(output_path)
# 使用示例
crop_center('input_image.jpg', 'center_cropped_output.jpg', (500, 500)) # 截取500x500像素的中心部分
```
这个函数首先打开图片,然后计算出中心位置,接着使用`crop()`方法截取指定大小的中心区域,并将结果保存到新的文件。
阅读全文
相关推荐


















