各种不同的模糊处理
python
import os
import cv2
def apply_blur_to_images(input_folder_path, output_folder_path):
# 遍历文件夹下的所有文件
for filename in os.listdir(input_folder_path):
# 检查文件类型是否为图片
if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):
# 构建输入图片的完整路径
input_image_path = os.path.join(input_folder_path, filename)
# 读取图片
image = cv2.imread(input_image_path)
# 根据不同的模糊方法进行处理
for blur_method in ['gaussian', 'mean', 'median', 'bilateral']:
# 创建对应的模糊文件夹
output_blur_folder_path = os.path.join(output_folder_path, blur_method)
os.makedirs(output_blur_folder_path, exist_ok=True)
# 根据选择的模糊方法进行处理
if blur_method == 'mean':
blurred_image = cv2.blur(image, (15, 15))
elif blur_method == 'median':
blurred_image = cv2.medianBlur(image, 15)
elif blur_method == 'bilateral':
blurred_image = cv2.bilateralFilter(image, 15, 75, 75)
else:
blurred_image = cv2.GaussianBlur(image, (15, 15), 0)
# 构建输出图片的完整路径
output_image_path = os.path.join(output_blur_folder_path, filename)
# 保存模糊处理后的图片
cv2.imwrite(output_image_path, blurred_image)
if __name__ == '__main__':
# 文件夹不要有中文!!!!!!!!!
# 输入文件夹路径
input_folder_path = './data'
# 输出文件夹路径
output_folder_path = './output'
# 调用函数
apply_blur_to_images(input_folder_path, output_folder_path)
resize 下采样
python
import os
import cv2
def reduce_resolution(input_folder_path, output_folder_path, scale_factor, interpolation):
# 遍历文件夹下的所有文件
for filename in os.listdir(input_folder_path):
# 检查文件类型是否为图片
if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):
# 构建输入图片的完整路径
input_image_path = os.path.join(input_folder_path, filename)
# 读取图片
image = cv2.imread(input_image_path)
# 计算目标宽度和高度
target_width = int(image.shape[1] * scale_factor)
target_height = int(image.shape[0] * scale_factor)
# 调整图像尺寸
resized_image = cv2.resize(image, (target_width, target_height), interpolation=interpolation)
# 构建输出图片的完整路径
interpolation_name = get_interpolation_name(interpolation)
output_folder = os.path.join(output_folder_path, interpolation_name)
os.makedirs(output_folder, exist_ok=True) # 创建输出文件夹(如果不存在)
output_image_path = os.path.join(output_folder, filename)
# 保存调整尺寸后的图片
cv2.imwrite(output_image_path, resized_image)
def get_interpolation_name(interpolation):
if interpolation == cv2.INTER_NEAREST:
return 'INTER_NEAREST'
elif interpolation == cv2.INTER_LINEAR:
return 'INTER_LINEAR'
elif interpolation == cv2.INTER_CUBIC:
return 'INTER_CUBIC'
elif interpolation == cv2.INTER_LANCZOS4:
return 'INTER_LANCZOS4'
else:
return 'UNKNOWN'
if __name__ == '__main__':
# 文件夹不要有中文!!!!!!!!!
# 输入文件夹路径
input_folder_path = './data'
# 输出文件夹路径
output_folder_path = './output'
# 比例系数
scale_factor = 0.5 # 调整为原始图像的一半
# 插值方法列表
interpolations = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4]
# 遍历插值方法
for interpolation in interpolations:
# 调用函数进行图像尺寸调整
reduce_resolution(input_folder_path, output_folder_path, scale_factor, interpolation)
遍历文件夹,结果以名字命令,方便区分