Skip to content

Instantly share code, notes, and snippets.

@wibus-wee
Created August 27, 2025 03:47
Show Gist options
  • Select an option

  • Save wibus-wee/6126116cfa6e812d2bcf0854c07b66aa to your computer and use it in GitHub Desktop.

Select an option

Save wibus-wee/6126116cfa6e812d2bcf0854c07b66aa to your computer and use it in GitHub Desktop.
from PIL import Image
def extract_red_remove_white_black(image_path, output_path, make_transparent=True):
"""
提取图片中的红色,去掉白色和黑色
:param image_path: 输入图片路径
:param output_path: 输出图片路径
:param make_transparent: 是否创建透明背景
"""
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
width, height = img.size
if make_transparent:
new_img = Image.new('RGBA', (width, height), (0, 0, 0, 0)) # 透明背景
else:
new_img = Image.new('RGB', (width, height), (255, 255, 255)) # 白色背景
for x in range(width):
for y in range(height):
r, g, b = img.getpixel((x, y))
if r > 150 and g < 100 and b < 100 and not (r > 240 and g > 240 and b > 240) and not (r < 15 and g < 15 and b < 15):
if make_transparent:
new_img.putpixel((x, y), (r, g, b, 255)) # 红色像素不透明
else:
new_img.putpixel((x, y), (r, g, b)) # 普通RGB模式
else:
if make_transparent:
new_img.putpixel((x, y), (0, 0, 0, 0)) # 非红色像素设为透明
# 如果不是透明模式,不需要处理其他像素(保持默认背景)
if make_transparent and output_path.lower().endswith(('.jpg', '.jpeg')):
output_path = output_path.rsplit('.', 1)[0] + '.png'
print(f"透明背景图片已自动保存为PNG格式: {output_path}")
else:
print(f"处理完成,结果保存到: {output_path}")
new_img.save(output_path)
if __name__ == "__main__":
input_image = "input.png" # 替换为你的输入图片路径
output_image = "output_transparent.png" # 输出为透明背景的PNG文件
extract_red_remove_white_black(input_image, output_image, make_transparent=True)
# output_opaque = "output_opaque.png"
# extract_red_remove_white_black(input_image, output_opaque, make_transparent=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment