问题
I want to change pixel in a grayscale pgm image. When I compile the following code it shows image is read-only. I can not change the pixel of the image. How can I fix this error?
Here are my codes:
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")
回答1:
In order to change a pixel, use the following API
image.putpixel((j, i), 250)
In particular, your code becomes
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")
回答2:
You appear to want to use "array notation" to access pixels so you may find it more intuitive and faster to convert your image to a numpy
array and do your modifications there.
So, if I start with this 320x240 black image:
#!/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")
You can merge the first two lines to simplify things like this:
# Load the image from disk and make into numpy array
na = np.array(Image.open("image.pgm"))
来源:https://stackoverflow.com/questions/51908968/why-is-valueerror-image-is-readonly-in-pil