《Python实现图像剪辑:从基础裁剪到高级滤镜处理》
核心内容:使用Pillow库实现基础图像剪辑功能
1. 引言
- 图像剪辑在社交媒体、电商、设计领域的应用场景
- 为什么选择Python(生态丰富、开发效率高)
2. 环境准备
python
# 安装依赖 |
pip install Pillow numpy opencv-python |
3. 基础图像剪辑操作
3.1 图像裁剪
python
from PIL import Image |
def crop_image(input_path, output_path, box): |
""" |
box: (left, upper, right, lower) 元组 |
""" |
with Image.open(input_path) as img: |
cropped = img.crop(box) |
cropped.save(output_path) |
# 示例:裁剪中间区域 |
img = Image.open("input.jpg") |
width, height = img.size |
crop_image("input.jpg", "output.jpg", (width//4, height//4, width*3//4, height*3//4)) |
3.2 调整尺寸与比例
python
def resize_image(input_path, output_path, size): |
with Image.open(input_path) as img: |
resized = img.resize(size, Image.LANCZOS) # 高质量重采样 |
resized.save(output_path) |
resize_image("input.jpg", "resized.jpg", (800, 600)) |
4. 高级图像处理
4.1 添加水印
python
def add_watermark(input_path, output_path, watermark_text, position=(10,10)): |
img = Image.open(input_path).convert("RGBA") |
watermark = Image.new("RGBA", img.size, (255,255,255,0)) |
draw = ImageDraw.Draw(watermark) |
draw.text(position, watermark_text, fill=(255,255,255,128), font=ImageFont.truetype("arial.ttf", 20)) |
merged = Image.alpha_composite(img, watermark) |
merged.convert("RGB").save(output_path) |
4.2 应用滤镜效果
python
import numpy as np |
from PIL import ImageFilter |
def apply_sepia_filter(input_path, output_path): |
img = Image.open(input_path) |
# 转换为numpy数组处理 |
arr = np.array(img) |
# 棕褐色滤镜矩阵 |
sepia_filter = np.array([ |
[0.393, 0.769, 0.189], |
[0.349, 0.686, 0.168], |
[0.272, 0.534, 0.131] |
]) |
sepia = np.dot(arr[...,:3], sepia_filter.T) |
sepia = np.clip(sepia, 0, 255).astype(np.uint8) |
Image.fromarray(sepia).save(output_path) |
5. 性能优化技巧
- 使用多线程处理批量图像
- 内存管理最佳实践(避免重复加载大图)
6. 总结
- 完整项目GitHub链接
- 扩展方向:OpenCV实现实时视频剪辑、TensorFlow图像风格迁移