How to resize an image in python using Pillow like photoshops "hard edges" algorithm

Viewed 328

I am trying to downsize images with no form of resampling. I want it to fully maintain hard edges, and not add any blur / antialiasing whatsoever. Essentially, exactly like the photoshop "Hard edges" resampling mode. However, each and every one of Pillow's built in resampling methods gives me some kind of blur or aliasing effects.

The code im using currently is as follows

fileName = "big.jpg"

for i in range(6):
    filename16 = "small" + str(i) + ".jpg" 
    img = Image.open(fileName)

    img16 = img.resize((16, 16), resample=i)

    img16.save(filename16)

Original image: enter image description here

The results

Resized image to 16x16 by using;

enter image description here

Photoshop's "Nearest neighbour - Hard edges"

enter image description here

0 Pillow Nearest Neighbor

enter image description here

1 Pillow Lanczos

enter image description here

2 Pillow Linear

enter image description here

3 Pillow Bicubic

enter image description here

4 Pillow Box

enter image description here

5 Pillow Hamming

enter image description here

Or side by side, it can be clearly seen that all resampling methods change something about the image

How would i be able to get a result as that achieved by photoshop's "hard edges" option in Pillow? Thanks!

1 Answers

Make sure to save your images as .png files. .jpg files are lossy, and don't compress hard lines very well, since they are designed to store regular photos. If you look at the raw photo data, you will see a sharp transition between zones when you interpolated with NEAREST, but since the image is saved as .jpg, that all goes out the window.


Here's what the raw data is when you downsize with NEAREST:

enter image description here

Here's what the .jpg data looks like:

enter image description here

You can see the transition if filled with noise.

Related