 # Trying to write code to change pixels

Hi everyone, I’m looking for a little help on a small project.

I am trying to take an image and change the pixels by a slight shift.
So I bring an image in, and change the r value by the original value divided by 4.
I add this image to a list, then take the original image and change the red value divided by 2, and finally the same again and change the red value by minus 10.

After this I follow the same procedure for the Green and blue values.
Any help appreciated.

``````from PIL import Image

# Set the file and open it
file = "Final/charlie.png"
pic = Image.open(file)

#Convert to RGB, so we dont have to deal with the alpha channel
pic = pic.convert('RGB')
images = []
count = 0

#Image processing for
def image_processing(x,y,z):
if count == 0:
return int(x / 10), y, z
elif count == 1:
return int(x / 2), y, z
else:
return int(x - 10), y, z

#Create PixelMap
def pixel_map(image):
for x in range(pic.size):
for y in range(pic.size):
r, g, b = pic.getpixel((x,y))
pic.putpixel((x,y),image_processing(r,g,b))
images.append(pic)

while count <3:
pixel_map(pic)
count+=1``````

Hi Pace,

Thanks for posting your code, but what’s your question? Does your code
raise an error? Not do what you expect? Too slow?

Hi Steven, sorry I forgot to actually tell you what my current issue was.

I’ struggling to figure out how to make this work for my multiple images. I figure that I will need a while loop, that passes my image through each stage of processing, bit I’m not sure how to implemt the logic that understands that it has already passed through a processing stage.

I’m guessing I need a counter, but when I implement this I just get multiple images that are equal in my list. Instead of images with different rgb adjustments.maybe this is because I’m not making a copy of the image, I’m not sure.

I think it is exactly that. Your loop looks like this:

`````` for x in range(pic.size):
for y in range(pic.size):
r, g, b = pic.getpixel((x,y))
pic.putpixel((x,y),image_processing(r,g,b))
images.append(pic)
``````

pic.putpixel() modifies the image in place. Remember that variables in
Python are reference to values. So when you go:

`````` images.append(pic)
``````

it appends a reference to the same image each time. Make a copy of pic
and modify the copy.

The Image class is documented here:

``````https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image
``````

Notice that some methods, like filter, produce a modified copy of the
image, and other methods modify the image itself.

There’s an Image.copy() method which gets you an identical copy of the
image:

``````https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.copy
``````

Cheers,
Cameron Simpson cs@cskk.id.au

Thanks Cameron, this got me going in the right direction 