2

Currently, to make a polygon transparent I'm doing,

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()

But what I want is all the areas which is outside my polygon, to be transparent, and the area inside my polygon to be same. Basically, the reverse of what I'm doing now.

n00b
  • 1,549
  • 2
  • 14
  • 33

2 Answers2

1

You can use ImageOps to invert the mask.

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()
Ian Price
  • 7,416
  • 2
  • 23
  • 34
  • 1
    Note: ImageOps.invert(poly) won't work for RGB image. Had to use http://stackoverflow.com/questions/2498875/how-to-invert-colors-of-image-with-pil-python-imaging to resolve this. – n00b Feb 25 '16 at 10:08
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')

Explanation

  1. mask_grayscale_img is a black and white image used by PUTHALPHA()

  2. PUTALPHA() SET EVERY BLACK PIXEL TO ALPHA 0 (TRANSPARENT).

  3. PUTALPHA() SET EVERY WHITE PIXEL TO ALPHA 255 (NOTTRANSPARENT).

  4. Read the section Create alpha channel in drawing: https://note.nkmk.me/en/python-pillow-putalpha/

1

2

quine9997
  • 685
  • 7
  • 13