enlarge image (may be pixelate but not blurry)

Viewed 2217

I wrote a script that draws some images, usually not bigger than 50x50px. Then I want to display that image in a Tkinter window. But first I need to enlarge the image because 30x30px are too small for a user to see every single pixel generated by my script. So I wrote this:

multiplier = 4
image = np.full((height * multiplier, width * multiplier, 3), 0, dtype=np.uint8)

for r in range(height):
    for c in range(width):
        for i in range(multiplier):
            for j in range(multiplier):
                image[r * multiplier + i][c * multiplier + j] = original[r][c]

P.S. original was initialized the same way as image

Also I tried:

resize((width * multiplier ,height * multiplier), Image.ANTIALIAS)

but it's not an option, because it makes an image look blurry. So what would be the better solution?

Example image: enter image description here

4 Answers

I would suggest resizing with Nearest Neighbour resampling so you don't introduce any new, blurred colours - just ones already existing in your image:

import numpy as np
from PIL import Image

im = Image.open("snake.png").convert('RGB')
im = im.resize((200,200),resample=Image.NEAREST)
im.save("result.png")

enter image description here

You can go from a Pillow image to a numpy array with:

numpy_array = np.array(pillowImage)

and from numpy array to a Pillow image with:

pillow_image = Image.fromarray(numpyArray)

You could use PIL.Image/openCV and PIL.ImageFilter modules:

from PIL import Image, ImageFilter
import cv2

image = cv2.resize(image, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
image = Image.fromarray(image)

Here, fx and fy are the values you have to set yourself. Hope this helps :)

Here's a solution using just PIL:

from PIL import Image
multiplier = 4
original = Image.open("snake.png")
width, height = original.size
resized = original.resize((width * multiplier, height * multiplier), resample=0)
resized.save("resized.png")

Using resample=0 is the key.

Related