当前位置: 首页 > news >正文

零成本实现商品图换背景

这个同样是图片素材处理的付费功能,这期演示如果通过技术实现给商品图换背景。
首先这是我用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()

合成好的效果,商品的边缘可以进一步羽化使其看起来更自然一些。
在这里插入图片描述

http://www.lryc.cn/news/584034.html

相关文章:

  • 特征筛选步骤
  • 计算机视觉 之 数字图像处理基础
  • NAT技术(网络地址转换)
  • IPv4和IPv6双栈配置
  • CRT 不同会导致 fopen 地址不同
  • 飞书AI技术体系
  • Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
  • OSPF协议:核心概念与配置要点解析
  • 栈题解——有效的括号【LeetCode】两种方法
  • ACL协议:核心概念与配置要点解析
  • LlamaFactory Demo
  • 强缓存和协商缓存详解
  • SQL进阶:自连接的用法
  • 深度探索:实时交互与增强现实翻译技术(第六篇)
  • 【郑大二年级信安小学期】Day9:XSS跨站攻击XSS绕过CSRF漏洞SSRF漏洞
  • 医院多部门协同构建知识库-指南库-预测模型三维网络路径研究
  • 【C++】第十四节—模版进阶(非类型模版参数+模板的特化+模版分离编译+模版总结)
  • OSPF实验以及核心原理全解
  • vue引入应用通义AI大模型-(一)前期准备整理思路
  • Vue+Element Plus 中按回车刷新页面问题排查与解决
  • Scala实现网页数据采集示例
  • AI 智能体:开启自动化协作新时代
  • 2025.07.09华为机考真题解析-第三题300分
  • CentOs 7 MySql8.0.23之前的版本主从复制
  • 树莓派5+Ubuntu24.04 LTS ROS2 N10P镭神激光雷达 保姆级教程
  • ubuntu server配置静态IP
  • java(2025/7/10)
  • 【LeetCode 热题 100】19. 删除链表的倒数第 N 个结点——双指针+哨兵
  • 如何把Arduino IDE中ESP32程序bin文件通过乐鑫flsah_download_tool工具软件下载到ESP32中
  • 【音视频】HTTP协议介绍