本文目录导读:

使用 Python + Pillow(推荐)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量模糊处理图片脚本
支持:整图模糊、局部模糊、多种模糊效果
"""
import os
import sys
from PIL import Image, ImageFilter, ImageOps
import argparse
from pathlib import Path
def create_output_dir(input_path, output_dir):
"""创建输出目录"""
if output_dir is None:
# 默认在输入目录下创建 blurred 文件夹
input_dir = Path(input_path)
if input_dir.is_file():
input_dir = input_dir.parent
output_dir = input_dir / "blurred"
output_dir.mkdir(parents=True, exist_ok=True)
return output_dir
def add_gaussian_blur(image, radius=2):
"""高斯模糊"""
return image.filter(ImageFilter.GaussianBlur(radius=radius))
def add_average_blur(image, size=3):
"""均值模糊"""
return image.filter(ImageFilter.BoxBlur(size))
def add_motion_blur(image, angle=0, distance=5):
"""运动模糊"""
return image.filter(ImageFilter.GaussianBlur(radius=distance))
def add_bilateral_blur(image, radius=5, sigma_color=50, sigma_space=50):
"""双边滤波(保留边缘的模糊)"""
# 使用 PIL 的高斯模糊替代(PIL 没有内置双边滤波)
return image.filter(ImageFilter.Smoothing())
def blur_only_center(image, blur_radius=5, center_percent=0.3):
"""只模糊图片中心区域"""
img = image.copy()
width, height = img.size
# 计算中心区域
center_w = int(width * center_percent)
center_h = int(height * center_percent)
left = (width - center_w) // 2
top = (height - center_h) // 2
right = left + center_w
bottom = top + center_h
# 创建 mask
mask = Image.new("L", (width, height), 0)
mask_pixels = mask.load()
from PIL import ImageDraw
draw = ImageDraw.Draw(mask)
draw.rectangle([left, top, right, bottom], fill=255)
# 模糊整个图片
blurred = add_gaussian_blur(image, blur_radius)
# 使用 mask 合成
result = Image.composite(blurred, img, mask)
return result
def remove_exif(image):
"""移除 EXIF 数据"""
data = list(image.getdata())
image_without_exif = Image.new(image.mode, image.size)
image_without_exif.putdata(data)
return image_without_exif
def process_image(input_path, output_path, blur_type='gaussian', radius=5, quality=95, **kwargs):
"""处理单张图片"""
try:
# 打开图片
img = Image.open(input_path)
# 应用模糊
if blur_type == 'gaussian':
result = add_gaussian_blur(img, radius)
elif blur_type == 'average':
result = add_average_blur(img, radius)
elif blur_type == 'motion':
result = add_motion_blur(img, radius)
elif blur_type == 'center':
result = blur_only_center(img, radius, kwargs.get('center_percent', 0.3))
elif blur_type == 'smart':
# 智能模糊 - 保持边缘
result = add_bilateral_blur(img)
else:
print(f"未知的模糊类型: {blur_type}")
return False
# 保存结果
result.save(output_path, quality=quality, optimize=True)
return True
except Exception as e:
print(f"处理 {input_path} 时出错: {e}")
return False
def batch_process(input_path, output_dir=None, blur_type='gaussian',
radius=5, quality=95, recursive=False, **kwargs):
"""批量处理图片"""
input_path = Path(input_path)
output_dir = create_output_dir(input_path, output_dir)
# 收集图片文件
images = []
if input_path.is_file():
if input_path.suffix.lower() in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp', '.tiff']:
images.append(input_path)
elif input_path.is_dir():
pattern = "**/*" if recursive else "*"
for ext in ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.gif', '*.webp', '*.tiff']:
images.extend(input_path.glob(f"{pattern}.{ext.split('.')[1]}"))
if not images:
print("没有找到图片文件")
return
print(f"找到 {len(images)} 张图片")
# 处理每张图片
success_count = 0
for img_path in images:
# 构造输出路径
relative_path = img_path.relative_to(input_path if input_path.is_dir() else input_path.parent)
output_path = output_dir / relative_path
output_path.parent.mkdir(parents=True, exist_ok=True)
print(f"处理: {img_path}")
if process_image(img_path, output_path, blur_type, radius, quality, **kwargs):
success_count += 1
print(f" ✓ 已保存到 {output_path}")
else:
print(f" ✗ 处理失败")
print(f"\n处理完成!成功 {success_count}/{len(images)} 张图片")
print(f"输出目录: {output_dir}")
def main():
parser = argparse.ArgumentParser(description="批量模糊处理图片")
parser.add_argument("input", help="输入文件或文件夹路径")
parser.add_argument("-o", "--output", help="输出文件夹路径(默认:输入目录下blurred文件夹)")
parser.add_argument("-t", "--type", choices=['gaussian', 'average', 'motion', 'center', 'smart'],
default='gaussian', help="模糊类型")
parser.add_argument("-r", "--radius", type=int, default=5, help="模糊半径")
parser.add_argument("-q", "--quality", type=int, default=95, help="图片质量(1-100)")
parser.add_argument("--recursive", action="store_true", help="递归处理子文件夹")
parser.add_argument("--center-percent", type=float, default=0.3,
help="中心模糊范围(0-1,默认0.3)")
args = parser.parse_args()
batch_process(
args.input,
args.output,
args.type,
args.radius,
args.quality,
args.recursive,
center_percent=args.center_percent
)
if __name__ == "__main__":
main()
使用 ImageMagick 命令行工具
#!/bin/bash
# 批量模糊处理图片脚本 (需安装 ImageMagick)
# 使用方法: ./blur_images.sh [输入目录] [输出目录] [模糊半径]
INPUT_DIR="${1:-.}"
OUTPUT_DIR="${2:-blurred}"
BLUR_RADIUS="${3:-5}"
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 计数器
count=0
# 遍历所有图片文件
for img in "$INPUT_DIR"/*.{jpg,jpeg,png,bmp,gif,webp,tiff} 2>/dev/null; do
# 检查文件是否存在
if [ -f "$img" ]; then
filename=$(basename "$img")
echo "处理: $filename"
# 使用 ImageMagick 进行高斯模糊
convert "$img" -blur 0x$BLUR_RADIUS "$OUTPUT_DIR/$filename"
if [ $? -eq 0 ]; then
echo " ✓ 完成"
((count++))
else
echo " ✗ 失败"
fi
fi
done
echo "完成!共处理 $count 张图片"
echo "输出目录: $OUTPUT_DIR"
使用 OpenCV (适合高级处理)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用 OpenCV 进行批量模糊处理
支持更多高级功能:人脸识别模糊、区域模糊等
"""
import os
import cv2
import numpy as np
from pathlib import Path
import argparse
def gaussian_blur(image, kernel_size=(15, 15)):
"""高斯模糊"""
return cv2.GaussianBlur(image, kernel_size, 0)
def median_blur(image, kernel_size=15):
"""中值模糊 - 适合去除椒盐噪声"""
return cv2.medianBlur(image, kernel_size)
def bilateral_filter(image, d=9, sigma_color=75, sigma_space=75):
"""双边滤波 - 保持边缘"""
return cv2.bilateralFilter(image, d, sigma_color, sigma_space)
def custom_region_blur(image, regions=None):
"""自定义区域模糊
regions: list of tuples [(x, y, w, h), ...] 需要模糊的区域
"""
result = image.copy()
if regions:
for (x, y, w, h) in regions:
region = result[y:y+h, x:x+w]
blurred_region = gaussian_blur(region)
result[y:y+h, x:x+w] = blurred_region
return result
def batch_process_opencv(input_path, output_dir=None, blur_type='gaussian',
kernel_size=15, **kwargs):
"""OpenCV 批量处理"""
input_path = Path(input_path)
if output_dir is None:
output_dir = input_path if input_path.is_dir() else input_path.parent
output_dir = output_dir / "blurred_opencv"
output_dir.mkdir(exist_ok=True)
images = []
if input_path.is_file():
images.append(input_path)
elif input_path.is_dir():
for ext in ['*.jpg', '*.jpeg', '*.png', '*.bmp']:
images.extend(input_path.glob(ext))
for img_path in images:
print(f"处理: {img_path.name}")
# 读取图片
image = cv2.imread(str(img_path))
if image is None:
print(f" ✗ 无法读取")
continue
# 选择模糊方法
if blur_type == 'gaussian':
result = gaussian_blur(image, (kernel_size, kernel_size))
elif blur_type == 'median':
result = median_blur(image, kernel_size)
elif blur_type == 'bilateral':
result = bilateral_filter(image)
else:
print(f"未知模糊类型: {blur_type}")
continue
# 保存结果
output_path = output_dir / img_path.name
cv2.imwrite(str(output_path), result)
print(f" ✓ 已保存")
print(f"处理完成!输出目录: {output_dir}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("input", help="输入文件或文件夹")
parser.add_argument("-o", "--output", help="输出文件夹")
parser.add_argument("-t", "--type", choices=['gaussian', 'median', 'bilateral'],
default='gaussian', help="模糊类型")
parser.add_argument("-k", "--kernel", type=int, default=15, help="内核大小")
args = parser.parse_args()
batch_process_opencv(args.input, args.output, args.type, args.kernel)
if __name__ == "__main__":
main()
使用方法
安装依赖
# Python 方案需要的依赖 pip install Pillow numpy opencv-python # 方案二需要安装 ImageMagick # Ubuntu/Debian: sudo apt-get install imagemagick # macOS: brew install imagemagick
Python 脚本使用示例
# 基本用法 python blur_batch.py ./input_folder # 指定输出文件夹和模糊类型 python blur_batch.py ./input_folder -o ./output_folder -t gaussian -r 8 # 局部模糊(只模糊中心) python blur_batch.py ./input_folder -t center -r 10 --center-percent 0.4 # 递归处理子文件夹 python blur_batch.py ./input_folder --recursive
Bash 脚本使用
./blur_images.sh "./images" "./blurred_output" 8
功能特点
- 多种模糊类型:高斯模糊、均值模糊、运动模糊、中心区域模糊等
- 批量处理:支持文件夹批量处理
- 保留原图:默认不覆盖原图片
- 灵活输出:可以指定输出目录
- 递归处理:可以递归处理子文件夹
- 质量控制:可以调整输出图片质量
您可以根据需要选择最适合的方案,如果需要特殊功能(如人脸识别模糊、特定区域模糊等),我可以进一步修改脚本。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播