[英]Remove Image background and create a transparent Image using Python's PIL
我正在一個項目中,我需要刪除圖像的背景,我們僅有的信息是它是其中包含一些(一個或多個)對象的圖像,我需要刪除背景並進行它是透明的圖像。
這是一個示例圖像:
而且,這是我嘗試使用PIL的方法:
img = Image.open(url)
img = img.convert("RGBA")
datas = img.getdata()
print('Old Length is: {}'.format(len(datas)))
# print('Exisitng Data is as: {}'.format(datas))
newData = []
for item in datas:
# print(item)
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
print('New Length is: {}'.format(len(datas)))
img.show()
img.save("/Users/abdul/PycharmProjects/ImgSeg/img/new.png", "PNG")
print('Done')
它將與輸入相同的圖像保存為new.png
,未從圖像中刪除任何內容。
當我打印datas
和newData
它打印相同的值:
Old Length is: 944812
New Length is: 944812
提前致謝!
您正在過濾掉所有白色像素:
item[0] == 255 and item[1] == 255 and item[2] == 255
但這並不意味着:
所有白色像素(255, 255, 255)
屬於背景,
所有背景僅包含白色像素。
啟發式方法(部分適用於您的示例圖像)將增加背景像素定義的閾值:
if 50 <= item[0] <= 80 and 60 <= item[1] <= 100 and 80 <= item[2] < 140:
過濾掉更多像素。
您是否真的希望背景像素為白色也是要回答的問題。
另外,用於檢查過濾輸出的測試將無法進行,因為無論圖像的透明度如何,無論如何,這兩個圖像都將包含相同數量的像素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.