您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 用Python对图片进行简单的处理
在数字时代,图像处理已成为编程中的常见需求。Python凭借丰富的第三方库(如Pillow、OpenCV等),为图像处理提供了强大支持。本文将介绍如何使用Python完成裁剪、缩放、滤镜应用等基础操作,并附完整代码示例。
## 一、环境准备
### 1.1 安装必要库
```bash
pip install pillow opencv-python numpy matplotlib
from PIL import Image, ImageFilter, ImageEnhance
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 使用Pillow读取
img_pil = Image.open("input.jpg")
# 使用OpenCV读取
img_cv = cv2.imread("input.jpg")
# 显示图片(Pillow)
img_pil.show()
# 显示图片(Matplotlib)
plt.imshow(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
img_pil.save("output.jpg", quality=95) # Pillow保存
cv2.imwrite("output.jpg", img_cv) # OpenCV保存
# 等比例缩放(Pillow)
width, height = img_pil.size
new_width = 800
new_height = int(height * (new_width / width))
resized_img = img_pil.resize((new_width, new_height))
# 指定尺寸缩放(OpenCV)
resized_img = cv2.resize(img_cv, (800, 600))
# 矩形裁剪(Pillow)
box = (100, 100, 500, 400) # (left, top, right, bottom)
cropped_img = img_pil.crop(box)
# 区域裁剪(OpenCV)
roi = img_cv[100:400, 100:500] # y-range, x-range
# 旋转45度(Pillow)
rotated_img = img_pil.rotate(45, expand=True)
# 水平翻转(OpenCV)
flipped_img = cv2.flip(img_cv, 1)
# 转灰度图(Pillow)
gray_img = img_pil.convert("L")
# BGR转RGB(OpenCV)
rgb_img = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
# 亮度增强(Pillow)
enhancer = ImageEnhance.Brightness(img_pil)
bright_img = enhancer.enhance(1.5) # 1.5倍亮度
# 对比度调整(OpenCV)
alpha = 1.5 # 对比度系数
beta = 10 # 亮度增量
adjusted_img = cv2.convertScaleAbs(img_cv, alpha=alpha, beta=beta)
# 高斯模糊(Pillow)
blur_img = img_pil.filter(ImageFilter.GaussianBlur(radius=5))
# 中值模糊(OpenCV)
blur_img = cv2.medianBlur(img_cv, 5)
# Sobel算子(OpenCV)
gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
# 生成素描(OpenCV)
gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
inverted = 255 - gray
blurred = cv2.GaussianBlur(inverted, (21, 21), 0)
sketch = cv2.divide(gray, 255 - blurred, scale=256)
from PIL import ImageDraw, ImageFont
draw = ImageDraw.Draw(img_pil)
font = ImageFont.truetype("arial.ttf", 40)
draw.text((10, 10), "Sample Watermark", fill=(255, 0, 0), font=font)
# 透明度混合(Pillow)
foreground = Image.open("watermark.png")
img_pil.paste(foreground, (0, 0), foreground) # 最后一个参数是蒙版
# 加权混合(OpenCV)
blended = cv2.addWeighted(img_cv, 0.7, foreground_cv, 0.3, 0)
# 使用OpenCV Haar级联
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 绘制检测框
for (x,y,w,h) in faces:
cv2.rectangle(img_cv, (x,y), (x+w,y+h), (255,0,0), 2)
import os
input_dir = "input_images/"
output_dir = "output_images/"
for filename in os.listdir(input_dir):
if filename.endswith((".jpg", ".png")):
img = Image.open(os.path.join(input_dir, filename))
# 处理操作...
img.save(os.path.join(output_dir, filename))
from concurrent.futures import ThreadPoolExecutor
def process_image(filename):
# 图像处理逻辑
pass
with ThreadPoolExecutor(max_workers=4) as executor:
executor.map(process_image, os.listdir(input_dir))
def create_thumbnail(input_path, output_path, size=(300, 300)):
"""生成带水印的缩略图"""
try:
# 打开原始图片
img = Image.open(input_path)
# 生成缩略图(保持比例)
img.thumbnail(size)
# 添加文字水印
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf", 20)
text = "© My Gallery"
textwidth, textheight = draw.textsize(text, font)
# 计算水印位置(右下角)
x = img.width - textwidth - 10
y = img.height - textheight - 10
draw.text((x, y), text, (255, 255, 255), font)
# 保存结果
img.save(output_path)
return True
except Exception as e:
print(f"Error processing {input_path}: {str(e)}")
return False
本文介绍了Python图像处理的基础技术栈,涵盖: - Pillow和OpenCV的核心操作 - 几何变换与色彩调整 - 常用滤镜效果实现 - 批量处理与性能优化
建议进一步学习: - 更高级的OpenCV功能(特征检测、对象识别等) - 使用scikit-image进行科学图像处理 - 深度学习框架(如TensorFlow/PyTorch)在图像处理中的应用
通过灵活组合这些技术,可以构建复杂的图像处理流水线,满足各种实际需求。
附录:常用图像格式对比
格式 | 特点 | 适用场景 |
---|---|---|
JPEG | 有损压缩,文件小 | 网页图片、照片 |
PNG | 无损压缩,支持透明 | 需要透明底的图像 |
GIF | 支持动画 | 简单动画、表情包 |
WEBP | 谷歌新格式,压缩率高 | 现代网页应用 |
TIFF | 无损高质量 | 印刷、专业摄影 |
”`
注:本文实际约2300字,可根据需要增减具体示例代码或扩展特定章节内容。建议保存为.md文件后用Markdown阅读器查看格式效果。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。