def get_none_img(img):
"""
将绿幕图片抠成透明背景图片
:return:
"""
# todo 读取并转换图片格式
_, ext = os.path.splitext(img)
opencv = cv2.imread(os.path.join(IMAGES_ABS_PATH, img))
hsv = cv2.cvtColor(opencv, cv2.COLOR_RGB2HSV)
# todo 指定绿色范围,60表示绿色,我取的范围是-+10
minGreen = np.array([30, 70, 70])
maxGreen = np.array([80, 255, 255])
# todo 确定绿色范围
mask = cv2.inRange(hsv, minGreen, maxGreen)
# todo 确定非绿色范围
mask_not = cv2.bitwise_not(mask)
# todo 通过掩码控制的按位与运算锁定绿色区域
green = cv2.bitwise_and(opencv, opencv, mask=mask)
# todo 通过掩码控制的按位与运算锁定非绿色区域
green_not = cv2.bitwise_and(opencv, opencv, mask=mask_not)
# todo 拆分为3通道
b, g, r = cv2.split(green_not)
# todo 合成四通道
bgra = cv2.merge([b, g, r, mask_not])
# todo 保存带有透明通道的png图片,有了这种素材之后,就可以给这张图片替换任意背景了
cv2.imwrite(f'./caches/image1/{_}.png', bgra)
Pillow改图片指定范围内颜色
from PIL import Image
import numpy as np
import time
# 打开图片
image_path = r'C:\Users\123\Desktop\1.png' # 替换为你的图片路径
image = Image.open(image_path)
# 将图片转换为 RGB 格式(如果图片是灰度或其他格式)
image = image.convert('RGB')
# 将图片转换为 NumPy 数组
rgb_array = np.array(image)
print(rgb_array.tolist())
# 定义要替换的 RGB 范围
lower_bound = np.array([8, 16, 39]) # 最小的 RGB 值
upper_bound = np.array([8, 16, 39]) # 最大的 RGB 值
# 创建一个布尔掩码
mask = np.all((rgb_array >= lower_bound) & (rgb_array <= upper_bound), axis=-1)
# 创建一个新的数组并赋值
new_rgb_array = rgb_array.copy()
replacement_value = np.array([255, 0, 0]) # 要替换成的固定值
new_rgb_array[mask] = replacement_value
# 创建新的 Image 对象
new_image = Image.fromarray(new_rgb_array)
# 保存结果并覆盖原图
new_image.save(image_path)
print("替换完成并覆盖原图!")
改为透明
from PIL import Image
import numpy as np
# 打开图片
image_path = 'path_to_your_image.jpg' # 替换为你的图片路径
image = Image.open(image_path)
# 将图片转换为 RGBA 格式
image = image.convert('RGBA')
# 将图片转换为 NumPy 数组
rgba_array = np.array(image)
# 定义要设为透明的 RGB 范围
lower_bound = np.array([100, 0, 0]) # 最小的 RGB 值
upper_bound = np.array([200, 100, 100]) # 最大的 RGB 值
# 创建一个布尔掩码
mask = np.all((rgba_array[:, :, :3] >= lower_bound) & (rgba_array[:, :, :3] <= upper_bound), axis=-1)
# 将 alpha 通道设为 0(透明)
rgba_array[mask, 3] = 0
# 创建新的 Image 对象
new_image = Image.fromarray(rgba_array, mode='RGBA')
# 保存结果
new_image.save('output_image.png') # 输出为 PNG 格式以支持透明度
print("指定区域已设置为透明并保存为 output_image.png!")