我做淘宝网站卖东西怎么激活,公司网站模板大全,服务器租用网站,江苏城乡建设部网站首页使用Pillow去除图像背景
安装依赖#xff1a;
pip install pillow
实现步骤#xff1a;
使用Pillow库加载图像#xff0c;并将其转换为RGBA模式#xff0c;以支持透明度。遍历图像的每个像素#xff0c;检查其红色、绿色和蓝色值是否都高于预设的阈值。对于被视为白色…使用Pillow去除图像背景
安装依赖
pip install pillow
实现步骤
使用Pillow库加载图像并将其转换为RGBA模式以支持透明度。遍历图像的每个像素检查其红色、绿色和蓝色值是否都高于预设的阈值。对于被视为白色的像素即RGB值均高于阈值的像素将其透明度设置为0完全透明。对于非白色像素保留其原始透明度值或不改变其透明度因为它们在原始图像中可能已经是部分透明或有其他透明度值。将修改后的图像保存为PNG格式以保留透明度信息。
示例代码
from PIL import Imagedef remove_image_bg_pil(input_path, output_path):img Image.open(input_path)img img.convert(RGBA)data img.getdata()threshold 240# 创建一个新的图片数据列表new_data []for item in data:# 将背景颜色设置为透明这里假设背景颜色为白色RGB值为(255, 255, 255)if item[0] threshold and item[1] threshold and item[2] threshold:new_data.append((255, 255, 255, 0))else:new_data.append(item)# 更新图片数据img.putdata(new_data)img.save(output_path, PNG)
使用OpenCV去除图像背景
安装依赖
pip install opencv-python
pip install numpy
实现步骤
创建RGBA图像将BGR图像转换为RGBA图像初始时Alpha通道设置为全不透明255。定义白色阈值设置一个阈值用于判断哪些像素是“白色”。创建掩码使用cv2.inRange函数创建一个掩码将白色像素标记为0透明其他像素标记为255不透明。反转掩码使用cv2.bitwise_not函数反转掩码只对白色像素进行透明处理。应用掩码到Alpha通道使用cv2.bitwise_and函数将掩码应用到Alpha通道使白色像素的Alpha通道变为0透明。
示例代码
import cv2
import numpy as npdef remove_image_bg_cv(input_path, output_path):# 读取图像img cv2.imread(input_path)b, g, r cv2.split(img)rgba cv2.merge((b, g, r, 255 * np.ones(b.shape, dtypeb.dtype)))# 定义白色阈值white_threshold 240# 创建一个掩码将白色像素标记为0透明其他像素标记为255不透明mask cv2.inRange(img, (white_threshold, white_threshold, white_threshold), (255, 255, 255))mask_inv cv2.bitwise_not(mask)cv2.imwrite(output2/mask.png, mask_inv)# 将掩码应用到Alpha通道rgba[:, :, 3] cv2.bitwise_and(rgba[:, :, 3], mask_inv)# 保存结果图像cv2.imwrite(output_path, rgba)