簡體   English   中英

使用透明背景為圖像重新着色

[英]Recolor Image with Transparent Background

我正在嘗試使用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()

結果是:

final_image

有沒有辦法只替換白色的前列而不替換透明的背景? (我意識到在這個問題中透明背景顯示為白色,但是如果您查看圖片,則圓圈周圍是透明的。)

我確實找到了答案。 我還需要導入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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM