import cv2
import os
def resize_and_save_images(directory, output_directory, scale_percentage=100):
“””
使用OpenCV遍历目录及其子目录下的所有.jpg图片,将其尺寸缩小至原图的scale_percentage%,
并将调整后的图片另存为新文件在指定的输出目录下。
“””
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith(‘.jpg’):
input_path = os.path.join(root, file)
# 构建输出路径,保持目录结构一致
relative_path = os.path.relpath(root, directory)
output_subdir = os.path.join(output_directory, relative_path)
os.makedirs(output_subdir, exist_ok=True)
output_path = os.path.join(output_subdir, file)
try:
# 读取图片
img = cv2.imread(input_path)
if img is None:
print(f”Warning: Unable to load image at {input_path}. Skipping…”)
continue
# 获取图片的宽度和高度
height, width = img.shape[:2]
# 计算新的尺寸
new_width = int(width * (scale_percentage / 100))
new_height = int(height * (scale_percentage / 100))
# 缩放图片
resized_img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_LANCZOS4)
# 保存图片到输出目录
cv2.imwrite(output_path, resized_img)
except Exception as e:
print(f”Error processing {input_path}: {e}. Skipping…”)
# 指定输入和输出目录路径
input_directory_path = ‘F:/python/yrkcol2’
output_directory_path = ‘F:/python/toyrkcol2’
print(“执行完成!”)
# 调用函数
resize_and_save_images(input_directory_path, output_directory_path)