Home > Software design >  Python imaging producing rectangular pixels instead of square pixels
Python imaging producing rectangular pixels instead of square pixels

Time:06-02

New to Python Imaging Library (PIL) but have noticed that generated pixels are rectangular and not a square. See images

Left red pixel is off Almost positive these pixels are rectangular

Pic 1: The left red pixel is clearly off (zoomed from 96x96 pixel image). Pic 2: All of the pixels seem to be rectangular (zoomed from 48x48 pixel image).

It looks like small images (< 20x20) seem to be ok (maybe they are rectangular but I can't notice) but as you go higher (> 30x30), the rectangular pixels are very noticeable.

I would love to know why this is happening and how to fix it? Is there a way to set pixel ratio/dimensions.

My code to simulate picture 2 is below:

import numpy as np
from PIL import Image

def random_rgb():
    """
    Creates tuple of random values between 0 - 255 inclusive.
    :return: tuple
    """
    r, g, b = np.random.randint(0, 256), np.random.randint(0, 256), np.random.randint(0, 256)
    rgb = (r, g, b)
    return rgb

def rainbow_bg(n):
    """
    Creates a list of lists of dimensions n x n
    :return: list
    """
    img = []
    for i in range(n):
        img.append([random_rgb() for i in range(n)])

    return img

def generate_image(pixels, dim, img_name):
    """
    Generates pixel image from list.
    :param pixels: list
    :param dim: tuple
    :param img_name: string
    :return:
    """

    arr = np.array(pixels, dtype=np.uint8)

    new_image = Image.fromarray(arr)
    new_image = new_image.resize(dim, resample=0)

    filename = f'{img_name}.png'
    new_image.save(filename)
    return


bg = rainbow_bg(48)
generate_image(pixels=bg, dim=(400, 400), img_name=f'background')

CodePudding user response:

I think that is a division problem because the dimension of your image can't fit the number of pixels you want to draw.

If you change your dimension to:

dim=(480, 480)

You'll get perfect squares

I'd probably use power of 2 for both "n" and dims, so you'll never have any problem

  • Related