[英]python PIL - check if image is transparent
我正在將圖像粘貼到另一個圖像上,在查看此問題后,我看到為了粘貼透明圖像,您需要執行
background = Image.open("test1.png")
foreground = Image.open("test2.png")
background.paste(foreground, (0, 0), foreground)
使用正常圖像,您應該這樣做
background = Image.open("test1.png")
foreground = Image.open("test2.png")
background.paste(foreground, (0, 0)) // difference here
我的問題是,如何檢查圖像是否透明,以便確定如何使用paste
方法(有或沒有最后一個參數)。
我提出了以下函數作為解決方案,它將 PIL Image
對象作為參數。 如果圖像使用索引顏色(例如在 GIF 中),它會獲取調色板中透明顏色的索引( img.info.get("transparency", -1)
)並檢查它是否在畫布中的任何位置使用( img.getcolors()
)。 如果圖像處於 RGBA 模式,那么大概它具有透明度,但它通過獲取每個通道的最小值和最大值( img.getextrema()
)進行雙重檢查,並檢查 alpha 通道的最小值是否低於 255。
def has_transparency(img):
if img.mode == "P":
transparent = img.info.get("transparency", -1)
for _, index in img.getcolors():
if index == transparent:
return True
elif img.mode == "RGBA":
extrema = img.getextrema()
if extrema[3][0] < 255:
return True
return False
檢查 alpha 透明層的圖像模式。 例如,RGB 沒有透明度,但 RGBA 有。
有關更多信息,請參閱https://pillow.readthedocs.io/en/latest/handbook/concepts.html 。
我使用 numpy 檢查 alpha 通道:
def im_has_alpha(img_arr):
'''
returns True for Image with alpha channel
'''
h,w,c = img_arr.shape
return True if c ==4 else False
使用它,假設pil_im
是你的枕頭圖像:
import numpy as np
has_transparency = im_has_alpha(np.array(pil_im))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.