简体   繁体   English

PIL(枕头)不会让我在 .png 上写每个像素超过一个值

[英]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 :实际问题可以在第 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.通过打印图像中的所有像素,PIL 出于某种原因将它们理解为 0(白色)和 1(蓝色)。 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.您的 PNG 文件是调色板映射图像,因此您从pix[x, y]获得的数字是调色板编号,而不是 RGB 元组。 That is, the image is in 'P' mode, not 'RGB mode'.You could convert the image to 24 bit RGB mode, eg by doing也就是说,图像处于“P”模式,而不是“RGB 模式”。您可以将图像转换为 24 位 RGB 模式,例如通过执行

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.尽管 PNG 支持多种调色板大小,最多 256 色,但 PIL 期望调色板恰好包含 256 色。 Currently, PIL thinks that image's palette is White, Blue, Black, followed by 253 default grey values.目前,PIL 认为图像的调色板是白色、蓝色、黑色,然后是 253 个默认灰度值。 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; PIL 以“P”模式保存了上面的图像,但使用了 256 色板; I passed it through optipng to optimize the palette to 4 colors, and to improve the compression.我通过optipng将调色板优化为 4 种颜色,并改进压缩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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