简体   繁体   中英

Changing the value of pixel in an image

I am working with stenography. I need to hide data in pixel of an image.But I am fetching problem when I am trying to update the value of pixel. I tried the code below:

from PIL import Image

im = Image.open('./data/frame398.png')
pix = im.load()
r, g, b = pix[200,200]
print("Pre RGB")
print(r, g, b)
pix[200,200] = 0,0,0  

It should change the value of the pixel to (0,0,0). But it doesn't. If I try the code below:

imx = Image.open('./data/frame398.png')
pixx = imx.load()
r, g, b = pixx[200,200]
print("Post RGB")
print(r, g, b)

I got the output below:

Pre RGB
69 62 65
Post RGB
69 62 65

Instead of (0,0,0) I am getting the old value. What I am doing wrong? I need help.Thanks

You are successfully changing the image, but you need to write it to a file if you want to read it again:

To save to the same image file just do

im.save('./data/frame398.png', ‘PNG’)

When you do

r, g, b = pixx[200,200]

You are off-loading the pixel value from either a tuple or an array. So your best bet would be

pixel[200,200] = (0, 0, 0)
#or
pixel[200,200] = [0, 0, 0]

I ran the below code and got the expected output.

from PIL import Image

im = Image.open('image.jpg')
pix = im.load()

r, g, b = pix[200,200]
print("Pre RGB")
print(r, g, b)

pix[200,200] = 0,0,0

r, g, b = pix[200,200]
print("Post RGB")
print(r, g, b)

Output:

Pre RGB
172 196 220
Post RGB
0 0 0

As mentioned in answer by @chthonicdaemon , you actually need to save the mage with Image.save().

Secondaly if you want to play around with pixel values it will be better to convert loaded image to numpy array like,

import numpy as np
im = Image.open('./data/frame398.png')
im = np.array(im)

This make pixel manipulation a lot simpler, just take care to create a copy of the original image like,

im = np.array(im)
im = im.copy()

If a copy is not made sometime python doesn't allow assigning direct values.

After that you can easily change individual values like,

im[0, 0, 0] = 255 # Complete RED
im[0, 0, 1] = 0 # No green
im[0, 0, 2] = 0 # No blue

And as of saving image, it is also super easy like,

Image.fromarray(im).save('name_of_file.png', 'PNG')


We were also given similar assignment for stegnography, if you are intrested can check complete code here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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