Skip to content

Instantly share code, notes, and snippets.

@BilHim
Last active March 16, 2024 16:20
Show Gist options
  • Select an option

  • Save BilHim/3ab19214ca19cc1308414fb317ebb6bf to your computer and use it in GitHub Desktop.

Select an option

Save BilHim/3ab19214ca19cc1308414fb317ebb6bf to your computer and use it in GitHub Desktop.
import numpy as np
from PIL import Image
# Import image and get its dimensions
image = Image.open('image.jpg')
width, height = image.size
# Create a new empty image
new_width, new_height = 480, 320
scaled_image = Image.new(image.mode, (new_width, new_height), 'white')
# These guys will help us
scale_x = new_width/width
scale_y = new_height/height
# Fill in every pixel in the scaled image
for y in range(new_height):
for x in range(new_width):
pixel = magic # Here magic happens
scaled_image.putpixel((x, y), pixel)
# Save it
scaled_image.save('scaled_image.jpg')
@mihirpatil37
Copy link

mihirpatil37 commented May 12, 2022

Hello Sir,
I am Mihir, I am a student. I was trying to understand this code but I got stuck on magic, could you be nice and please tell me what is magic and how it works.

@BilHim
Copy link
Author

BilHim commented May 12, 2022

Hello Sir, I am Mihir, I am a student. I was trying to understand this code but I got stuck on magic, could you be nice and please tell me what is magic and how it works.

Helllo Mihir!
The "magic" part is just a placeholder for the code that is supposed to generate the scaled image.

In the example of nearest neighbors interpolation the code would look something like this:

for y in range(new_height):
    for x in range(new_width):
        x_nearest = int(np.round(x/scale_x))
        y_nearest = int(np.round(y/scale_y))
        pixel = image.getpixel((x_nearest, y_nearest))

        scaled_image.putpixel((x, y),  pixel)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment