0

我想用Python(最好是Python 3)在照片中重新着色(切换颜色)。我有很多几何形状,有黑色边框,白色填充和透明背景。带有透明背景的重新着色图像

这里是一个输入照片的例子。

White Circle

我希望能够生成随机颜色的圆圈。

我开始使用此代码:

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() 

这导致:

final_image

有没有办法只更换白色的前沿,而不是透明的背景是什么? (我知道透明背景在这个问题中出现白色,但是如果你看图片,它在圆周上是透明的。)

回答

0

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

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()