![](/img/trans.png)
[英]How to convert binary image to rgba image with transparent background in opencv
[英]Pillow/NP: how to convert transparent mapped (indexed) PNG to RGBA when transparency is in binary format
我需要將透明映射(索引)PNG 轉換為 RGBA。 通常透明度由一種單一顏色定義,以下基於 Pillow 和 Numpy 的代碼將起作用:
from PIL import Image
import numpy as np
indexed = Image.open("mapped_image.png")
if indexed.mode == "P":
is_transparent = False
# check if transparent
transp_byte = indexed.info.get("transparency", -1)
for _, index in indexed.getcolors():
if index == transp_byte:
is_transparent = True
break
# convert indexed image to Numpy array
indexed_as_np = np.asarray(indexed)
# convert indexed image to RGB
image = indexed.convert("RGB")
# if transparency is confirmed then create the mask
if is_transparent:
mask = np.zeros(indexed_as_np.shape, dtype="uint8")
mask[indexed_as_np != transp_byte] = 255
# add mask to rgb image
mask = Image.fromarray(mask)
image.putalpha(mask)
elif indexed.mode == 'PA':
image = indexed.convert("RGBA")
我的問題是我必須管理透明度由多個值定義的圖像,實際上是一個二進制值。 我在這種情況下 transp_byte 變成了:
b'\x00\x0e\x19#.8BLVq\x8e\x80`\x9a\xfe\x17.\xb7F\xd2\xea\xfd\xfe`\xfe\xdf\x9d\x86\xd1\xc0\xd9|\xbe\xa6\xa4\xfdt\xc2\x8a'
我應該如何將此類二進制信息轉換為有效的掩碼?
實際上,答案比預期的要簡單,因為 Pillow 已經包含了這樣的功能。 下面的代碼解決了這個問題,並簡化了很多我原來的代碼:
from PIL import Image
indexed = Image.open("mapped_image.png")
if indexed.mode == "P":
# check if transparent
is_transparent = indexed.info.get("transparency", False)
if is_transparent is False:
# if not transparent, convert indexed image to RGB
image = indexed.convert("RGB")
else:
# convert indexed image to RGBA
image = indexed.convert("RGBA")
elif indexed.mode == 'PA':
image = indexed.convert("RGBA")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.