Python 图像处理实战:生成手绘图、证件照与九宫格
Python 图像处理库可实现多种图片自动化处理功能。本文介绍了利用 Pillow 和 NumPy 将照片转换为手绘风格的方法;使用 RemoveBg 接口实现证件照抠图换底;通过 MyQR 库生成带背景图的二维码;利用 WordCloud 库制作词云图;以及编写脚本将单张图片分割为朋友圈九宫格。内容涵盖代码示例与关键参数说明,适合初学者参考实践。

Python 图像处理库可实现多种图片自动化处理功能。本文介绍了利用 Pillow 和 NumPy 将照片转换为手绘风格的方法;使用 RemoveBg 接口实现证件照抠图换底;通过 MyQR 库生成带背景图的二维码;利用 WordCloud 库制作词云图;以及编写脚本将单张图片分割为朋友圈九宫格。内容涵盖代码示例与关键参数说明,适合初学者参考实践。

Python 拥有强大的生态库,在图像处理领域表现尤为出色。通过 Pillow、NumPy、WordCloud 等库,我们可以实现从基础格式转换到复杂视觉效果生成的多种功能。本文详细介绍五个实用的图像处理案例,涵盖手绘风格转换、证件照制作、艺术二维码、词云生成及九宫格切图,并提供完整的代码示例与逻辑解析。
在开始之前,请确保已安装 Python 3.x 环境,并通过 pip 安装以下依赖库:
pip install pillow numpy wordcloud myqr removebg
许多软件支持将照片转换为素描或手绘风格,利用 Python 的 Pillow 和 NumPy 库,我们可以自定义算法实现更灵活的批量转换。
该算法的核心思想是利用图像灰度值的梯度来模拟光照下的阴影效果。具体步骤如下:
# -*- coding: UTF-8 -*-
from PIL import Image
import numpy as np
# 配置路径
original_image_path = "input.jpg"
handdrawn_image_path = "output_handdrawn.jpg"
try:
# 加载原图并转换为灰度模式
img = Image.open(original_image_path).convert('L')
a = np.asarray(img).astype('float')
depth = 10.0
# 计算图像灰度的梯度值
grad = np.gradient(a)
grad_x, grad_y = grad
# 调整梯度幅度
grad_x = grad_x * depth / 100.0
grad_y = grad_y * depth / 100.0
# 计算归一化因子
A = np.sqrt(grad_x**2 + grad_y**2 + 1.)
uni_x = grad_x / A
uni_y = grad_y / A
uni_z = 1.0 / A
# 定义光源角度(弧度)
vec_el = np.pi / 2.2 # 俯仰角
vec_az = np.pi / 4.0 # 方位角
# 计算光源向量分量
dx = np.cos(vec_el) * np.cos(vec_az)
dy = np.cos(vec_el) * np.sin(vec_az)
dz = np.sin(vec_el)
# 计算光照强度
b = 255 * (dx * uni_x + dy * uni_y + dz * uni_z)
# 裁剪数据至有效范围 [0, 255]
b = np.clip(b, 0, 255).astype('uint8')
# 重构图像
im = Image.fromarray(b)
im.save(handdrawn_image_path)
print(f'成功生成手绘图:{handdrawn_image_path}')
except FileNotFoundError:
print("错误:未找到指定的输入图片文件")
except Exception as e:
print(f"处理过程中发生错误:{e}")
此脚本可轻松扩展为批量处理模式,遍历文件夹中的所有图片进行转换。
证件照通常需要特定尺寸和纯色背景。本例演示如何使用 Pillow 调整尺寸,并结合 RemoveBg 接口实现智能抠图换底。
(255, 255, 255) 代表白色。# encoding=utf-8
from PIL import Image
from removebg import RemoveBg
# 替换为你的真实 API Key
API_KEY = 'YOUR_API_KEY_HERE'
LOG_FILE = 'error.log'
def change_bgcolor(file_in, file_out, api_key, color):
'''
去除背景并填充指定颜色
:param file_in: 输入图片路径
:param file_out: 输出图片路径
:param api_key: RemoveBg API Key
:param color: 背景颜色元组 (R, G, B)
'''
if not api_key or api_key == 'YOUR_API_KEY_HERE':
raise ValueError("请先设置有效的 API Key")
rmbg = RemoveBg(api_key, LOG_FILE)
try:
# 执行抠图
rmbg.remove_background_from_img_file(file_in)
# 获取无背景图片路径
base_name = file_in.split('.')[0]
ext = file_in.split('.')[-1]
no_bg_path = f"{base_name}_no_bg.{ext}"
no_bg_image = Image.open(no_bg_path)
x, y = no_bg_image.size
# 创建新画布
new_image = Image.new('RGBA', no_bg_image.size, color=color)
# 合成图片
new_image.paste(no_bg_image, (0, 0), no_bg_image)
new_image.save(file_out)
print(f'背景更换完成:{file_out}')
except Exception as e:
print(f'抠图失败:{e}')
def change_size():
image = Image.(file_in)
resized_image = image.resize((width, height), Image.LANCZOS)
resized_image.save(file_out)
()
__name__ == :
input_file =
output_file =
bg_color = (, , )
change_bgcolor(input_file, output_file, API_KEY, bg_color)
标准二维码较为单调,MyQR 库允许我们在二维码中心嵌入图片,增加视觉吸引力。
安装后,既可在命令行直接运行,也可在 Python 脚本中调用。
myqr https://www.example.com -p logo.png -c
参数说明:
https://...: 目标链接。-p: 指定要嵌入的图片路径。-c: 开启彩色模式。from myqr import run
run(
url='https://www.example.com',
version=1,
level='H',
picture='logo.png',
colored=True,
save_name='art_qr.png'
)
此方法生成的二维码不仅美观,且具备较高的容错率,适合海报设计或社交媒体分享。
词云图能直观展示文本数据的关键词分布,常用于数据分析报告或情感分析可视化。
from wordcloud import WordCloud
from PIL import Image
import numpy as np
# 假设 wordlist 是分词后的列表,例如 ['Python', '编程', '数据处理']
wordlist = ['Python', '图像处理', '自动化', 'Pillow', 'Numpy', '开发', '效率']
def generate_word_cloud(word_list, width=900, height=600, bg_color='white', save_path='wordcloud.png'):
# 加载遮罩图片(可选,如哪吒轮廓)
# mask_array = np.array(Image.open('mask.png'))
wc = WordCloud(
width=width,
height=height,
background_color=bg_color,
# mask=mask_array, # 启用遮罩
max_words=300,
font_path='./fonts/simhei.ttf', # 必须指定中文字体路径,否则乱码
collocations=False,
min_font_size=10,
max_font_size=100,
random_state=42
)
# 生成词云
wc.generate(' '.join(word_list))
# 显示图片
# wc.show()
# 保存图片
wc.to_file(save_path)
print(f'词云图已保存至:{save_path}')
if __name__ == '__main__':
generate_word_cloud(wordlist)
注意:生成中文词云时,务必下载对应的 .ttf 字体文件(如黑体、宋体)并正确配置 font_path 路径。
朋友圈九宫格是将一张大图分割为 9 张小图的技术需求。由于原始图片可能非正方形,需先进行填充处理。
# encoding=utf-8
from PIL import Image
import os
def fill_image(image):
"""将图片填充为正方形"""
width, height = image.size
new_length = max(width, height)
new_image = Image.new(image.mode, (new_length, new_length), color='white')
# 居中粘贴
if width > height:
new_image.paste(image, (0, int((new_length - height) / 2)))
else:
new_image.paste(image, (int((new_length - width) / 2), 0))
return new_image
def cut_image(image):
"""将图片切割成九宫格"""
width, height = image.size
item_width = int(width / 3)
box_list = []
for i in range(0, 3):
for j in range(0, 3):
box = (
j * item_width,
i * item_width,
(j + 1) * item_width,
(i + 1) * item_width
)
box_list.append(box)
image_list = [image.crop(box) for box in box_list]
return image_list
def save_images(image_list, output_dir='./grid_output'):
"""保存图片"""
os.path.exists(output_dir):
os.makedirs(output_dir)
index =
image image_list:
filename = os.path.join(output_dir, )
image.save(filename, )
index +=
()
__name__ == :
file_path =
os.path.exists(file_path):
image = Image.(file_path)
square_image = fill_image(image)
grid_list = cut_image(square_image)
save_images(grid_list)
:
()
本文展示了 Python 在图像处理领域的五种典型应用场景。通过组合不同的库,开发者可以快速构建出具有实用价值的工具。这些技术不仅适用于个人娱乐,也可集成到企业级应用中,提升工作效率。建议读者在实际项目中根据需求灵活调整参数,并注意处理异常情况和文件路径兼容性。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online