【问题标题】:How to change the pixel colour of an image with PIL?如何使用 PIL 更改图像的像素颜色?
【发布时间】:2019-09-24 17:31:26
【问题描述】:

我想更改一个像素,但由于某种原因这不起作用。

from PIL import Image
import numpy

im = Image.open("art\\PlanetX@1.25.png")
a = numpy.asarray(im)
img = Image.fromarray(a)
pixels = img.load()
pixels[0, 0] = (255, 0, 0, 255)

应该发生的是PNG的左上角应该设置为红色。我得到 ValueError: Image is readonly 错误。

【问题讨论】:

标签: python python-3.x python-imaging-library


【解决方案1】:

如果你只想改变几个奇数像素,你可以像这样使用相当慢的putpixel()

from PIL import Image

# Create blue 30x15 image
im = Image.new('RGB',(30,15),color='blue')

# Change single pixel at 10,0 to red
im.putpixel((10,0),(255,0,0))

或者,您可以将整个图像转换为 Numpy 数组并进行更多更改,使用 Numpy 函数更快:

from PIL import Image
import numpy as np

# Create blue 30x15 image
im = Image.new('RGB',(30,15),color='blue')

# Convert to Numpy array
na = np.array(im)

# Change single pixel at 10,0 to green
na[0,10] = (0,255,0)

# Change whole row to red
na[3] = (255,0,0)

# Change whole column to yellow
na[:,8] = (255,255,0)

# Convert back to PIL Image and save
Image.fromarray(na).save('result.png')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2014-11-07
    • 2011-11-08
    • 2015-07-31
    • 1970-01-01
    相关资源
    最近更新 更多