[英]How to change the background of an image using PIL?
我試圖找到如何使用 PIL 包在 Python 中刪除/更改灰度圖像的背景,但我失敗了。 我擁有的是一個具有白色背景的 RGB 圖像,我想加載它,調整大小,將背景從白色更改為黑色並保存。 到目前為止,我可以開始:
from PIL import Image
img = Image.open('my_picture.jpg').convert('LA')
# im1 = img.crop((left, top, right, bottom))
這給了我一個我想要的大小的灰度圖像,但現在我不知道如何更改背景。 我發現了一個非常好的帖子,使用cv2
從綠色 bg 中裁剪圖像,並直接設置背景,但我找不到 PIL。 有這樣的選擇嗎?
將圖像轉換為 RGB 並獲取數據。 然后按照步驟操作。
from PIL import Image
img = Image.open("test_image.jpg")
img = img.convert("RGB")
datas = img.getdata()
new_image_data = []
for item in datas:
if item[0] in list(range(190, 256)):
new_image_data.append((255, 204, 100))
else:
new_image_data.append(item)
img.putdata(new_image_data)
img.save("test_image_altered_background.jpg")
img.show()
你可以從 這里得到一些想法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.