Created
July 10, 2025 16:37
-
-
Save joedf/55d81869fdce34713e08785dc438be09 to your computer and use it in GitHub Desktop.
how to draw a transparent shape on an image in python with pillow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| from PIL import Image, ImageDraw | |
| # test how to draw a transparent shape on an image in python with pillow | |
| G_IMAGE_FILE = '~example.tif' | |
| def drawRect(): | |
| # https://pillow.readthedocs.io/en/latest/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.rectangle | |
| with Image.open(G_IMAGE_FILE) as im: | |
| draw = ImageDraw.Draw(im) | |
| # draw.line((0, 0) + im.size, fill=128) | |
| # draw.line((0, im.size[1], im.size[0], 0), fill=128) | |
| # rect properties | |
| rx = im.width / 2 | |
| ry = im.height / 2 | |
| rw = im.width * (1/2) | |
| rh = im.height * (1/3) | |
| # coords for rect bounding box | |
| rminx = rx - (rw/2) | |
| rmaxx = rx + (rw/2) | |
| rminy = ry - (rh/2) | |
| rmaxy = ry + (rh/2) | |
| rBox = ((rminx, rminy), (rmaxx, rmaxy)) | |
| rFill = (0, 255, 0, 90) # lime green with 50% alpha | |
| rOutline = (0, 0, 255, 255) # blue solid | |
| rLineWidth = 4 # px | |
| draw.rectangle(rBox, rFill, rOutline, rLineWidth) | |
| # write to stdout | |
| # im.save('~example.out.png', "PNG") | |
| im.show() | |
| def drawRect_alpha(): | |
| # https://www.reddit.com/r/learnpython/comments/u0960n/comment/i44fxxq/ | |
| # https://www.reddit.com/r/learnpython/comments/u0960n/comment/i44e8sd/ | |
| with Image.open(G_IMAGE_FILE) as img: | |
| img = img.convert("RGBA") # convert img to RGBA mode | |
| new = Image.new('RGBA', img.size, (255, 255, 255, 0)) | |
| draw = ImageDraw.Draw(new) | |
| draw.rectangle( | |
| [(img.width*.25, img.height*.25), (img.width*.75, img.height*.75)], | |
| fill=(0, 255, 0, 127), | |
| outline=(0, 0, 255, 192), # blue solid | |
| width=3 | |
| ) | |
| out = Image.alpha_composite(img, new) | |
| out.show() | |
| if __name__ == "__main__": | |
| # drawRect() | |
| drawRect_alpha() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment