gpt4 book ai didi

python 的 putpixel() 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:41 24 4
gpt4 key购买 nike

所以我在做这个学校项目(我知道真正的基本编程,而 python 是我唯一知道的语言),我需要更改我的像素颜色以对图片中的消息进行编码,但 PIL 的 putpixel 似乎没有要工作,这是我的代码。

P.S.:我所有的 PIL 信息都是自学的,英语不是我的主要语言,所以如果你能讲得简单点,我将不胜感激

from PIL import Image
e=input('file and location? ')
img=Image.open(e)
pmap=img.load()
imy=img.height
imx=img.width
if int(input('1 for encoding, 2 for decoding '))==1:
a=input('Your message? ')
for i in range(len(a)):
r , g , b=img.getpixel((i+10,imy//2))
img.putpixel((i+10,imy//2),(ord(a[i]),g,b))
r,g,b=img.getpixel((len(a)+10,imy//2))
img.putpixel((len(a)+10,imy//2),(999,g,b)) #999 is the stop code in decoding
else:
r=u=0
m=''
while r!=999:
r , g , b=img.getpixel((10+u,imy//2))
m+=chr(r)
u+=1
print(m[:len(a)-1])
img.save(e)

请记住,我不想在视觉上产生差异,而且我已经完成了调试。也没有错误,但 putpixel 出于某种原因无法正常工作。正如我所说,我是编程新手,如果其中包含愚蠢的错误,我深表歉意。

最佳答案

在使用您的代码并在图像上进行尝试后,putpixel 会按预期工作。像素的变化很难看到,这可能就是您认为它不起作用的原因。相信我,它正在发挥作用,只是您看不到它。

但是,我发现您的代码存在两个问题:

1) 999 不可编码

999 无法在单个像素中编码。像素的最大值为 255(范围为 0-255)。您需要选择不同的停止代码/序列。我建议将停止代码更改为 255

2)解码时,a从未被定义

您需要通过其他方式获取消息的长度。我建议使用计数器来执行此操作:

counter = 0
while something:
counter += 1

# do something with count here

总而言之,您的代码的工作版本如下所示:

e=input('file and location?  ')
img=Image.open(e)
pmap=img.load()
imy=img.height
imx=img.width
if int(input('1 for encoding, 2 for decoding '))==1:
a=input('Your message? ')
for i in range(len(a)):
r , g , b= img.getpixel((i+10,imy//2))
img.putpixel((i+10,imy//2),(ord(a[i]),g,b))
r,g,b=img.getpixel((len(a)+10,imy//2))
img.putpixel((len(a)+10,imy//2),(255,g,b)) #255 is the stop code in decoding
else:
r=u=0
m=''
message_length=0
while r!=255:
message_length+=1
r , g , b=img.getpixel((10+u,imy//2))
m+=chr(r)
u+=1
print(m[:message_length-1])
img.save(e)

关于python 的 putpixel() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36846755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com