Why is ''ValueError: image is readonly'' in PIL

Why is ''ValueError: image is readonly'' in PIL

我想更改灰度 pgm 图像中的像素。当我编译以下代码时,它显示图像是只读的。我无法更改 image 的像素。我该如何解决这个错误?
这是我的代码:

from PIL import Image
img = Image.open('Image.pgm')
pixval= img.load()
columnsize, rowsize = img.size 

img1 = Image.open('Image.pgm')
pix1 = img1.load()
for i in range(rowsize):
    for j in range(columnsize):
        pix1[j,i]=250
img1.save("share1.pgm")

为了改变一个像素,使用下面的API

image.putpixel((j, i), 250)

特别是,您的代码变为

from PIL import Image
img = Image.open('Image.pgm')
pixval = img.load()
columnsize, rowsize = img.size 
for i in range(rowsize):
    for j in range(columnsize):
        image.putpixel((j, i), 250)
img1.save("share1.pgm")

您似乎想使用 "array notation" 访问像素,因此您可能会发现将图像转换为 numpy 数组更直观、更快速并在那里进行修改。

所以,如果我从这张 320x240 的黑色图片开始:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Load the image from disk
im = Image.open("image.pgm")

# Convert image to numpy array
na = np.array(im)

# Make entire image grey (128)
na[:,:] = 128

# Make pixel 1,1 white (255)
na[1,1] = 255

# Make rows 20-30 white (255)
na[20:30,:] = 255

# Make columns 80-100 black (0)
na[:,80:100] = 0

# Convert numpy array back to image and save
Image.fromarray(na).save("result.png")


您可以合并前两行以简化如下:

# Load the image from disk and make into numpy array
na = np.array(Image.open("image.pgm"))