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