零成本实现商品图换背景
这个同样是图片素材处理的付费功能,这期演示如果通过技术实现给商品图换背景。
首先这是我用opencv画的背景图
绘制背景图的代码
import cv2
import numpy as np
import datetime
import osdef create_product_background(width=800, height=800):# 创建渐变背景(从浅灰到白色)background = np.zeros((height, width, 3), dtype=np.uint8)# 基础浅灰色背景background[:] = (240, 240, 240)# 添加垂直渐变效果for y in range(height):alpha = y / heightbackground[y, :] = background[y, :] * (1 - alpha) + np.array([255, 255, 255]) * alpha# 添加中心阴影效果(模拟产品放置区域)shadow = np.zeros((height, width), dtype=np.uint8)cv2.ellipse(shadow, (width//2, height//2), (300, 300), 0, 0, 360, 100, -1)background = cv2.addWeighted(background, 1.0, cv2.cvtColor(shadow, cv2.COLOR_GRAY2BGR), 0.3, 0)# 添加装饰性网格线(增强专业感)for i in range(0, width, 50):cv2.line(background, (i, 0), (i, height), (220, 220, 220), 1)for j in range(0, height, 50):cv2.line(background, (0, j), (width, j), (220, 220, 220), 1)return background# 保存背景图
def save_background(background, output_dir='output', prefix='product_bg'):os.makedirs(output_dir, exist_ok=True)current_time = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')output_path = os.path.join(output_dir, f'{prefix}_{current_time}.jpg')cv2.imwrite(output_path, background)print(f'背景图已保存到: {output_path}')# 使用示例
if __name__ == '__main__':bg = create_product_background()save_background(bg)
print('背景图已保存到output/product_background.jpg')
我用前面抠图程序抠好的图
图片合成,将抠好的商品图放到前面画的背景图中间
import os
import datetime
import cv2
import numpy as np
from PIL import Imagedef process_foreground(foreground):"""处理前景图,包括调整大小和边缘平滑"""# 调整前景图大小max_size = (500, 500)foreground.thumbnail(max_size, Image.LANCZOS)# 转换为OpenCV格式进行处理foreground_cv = np.array(foreground)if foreground.mode == 'RGBA':alpha = foreground_cv[:,:,3]alpha = cv2.GaussianBlur(alpha, (5,5), 0)foreground_cv[:,:,3] = alphaelse:foreground_cv = cv2.GaussianBlur(foreground_cv, (3,3), 0)return Image.fromarray(foreground_cv)def main():try:# 定义输入输出路径变量background_path = os.path.join('output', 'product_bg1.jpg')foreground_path = os.path.join('output', 'sku1.png')output_dir = 'output'# 获取当前时间并格式化current_time = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')output_filename = f'result_{current_time}.jpg'# 打开并验证图片background = Image.open(background_path)foreground = Image.open(foreground_path)# 处理前景图processed_foreground = process_foreground(foreground)# 合成图片background.paste(processed_foreground, (170, 150), processed_foreground)# 确保输出目录存在os.makedirs(output_dir, exist_ok=True)# 保存结果output_path = os.path.join(output_dir, output_filename)background.save(output_path)print(f'图片已保存到: {output_path}')except FileNotFoundError as e:print(f'错误: 文件未找到 - {e}')except Exception as e:print(f'错误: 处理图片时发生异常 - {e}')if __name__ == '__main__':main()
合成好的效果,商品的边缘可以进一步羽化使其看起来更自然一些。