通过python代码将图片进行裁剪
时间: 2023-03-25 19:01:34 浏览: 146
你可以使用Python中的Pillow库来裁剪图片。以下是一个示例代码:
```python
from PIL import Image
# 打开图片
img = Image.open('example.jpg')
# 裁剪图片
cropped_img = img.crop((100, 100, 300, 300)) # 左上角坐标为(100, 100),右下角坐标为(300, 300)
# 保存裁剪后的图片
cropped_img.save('cropped_example.jpg')
```
这段代码将打开名为"example.jpg"的图片,将其裁剪为左上角坐标为(100, 100),右下角坐标为(300, 300)的矩形,然后保存为"cropped_example.jpg"。
相关问题
Python图片裁剪代码
在Python中,我们可以使用PIL(Pillow)库来进行图片的裁剪。以下是一个简单的例子,展示如何使用PIL对图片进行水平或垂直方向的裁剪:
```python
from PIL import Image
def crop_image(image_path, left=0, top=0, right=None, bottom=None):
# 打开图片
with Image.open(image_path) as img:
# 如果未提供右下角坐标,则根据提供的左上角和宽度高度计算
if not right or not bottom:
width, height = img.size
right = left + width if right is None else right
bottom = top + height if bottom is None else bottom
# 裁剪并保存新的图片
cropped_img = img.crop((left, top, right, bottom))
cropped_img.save('cropped_' + image_path)
# 示例用法
crop_image('original.jpg', left=50, top=100, right=300, bottom=400)
```
这个`crop_image`函数接受原图路径以及四个参数:左、上、右、下坐标。如果只提供左上角坐标,那么会默认裁剪出从该点开始到图像边缘的部分。
如果你想要更复杂的裁剪操作,比如根据比例裁剪或者指定裁剪区域,可能需要借助`bbox`参数,如`img.crop((x1, y1, x2, y2))`,其中`(x1, y1)`为左上角坐标,`(x2, y2)`为右下角坐标。
python实现图片裁剪代码
以下是使用Python实现图片裁剪的代码示例:
```python
from PIL import Image
def crop_image(image_path, output_path, left, upper, right, lower):
img = Image.open(image_path)
cropped_img = img.crop((left, upper, right, lower))
cropped_img.save(output_path)
# 示例用法
crop_image("./data/cut/thor.jpg", "./data/cut/pil_cut_thor.jpg", 0, 0, 512, 128)
```
这段代码使用了Pillow库来进行图片的裁剪。首先,通过`Image.open()`方法打开原始图片。然后,使用`crop()`方法传入裁剪区域的左上角和右下角坐标来裁剪图片。最后,使用`save()`方法将裁剪后的图片保存到指定路径。在示例中,裁剪区域的左上角坐标为(0, 0),右下角坐标为(512, 128)。
#### 引用[.reference_title]
- *1* [Python实现图片裁剪的两种方式——Pillow和OpenCV](https://blog.csdn.net/hfutdog/article/details/82351549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [如何用python裁剪图片](https://blog.csdn.net/m0_59485658/article/details/123808484)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Python 实现图片裁剪(附代码) | Python工具](https://blog.csdn.net/zhiweihongyan1/article/details/122605995)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文
相关推荐












