Python实践——图片优化
我们在网上常常用到,让AI给图片加这样那样的特效,今天我就手把手教你几个用Python给自己的照片加特效的代码。
准备工作
想象Python是个大工具箱,我们得先装上处理图片的工具。打开你电脑的“终端”(Mac)或“命令提示符”(Windows),输入下面这个命令:
pip install pillow
按回车,等它安装完成就好了。如果看到“Successfully installed”的字样,就说明安装成功了!
如果安装不成功,可能是电脑里还没有Python。先去Python官网下载安装,然后对照网上的安装教程和使用教程,记得安装时勾选“Add Python to PATH”这个选项。
复古滤镜
from PIL import Image, ImageEnhance
# 第一步:打开你的照片
# 把 'my_photo.jpg' 改成你照片的实际名字
# 记得照片要和代码文件放在同一个文件夹里
image = Image.open('my_photo.jpg')
# 第二步:调整颜色,让照片看起来旧旧的
color_adjuster = ImageEnhance.Color(image)
old_style_photo = color_adjuster.enhance(0.5) # 数字越小颜色越淡
# 第三步:增加对比度,让明暗更分明
contrast_adjuster = ImageEnhance.Contrast(old_style_photo)
final_photo = contrast_adjuster.enhance(1.2)
# 第四步:保存你的作品
final_photo.save('old_style_photo.jpg')
print("搞定!看看文件夹里的 old_style_photo.jpg,是不是很有感觉?")
也试试把 0.5 改成 0.3 或者 0.8,看看效果有什么不同?
素描效果
from PIL import Image, ImageFilter, ImageOps
def make_sketch(photo_name):
"""把普通照片变成素描画"""
print(f"正在处理 {photo_name}...")
# 打开照片
img = Image.open(photo_name)
# 第一步:先变成黑白
black_white = img.convert('L')
# 第二步:颜色反转(黑变白,白变黑)
reversed_colors = ImageOps.invert(black_white)
# 第三步:稍微模糊一下
blurred = reversed_colors.filter(ImageFilter.BLUR)
# 第四步:混合两张图,做出铅笔素描的感觉
# 0.7是混合程度,可以调整
sketch_photo = Image.blend(black_white, blurred, 0.7)
# 保存
sketch_photo.save('sketch_style.jpg')
print("素描效果完成!保存为 sketch_style.jpg")
return sketch_photo
# 使用这个功能
make_sketch('my_photo.jpg')
这个效果特别适合人像照片,做出来像艺术照一样!
加漂亮相框
def add_photo_frame(photo_name, frame_color=(255, 200, 100)):
"""给照片加个相框"""
# 打开照片
img = Image.open(photo_name)
# 相框宽度,20像素
frame_size = 20
# 计算新图片大小(原图+相框)
new_width = img.width + frame_size * 2
new_height = img.height + frame_size * 2
# 创建新画布(相框颜色)
# frame_color是RGB颜色,比如(255,200,100)是金色
new_canvas = Image.new('RGB', (new_width, new_height), frame_color)
# 把原图放在新画布中央
new_canvas.paste(img, (frame_size, frame_size))
# 保存
new_canvas.save('photo_with_frame.jpg')
print("相框添加完成!")
return new_canvas
# 试试不同颜色的相框:
add_photo_frame('my_photo.jpg', (100, 150, 255)) # 蓝色相框
# add_photo_frame('my_photo.jpg', (255, 220, 150)) # 浅金色
# add_photo_frame('my_photo.jpg', (200, 255, 200)) # 浅绿色
切九宫格
def make_9grid(photo_name):
"""把一张照片切成九宫格"""
img = Image.open(photo_name)
# 决定切几行几列(3×3就是九宫格)
rows = 3
cols = 3
# 计算每小块的大小
block_width = img.width // cols
block_height = img.height // rows
print(f"每小块尺寸:{block_width}×{block_height}")
# 创建新图片用来展示效果
result = Image.new('RGB', (img.width, img.height))
# 切割并重新排列
for i in range(rows):
for j in range(cols):
# 计算切割位置
left = j * block_width
top = i * block_height
right = left + block_width
bottom = top + block_height
# 切出这一小块
small_block = img.crop((left, top, right, bottom))
# 贴到新图片上(按顺序贴就是原图,可以打乱顺序)
result.paste(small_block, (left, top))
result.save('9grid_photo.jpg')
print("九宫格效果完成!")
return result
# 使用:把'my_photo.jpg'换成你的照片名字
make_9grid('my_photo.jpg')
解决照片太暗或太亮的问题
这是最常见的问题,照片在室内拍的总感觉暗沉沉的
from PIL import Image, ImageEnhance
def fix_brightness(photo_name):
"""调整照片亮度"""
print(f"正在优化 {photo_name} 的亮度...")
# 打开照片
img = Image.open(photo_name)
# 创建一个亮度调整器
brightness_tool = ImageEnhance.Brightness(img)
# 调整亮度(1.0是原图,小于1变暗,大于1变亮)
# 通常1.2-1.5效果比较好,你可以多试试
brighter_img = brightness_tool.enhance(1.3)
# 保存
brighter_img.save('brightened_photo.jpg')
print("亮度调整完成!保存为 brightened_photo.jpg")
return brighter_img
# 使用:把'my_photo.jpg'换成你的照片名字
fix_brightness('my_photo.jpg')
模糊照片变清晰
from PIL import Image, ImageEnhance
def sharpen_photo(photo_name):
"""让照片更清晰"""
print(f"正在锐化 {photo_name}...")
img = Image.open(photo_name)
# 方法1:简单锐化(适合大多数情况)
sharpened = img.filter(ImageFilter.SHARPEN)
# 方法2:更强的锐化(如果照片真的很模糊)
# sharpened = img.filter(ImageFilter.UnsharpMask(radius=2, percent=150))
# 同时增加一点点对比度,让清晰度更明显
contrast_tool = ImageEnhance.Contrast(sharpened)
final_img = contrast_tool.enhance(1.05) # 只增加5%,很微妙
final_img.save('sharp_photo.jpg')
print("清晰度优化完成!保存为 sharp_photo.jpg")
return final_img
# 使用:把'my_photo.jpg'换成你的照片名字
sharpen_photo('my_photo.jpg')
智能优化
from PIL import Image, ImageEnhance
def auto_enhance(photo_name):
"""一键智能优化照片"""
print(f"正在智能优化 {photo_name}...")
img = Image.open(photo_name)
# 第一步:自动调整亮度(先判断照片是否偏暗)
# 计算平均亮度
grayscale = img.convert('L')
brightness = sum(grayscale.getdata()) / (img.width * img.height)
# 如果平均亮度低于128(0-255范围),说明偏暗
if brightness < 130:
brightness_tool = ImageEnhance.Brightness(img)
img = brightness_tool.enhance(1.3) # 调亮30%
print(f"检测到照片偏暗,已调亮")
# 第二步:增强颜色(但比手动调整保守)
color_tool = ImageEnhance.Color(img)
img = color_tool.enhance(1.2) # 保守的色彩增强
# 第三步:轻微增加对比度
contrast_tool = ImageEnhance.Contrast(img)
img = contrast_tool.enhance(1.08)
# 第四步:轻微锐化
img = img.filter(ImageFilter.SHARPEN)
img.save('auto_enhanced_photo.jpg')
print("智能优化完成!保存为 auto_enhanced_photo.jpg")
return img
# 使用:把'my_photo.jpg'换成你的照片名字
auto_enhance('my_photo.jpg')
背景虚化
让主体更突出,背景变模糊
from PIL import Image, ImageFilter
def selective_blur(photo_name, center_x=0.5, center_y=0.5, radius=0.3):
"""中心清晰,周围模糊的效果"""
img = Image.open(photo_name)
width, height = img.size
# 创建一个模糊版本
blurred = img.filter(ImageFilter.GaussianBlur(5))
# 创建一个蒙版(中间亮,周围暗)
from PIL import ImageDraw
mask = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(mask)
# 计算椭圆的中心位置
cx = int(width * center_x)
cy = int(height * center_y)
r = int(min(width, height) * radius)
# 画一个白色椭圆(中心区域)
draw.ellipse([cx-r, cy-r, cx+r, cy+r], fill=255)
# 模糊边缘过渡
mask = mask.filter(ImageFilter.GaussianBlur(20))
# 混合原图和模糊图
result = Image.composite(img, blurred, mask)
result.save(f'selective_blur_{photo_name}')
print("选择性模糊完成!中心清晰,周围模糊")
return result
# 使用:调整center_x, center_y让清晰区域对准主体
selective_blur('portrait.jpg', center_x=0.5, center_y=0.4)
上面就是我分享的一部分图片代码优化效果,至于优化后图片好不好看,建议使用图片去做大量测试,根据优化后的结果分析后再去调整代码里的参数,使它保证能够符合大部分人要求的,这样就能达到网上的效果了。

浙公网安备 33010602011771号