From 2a5ee3aa4663a7219e7130802d8f4cdc74b57447 Mon Sep 17 00:00:00 2001 From: muskit <15199219+muskit@users.noreply.github.com> Date: Tue, 22 Nov 2022 21:46:42 -0800 Subject: [PATCH] added image aspect ratio fixing --- .gitignore | 1 + requirements.txt | 1 + src/recrop.py | 31 +++++++++++++++++++++++++++++++ src/util.py | 2 ++ 4 files changed, 35 insertions(+) create mode 100644 src/recrop.py diff --git a/.gitignore b/.gitignore index 9f03741..b2dc1f0 100644 --- a/.gitignore +++ b/.gitignore @@ -146,6 +146,7 @@ cython_debug/ secrets.ini queue.txt img.png +img_adjusted.png src/img.png _queue_backup.txt _current_ttweet.txt diff --git a/requirements.txt b/requirements.txt index 2c972f5..aa9abf0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,4 +2,5 @@ nest-asyncio pytz tweet-capture tweepy +opencv-python git+https://github.com/muskit/twint_2022_fix.git \ No newline at end of file diff --git a/src/recrop.py b/src/recrop.py new file mode 100644 index 0000000..936d6cb --- /dev/null +++ b/src/recrop.py @@ -0,0 +1,31 @@ +import cv2 +from math import ceil + +# [3/4 --> 16/9] +def fix_aspect_ratio(img_file): + """Returns path to new image that better fits the aspect ratio of a single-image post.""" + img = cv2.imread(img_file) + img_ratio = img.shape[1]/img.shape[0] + print(f'{img_file}: {img_ratio}') + + if img_ratio > 16/9: + print('too wide; add height') + x, y = img.shape[1], (img.shape[1]*9)/16 + elif img_ratio < 3/4: + print('too skinny; add width') + x, y = (img.shape[0]*3)/4, img.shape[0] + else: + print('ratio is good; no need to readjust') + return img_file + + img_adjusted = cv2.copyMakeBorder( + img, + top=ceil((y-img.shape[0])/2), + bottom=ceil((y-img.shape[0])/2), + left=ceil((x-img.shape[1])/2), + right=ceil((x-img.shape[1])/2), + borderType=cv2.BORDER_REPLICATE + ) + adjusted_file = f'{img_file.rsplit(".", 1)[0]}_adjusted.png' + cv2.imwrite(filename=adjusted_file, img=img_adjusted) + return adjusted_file \ No newline at end of file diff --git a/src/util.py b/src/util.py index d4f9bd0..d8abd31 100644 --- a/src/util.py +++ b/src/util.py @@ -10,6 +10,7 @@ import twint import twapi from tweetcapture import TweetCapture +from recrop import fix_aspect_ratio import talent_lists # returns system path to this project, which is @@ -61,6 +62,7 @@ async def create_ttweet_image(ttweet): mode=4, night_mode=1 ) + img = fix_aspect_ratio(img) except: print('unable to create tweet image') traceback.print_exc()