
背景需求
用通义万相把虚拟人物照片转成简笔画线条
【教学类-97-10】20251126虚拟人物照片转简笔画效果
https://mp.csdn.net/mp_blog/creation/editor/155297482
我想试试用Python模拟PS的功能将人物照片批量转为简笔画线条效果。

一、用黑白化方式提取图像
'''
对“切边原图”操作,制作白色斑点狗——黑白化+背景透明+切边+统一大小
豆包,阿夏
20251117
'''
import os
from PIL import Image
import numpy as np
def convert_to_pure_bw(image_path, output_path, threshold=128):
"""
将图片转为纯黑白两色(黑色0,0,0和白色255,255,255)
参数:
image_path: 输入图片路径
output_path: 输出图片路径
threshold: 二值化阈值
"""
try:
img = Image.open(image_path)
img = img.convert('L') # 转为灰度图
# 二值化处理
binary_img = img.point(lambda x: 0 if x < threshold else 255, '1')
binary_img = binary_img.convert('RGB') # 转回RGB模式
# 保存黑白图片
binary_img.save(output_path)
print(f"黑白图生成: {os.path.basename(image_path)}")
return output_path
except Exception as e:
print(f"处理图片 {image_path} 时出错: {str(e)}")
return None
def crop_transparent_edges(image, margin=0):
"""
裁剪掉图片的透明边缘,并保留指定的间距
参数:
image: PIL Image对象(RGBA模式)
margin: 要保留的间距(磅/像素)
返回:
裁剪后的PIL Image对象
"""
# 转换为numpy数组
data = np.array(image)
# 获取alpha通道
alpha = data[:, :, 3]
# 找到非透明像素的位置
non_transparent = np.where(alpha > 0)
if len(non_transparent[0]) == 0:
# 如果全是透明像素,返回原图
return image
# 获取非透明区域的边界
top = np.min(non_transparent[0])
bottom = np.max(non_transparent[0])
left = np.min(non_transparent[1])
right = np.max(non_transparent[1])
# 添加间距
top = max(0, top - margin)
bottom = min(image.height - 1, bottom + margin)
left = max(0, left - margin)
right = min(image.width - 1, right + margin)
# 裁剪图片
cropped_image = image.crop((left, top, right + 1, bottom + 1))
return cropped_image
def make_background_transparent(bw_image_path, output_path, tolerance=30, margin=0):
"""
将黑白图片的白色背景变为透明并裁剪透明边缘
参数:
bw_image_path: 黑白图片路径
output_path: 输出图片路径
tolerance: 颜色容差,控制背景识别的灵敏度
margin: 裁剪后保留的间距(磅/像素)
"""
# 打开黑白图片并转换为RGBA模式
with Image.open(bw_image_path) as img:
# 转换为RGBA模式
img = img.convert('RGBA')
# 获取图片数据
data = np.array(img)
red, green, blue, alpha = data.T
# 创建白色背景掩码:判断像素是否为白色(在容差范围内)
white_mask = (
(red >= 255 - tolerance) & (red <= 255) &
(green >= 255 - tolerance) & (green <= 255) &
(blue >= 255 - tolerance) & (blue <= 255)
)
# 将白色背景像素的alpha通道设为0(透明)
data[white_mask.T] = (255, 255, 255, 0)
# 转换回Image
result = Image.fromarray(data)
# 裁剪透明边缘并保留间距
cropped_result = crop_transparent_edges(result, margin)
# 保存结
540


简笔画效果&spm=1001.2101.3001.11974&articleId=155377694&d=1&t=3&u=468480efe9ff4d50bbf7385c70187a48)

被折叠的 条评论
为什么被折叠?



