ValueError:太多值无法解压(hide_text_in_image(image_path,text)

问题描述 投票:0回答:1

我不知道如何修复这个错误。 发生异常:ValueError 需要解压的值太多(预计有 3 个) 文件,第 25 行,在 hide_text_in_image 中 r、g、b = 像素 ^^^^^^^ 文件第 46 行,位于 hide_text_in_image(图像路径,文本) ValueError:需要解包的值太多(预计为 3 个)

完整代码

从 PIL 导入图像

def text_to_bits(文本): bits = ''.join(format(ord(char), '08b') for char in text) 返回位

def hide_text_in_image(图像路径, 文本): img = Image.open(image_path)

位 = 文本到位(文本)

pixels = list(img.getdata())

encoded_pixels = []
bit_index = 0

for pixel in pixels:
    if bit_index < len(bits):
        r, g, b = pixel
        r = (r & 0xFE) | int(bits[bit_index])
        g = (g & 0xFE) | int(bits[bit_index+1])
        b = (b & 0xFE) | int(bits[bit_index+2])
        encoded_pixels.append((r, g, b))
        bit_index += 3
    else:
        encoded_pixels.append(pixel)

encoded_image = Image.new(img.mode, img.size)
encoded_image.putdata(encoded_pixels)

encoded_image.save("encoded_image.png")

text =“您好,这是一条隐藏消息!” image_path =“pngwing.com.png” 隐藏图像中的文本(图像路径,文本)

我试图在网上寻找答案,但我什么也没明白。

python
1个回答
0
投票

如果你这样做

r, g, b = pixel
,你期望
pixel
是一个可迭代的,就像列表或元组一样。在您的情况下,
pixel
的值太多,无法满足要为其赋值的变量数量。举个例子:

>>> x = [1,2,3]
>>> y, z = x
ValueError: too many values to unpack
>>> x = [1,2,3]
>>> y, z, a = x
>>> x
1
>>> z
2
>>> a
3
© www.soinside.com 2019 - 2024. All rights reserved.