[英]Python pillow image.putpixel((x,y),pixel) doesn't change all the pixel
I want to change each pixel of a given image by the use of image.putpixel((x,y),pixel)
but only the first element (if the returned image) has the correct value我想通过使用
image.putpixel((x,y),pixel)
更改给定图像的每个像素,但只有第一个元素(如果返回的图像)具有正确的值
Here is the code:这是代码:
def encode(text,image):
#image.show()
#for im in image.getdata():
#print(im)
pixels = image.load()
text = ''.join(format(x,'b') for x in bytes(text,"ascii"))
print(text)
iteration = 0
for i in range(image.size[0]):
for j in range(image.size[1]):
tmp = list(pixels[i,j])
for k in range(len(tmp)):
if iteration == len(text)-1:
return image
elif text[iteration]=="0":
if tmp[k]%2!=0:
if tmp[k]==255:
tmp[k]-=1
else:
tmp[k]+=1
elif text[iteration]=="1":
if tmp[k]%2==0:
tmp[k]+=1
iteration +=1
pixel = tuple(tmp)
image.putpixel((i,j),pixel)
print(f"pixel : {pixels[i,j]}")
if __name__ == "__main__":
img = Image.open("C:/Users/Toavina/Pictures/Crypto/icon.PNG")
img = encode("test_data",img)
#New pixel
for pixel in img.getdata():
print(pixel)
Excepted value:(value of each pixel if i print the value on the encode function)例外值:(如果我在编码函数上打印值,则每个像素的值)
pixel: (253, 253, 253, 254)像素:(253、253、253、254)
pixel: (253, 252, 252, 255)像素:(253、252、252、255)
pixel: (253, 252, 252, 255)像素:(253、252、252、255)
pixel: (252, 253, 253, 255)像素:(252、253、253、255)
pixel: (253, 252, 252, 255)像素:(253、252、252、255)
pixel: (253, 253, 253, 255)像素:(253、253、253、255)
pixel: (252, 253, 252, 254)像素:(252、253、252、254)
pixel: (253, 252, 253, 255)像素:(253、252、253、255)
pixel: (253, 253, 253, 255)像素:(253、253、253、255)
pixel: (253, 252, 252, 255)像素:(253、252、252、255)
Value of the image returned, only the first pixel has the correct value:返回图像的值,只有第一个像素具有正确的值:
(253, 253, 253, 254) (253, 253, 253, 254)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
(252, 252, 252, 255) (252, 252, 252, 255)
I think your code is actually working, it's just that the iteration order of我认为您的代码确实有效,只是迭代顺序
for i in range(image.size[0]):
for j in range(image.size[1]):
differs from the iteration order of不同于的迭代顺序
for pixel in img.getdata():
print(pixel)
Try changing how you iterate after you return and print out the coordinates along with the pixel values so that you can confirm.返回后尝试更改迭代方式并打印出坐标和像素值,以便您确认。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.