灰度图像转换
2025-07-03
很简单,提取通道就行
from PIL import Image import numpy as np def convert_to_grayscale_with_alpha(input_image_path, output_image_path): # 打开图像 img = Image.open(input_image_path).convert('RGBA') # 转换为 numpy 数组,方便处理 data = np.array(img) # 获取 RGB 和 Alpha 通道 r, g, b, a = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3] # 将 RGB 部分转换为灰度(按照加权平均) grayscale = 0.2989 * r + 0.5870 * g + 0.1140 * b # 创建新的 RGB 图像,使用灰度值替换原有的 RGB 值 data[:,:,0] = grayscale data[:,:,1] = grayscale data[:,:,2] = grayscale # 创建新的图像,保留 Alpha 通道 new_img = Image.fromarray(data) # 保存新的图像 new_img.save(output_image_path) print(f"灰度图像(带透明度)已保存为: {output_image_path}") # 输入和输出文件路径 input_image_path = "your_image_path.png" # 替换为你的原图路径 output_image_path = "grayscale_image_with_alpha.png" # 替换为你想保存的灰度图路径 convert_to_grayscale_with_alpha(input_image_path, output_image_path)
发表评论: