Python 具有透明背景的复原图像

Python 具有透明背景的复原图像,python,python-3.x,image-processing,python-imaging-library,Python,Python 3.x,Image Processing,Python Imaging Library,我正在尝试用Python(最好是Python 3)重新着色(切换颜色)。我有很多几何形状,有一个薄的黑色边框,白色填充,和一个透明的背景 下面是一个输入照片的示例 我想能够生成一个随机着色的圆圈 我从以下代码开始: start_color = (0,0,0) # white new_color = (255,255,255) # black # Open image shape_img = Image.open('circle_example.png').convert('RGB') shap

我正在尝试用Python(最好是Python 3)重新着色(切换颜色)。我有很多几何形状,有一个薄的黑色边框,白色填充,和一个透明的背景

下面是一个输入照片的示例

我想能够生成一个随机着色的圆圈

我从以下代码开始:

start_color = (0,0,0) # white
new_color = (255,255,255) # black
# Open image
shape_img = Image.open('circle_example.png').convert('RGB')
shape_data = np.array(shape_img)
# Replace start color with new color
shape_data[(shape_data == start_color).all(axis = -1)] = new_color
# Convert back to image
final_image = Image.fromarray(shape_data, mode='RGB')
final_image.show()
这导致:


有没有办法只替换白色的前端而不是透明的背景?(我知道在这个问题中透明背景是白色的,但是如果你看图片,它在圆圈周围是透明的。)

我确实找到了答案。我还需要导入alpha级别

import numpy as np
from PIL import Image
start_color = (0, 0, 0, 255) # white
new_color = (255, 255, 255, 255) # black
# Open image
shape_img = Image.open('circle_example.png').convert('RGBA')
shape_data = np.array(shape_img)
# Replace start color with new color
shape_data[(shape_data == start_color).all(axis = -1)] = new_color
# Convert back to image
final_image = Image.fromarray(shape_data, mode='RGBA')
final_image.show()

对于想要尝试此功能的任何人:将numpy作为np导入