python批量裁剪图片尺寸将5472 x 3648尺寸的图片裁剪成640*640的图片
时间: 2024-09-15 16:13:26 浏览: 128
在Python中,可以使用PIL(Pillow)库来批量裁剪图片。以下是一个简单的示例,展示如何将所有图片按照指定尺寸裁剪:
```python
from PIL import Image
# 设定原始图片路径、目标尺寸和保存目录
original_dir = 'path/to/original_images'
target_size = (640, 640)
save_dir = 'path/to/save/cropped_images'
for filename in os.listdir(original_dir):
if filename.endswith('.jpg') or filename.endswith('.png'): # 可视化扩展名限制,这里假设是.jpg和.png
img_path = os.path.join(original_dir, filename)
with Image.open(img_path) as im:
cropped_img = im.resize(target_size, Image.ANTIALIAS) # 使用抗锯齿选项
new_path = os.path.join(save_dir, filename)
cropped_img.save(new_path)
相关问题
python批量裁剪图片尺寸将5472 x 3648尺寸的图片裁剪成640*640的图片,边缘图片不足640则填充白色
在Python中,你可以使用PIL(Pillow)库来批量处理这样的图像大小调整任务,尤其是当涉及到裁剪和填充时。首先,你需要安装Pillow库,如果尚未安装可以使用`pip install pillow`命令。
以下是一个简单的脚本示例,展示了如何按照你的需求进行操作:
```python
from PIL import Image
def crop_and_pad(image_path, output_path, size=(640, 640), color='white'):
with Image.open(image_path) as img:
# 裁剪图片到指定尺寸
cropped_img = img.crop((0, 0, size[0], size[1]))
# 如果裁剪后的图片小于目标尺寸,则填充颜色
if cropped_img.width < size[0] or cropped_img.height < size[1]:
pad_width = (size[0] - cropped_img.width) // 2
pad_height = (size[1] - cropped_img.height) // 2
padded_img = Image.new('RGB', size, color=color)
padded_img.paste(cropped_img, (pad_width, pad_height))
# 保存裁剪并填充后的图片
padded_img.save(output_path)
# 示例文件路径替换为你实际的图片目录
input_folder = 'path/to/input/images'
output_folder = 'path/to/output/images'
for filename in os.listdir(input_folder):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
crop_and_pad(input_path, output_path)
```
在这个脚本中,`crop_and_pad`函数接受输入图片路径、输出路径以及裁剪后的尺寸和填充颜色。它先尝试裁剪图片,然后检查是否需要填充,如果是,就创建一个新的图片,并将裁剪的部分放置在新图的中间位置,最后保存结果。
python批量裁剪图片替换原图
你可以使用Pillow库来批量裁剪图片并替换原图。以下是一个基本的示例代码:
```python
from PIL import Image
import os
# 设置裁剪后的图片大小
new_size = (256, 256)
# 遍历文件夹中的所有图片
for file_name in os.listdir('images'):
if file_name.endswith('.jpg'): # 只处理jpg文件
# 打开原始图片
image = Image.open(os.path.join('images', file_name))
# 裁剪图片
cropped_image = image.crop((0, 0, new_size[0], new_size[1]))
# 保存裁剪后的图片
cropped_image.save(os.path.join('images', file_name))
```
这段代码会遍历`images`文件夹中的所有`.jpg`图片,裁剪它们为指定大小,然后覆盖原始图片。你可以根据需要修改代码以适应你的具体需求。
阅读全文
相关推荐











