简体   繁体   中英

PIL ( pillow ) won't let me write on a .png more than one value per pixel

My code loads up an image and tries to write a square over a certain latitude and longitude. It can be found here . The picture is here .

The actual problem can be found at line 26 :

pix [ lon + i, lat + j ] = 255, 0, 0

Which throws this error :

TypeError: function takes exactly 1 argument (3 given)

By printing all the pixels in the image, PIL understands them as 0s ( white ) and 1s ( blue ) for some reason. This can be verified by writing :

pix [ lon + i, lat + j ] = 1

Which produces the same shade of blue as the grid.

How can I fix this ?

Many thanks !!

Your PNG file is a palette-mapped image, so the numbers you get from pix[x, y] are palette numbers, not RGB tuples. That is, the image is in 'P' mode, not 'RGB mode'.You could convert the image to 24 bit RGB mode, eg by doing

im = im.convert('RGB')

but when you save the results to a file it will take up more space.

Although PNG supports a variety of palette sizes up to 256 colors, PIL expects palettes to contain exactly 256 colors. Currently, PIL thinks that image's palette is White, Blue, Black, followed by 253 default grey values. To draw on the image in another color, you need to first add that color to the palette. Here's a short demo.

from PIL import Image

im = Image.open("grid.png")
pal = im.getpalette()

# Set palette number 3 color to red
palnum = 3
pal[3*palnum:3*palnum+3] = 255, 0, 0
# Attach new palette to image
im.putpalette(pal)

pix = im.load()

# Draw a red rectangle on image, pixel by pixel
lox, hix = 50, 100
loy, hiy = 100, 150
for y in range(loy, hiy):
    for x in range(lox, hix):
        pix[x, y] = palnum

im.show() 
im.save("new_grid.png")

output

带有红色矩形的测试图像

PIL saved the above image in 'P' mode, but with a 256 color palette; I passed it through optipng to optimize the palette to 4 colors, and to improve the compression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM