Python PIL:使多边形外的像素透明

时间:2016-02-25 06:44:15

标签: python python-imaging-library

目前,为了使多边形透明,我正在做

img = Image.open("")
back = Image.new('RGBA', img.size)
back.paste(img)
poly = Image.new('RGBA', (512,512))
pdraw = ImageDraw.Draw(poly)
pdraw.rectangle([(10,10),(100,100)],
          fill=(255,255,255,200))

back.paste(poly, (0,0), mask=poly)
back.show()

但我想要的是我的多边形之外的所有区域,透明,并且多边形内的区域相同。基本上,与我现在所做的相反。

2 个答案:

答案 0 :(得分:1)

您可以使用ImageOps反转遮罩。

from PIL import ImageOps   

img = Image.open("")
back = Image.new('RGBA', img.size)
back.paste(img)
poly = Image.new('RGBA', (512,512))
pdraw = ImageDraw.Draw(poly)
pdraw.rectangle([(10,10),(100,100)],
          fill=(255,255,255,200))
inverted_poly = ImageOps.invert(poly)
back.paste(poly, (0,0), mask=inverted_poly)
back.show()

答案 1 :(得分:0)

#SET COORDINATE OF THE VISIBLE RECTANGLE
nottransparent_area=(10, 10, 200, 200)


#LOAD ORIGINAL IMAGE
image_original = Image.open('./original_image.png')

#START CREATE BLACK WHITE MASK

#HERE 0 MEANS BLACK, 
#LATER, PUTALPHA() USE THIS ZERO AS TRANSPARENT VALUE, NAMELY ALPHA 0
mask_grayscale = Image.new("L", image_original.size, 0)
mask_grayscale_img = ImageDraw.Draw(mask_grayscale)

#HERE 255 MEANS WHITE, 
#LATER, PUTALPHA() USE THIS 255 AS NOTTRANSPARENT VALUE, NAMELY ALPHA 255
mask_grayscale_img.rectangle(nottransparent_area, fill=255)

#END CREATE BLACK WHITE MASK



#Now, thanks to putalpha() we compose the mask and the original image.
image_out = Image.open('./original_image.png').convert('RGBA')
image_out.putalpha(mask_grayscale)
image_out.save('./image_out.png')

说明

  1. mask_grayscale_img 是 PUTHALPHA() 使用的黑白图像

  2. PUTALPHA() 将每个黑色像素设置为 ALPHA 0(透明)。

  3. PUTALPHA() 将每个白色像素设置为 ALPHA 255(不透明)。

  4. 阅读在绘图中创建 alpha 通道部分:https://note.nkmk.me/en/python-pillow-putalpha/

1

2