Created
June 10, 2023 22:50
-
-
Save ogabrielguerra/bbf5ed8bafcebefe64f9ba2d6449d233 to your computer and use it in GitHub Desktop.
Workaround for Super Resolution Upscaling with any aspect ratio
This file contains 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 math | |
from PIL import Image, ImageChops | |
class AdjustImages: | |
@staticmethod | |
def get_next_height(height): | |
fullhd_height = 1080 | |
if height % fullhd_height == 0: | |
return height | |
elif height < fullhd_height: | |
return fullhd_height | |
else: | |
return (height // fullhd_height + 1) * fullhd_height | |
@staticmethod | |
def get_proportional_width_from_height(original_height, original_width): | |
height = AdjustImages.get_next_height(original_height) | |
return math.floor((original_width * height) / original_height) | |
@staticmethod | |
def get_16_9_width_from_height(height): | |
# Ratio of 1920 and 1080 (16:9) | |
return math.floor(height * 1.77777) | |
@staticmethod | |
def trim(image): | |
background = Image.new(image.mode, image.size, image.getpixel((0, 0))) | |
difference = ImageChops.difference(image, background) | |
border = difference.getbbox() | |
if border: | |
return image.crop(border) | |
# Get original image dimensions | |
image = Image.open('source.png') | |
image_size = image.size | |
image_width = image_size[0] | |
image_height = image_size[1] | |
# Get next height proportional to 16:9 aspect | |
new_height = AdjustImages.get_next_height(image_height) | |
# Get proportional width, considering original widht x height aspect ratio | |
new_width = AdjustImages.get_proportional_width_from_height(image_height, image_width) | |
# Create a new 16:9 image as a placeholder | |
placeholder_width = AdjustImages.get_16_9_width_from_height(new_height) | |
new_image = Image.new('RGB', (placeholder_width, new_height), (255, 255, 255)) | |
# Resize as a new image using the new dimensions | |
resized_image = image.resize((new_width, new_height)) | |
resized_image_size = resized_image.size | |
resized_image_width = resized_image_size[0] | |
# Get x position for pasting the resized image in the center of placeholder image | |
x = math.floor((placeholder_width - resized_image_width) / 2) | |
new_image.paste(resized_image, (x, 0)) | |
# Mock upscaling | |
super_image = new_image.resize((AdjustImages.get_16_9_width_from_height(new_height*2), new_height*2)) | |
super_image_size = super_image.size | |
super_image_width = super_image_size[0] | |
super_image_height = super_image_size[1] | |
cropped = AdjustImages.trim(super_image) | |
cropped.save("cropped.jpg", "JPEG") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment