python opencv批量resize图片
时间: 2023-10-07 20:12:35 浏览: 253
要使用Python的OpenCV库批量调整图片大小,你可以按照以下步骤进行操作:
```python
import cv2
import os
def batch_resize_images(input_dir, output_dir, size):
# 确保输出目录存在
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 遍历输入目录中的所有文件
for filename in os.listdir(input_dir):
# 获取文件路径
input_path = os.path.join(input_dir, filename)
# 检查文件是否为图像文件
if os.path.isfile(input_path) and filename.lower().endswith(('.jpg', '.jpeg', '.png')):
# 读取图像
image = cv2.imread(input_path)
# 调整图像大小
resized_image = cv2.resize(image, size)
# 构造输出文件路径
output_path = os.path.join(output_dir, filename)
# 保存调整后的图像
cv2.imwrite(output_path, resized_image)
# 调用函数进行批量调整图片大小
input_dir = "input_folder" # 输入目录,包含要调整大小的图片文件
output_dir = "output_folder" # 输出目录,保存调整后的图片文件
size = (500, 500) # 要调整的目标尺寸,例如 (width, height)
batch_resize_images(input_dir, output_dir, size)
```
请将代码中的`input_folder`替换为包含要调整大小的图片文件的实际输入目录,将`output_folder`替换为你希望保存调整后图片的输出目录,将`size`替换为你想要调整的目标尺寸。这段代码将遍历输入目录中的所有图片文件(以.jpg、.jpeg或.png结尾),将它们调整为指定的尺寸,并保存到输出目录中。
阅读全文
相关推荐


















