Using PIL to draw individual pixels, but the image is blurry

Viewed 14

I am trying to create an image made up of coloured squares. I only need each square to be one pixel large, as it is just a single block colour. However, when I use this code, the image generated is extremely blurry. Is there anyway to make the boarders sharp?

def fancycolnw2(seq,m):
    data=numbwall(seq,m)
    #print(data)
    for i in range(len(data)):
        for j in range(len(data[i])):
            if data[i][j]==' ':
                data[i][j]=-1
    im = Image.new('RGBA', (len(data[0]),len(data))) # create the Image of size 1 pixel 
    #print(data)
    for i in range(len(data)-1):
        for j in range(len(data[i])-1):    
            #print(i,j)
            if data[i][j]==-1:
                im.putpixel((j,i), ImageColor.getcolor('black', 'RGBA'))
            if data[i][j]==0:
                #print('howdy')
                im.putpixel((j,i), ImageColor.getcolor('red', 'RGBA'))
            if data[i][j]==1:
                im.putpixel((j,i), ImageColor.getcolor('blue', 'RGBA'))
            if data[i][j]==2:
                im.putpixel((j,i), ImageColor.getcolor('grey', 'RGBA'))
    im.show()
    im.save('simplePixel.png') # or any image format

The result I get looks like this: Image

It is the correct image, I just wish the boundaries between pixels were sharp. Any help would be greatly appreciated!

1 Answers

The image is perfectly sharp, but rather small. I suspect that you are "zooming in" to view it clearer, and that whatever program you are zooming with is filtering the image, because with most images this looks better. You need to find a viewing program that uses "nearest neighbour" resampling when zooming in, or generate a larger image to start with, for example by setting a 4-by-4 pixel block rather than individual pixels.

(Also, the code says "# or any other image format". Don’t use JPEG for this, as the lossy compression will likely wreck your image.)

Related