Last active
May 21, 2021 01:51
-
-
Save rsomani95/3978cb827842cccf5329b1478ff7959e to your computer and use it in GitHub Desktop.
Operators for PIL Images for easily creating grid views and viewing multiple Images side by side.
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 fastcore.all as fastcore | |
import PIL | |
@fastcore.patch | |
def __or__(self: PIL.Image.Image, other: PIL.Image.Image): | |
"Horizontally stack two PIL Images" | |
assert isinstance(other, PIL.Image.Image) | |
widths, heights = zip(*(i.size for i in [self, other])) | |
new_img = PIL.Image.new("RGB", (sum(widths), max(heights))) | |
x_offset = 0 | |
for img in [self, other]: | |
new_img.paste(img, (x_offset, 0)) | |
x_offset += img.size[0] | |
return new_img | |
@fastcore.patch | |
def __floordiv__(self: PIL.Image.Image, other: PIL.Image.Image): | |
"Vertically stack two PIL Images" | |
assert isinstance(other, PIL.Image.Image) | |
widths, heights = zip(*(i.size for i in [self, other])) | |
new_img = PIL.Image.new("RGB", (max(widths), sum(heights))) | |
y_offset = 0 | |
for img in [self, other]: | |
new_img.paste(img, (0, y_offset)) | |
y_offset += img.size[1] | |
return new_img |
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 requests, io | |
# Download Test Img | |
tmp_fpath = "/tmp/a-wrinkle-in-time-filmgrab.jpg" | |
req = requests.get("https://film-grab.com/wp-content/uploads/photo-gallery/wrinkle046.jpg?bwg=1551280654", stream=True) | |
img = Image.open(io.BytesIO(req.content)) | |
# USAGE | |
img | img # hstack | |
img // img # vstack | |
(img | img) // (img | img) # 2x2 grid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment