问题描述
你好,我是 Python 的新手。在我的函数中,我不断收到未使用变量 r、g、b、a 的警告。谁能帮我解释一下?
def encode_image(self,img,msg):
length = len(msg)
if length > 255:
print("text too long! (don't exeed 255 characters)")
return False
encoded = img.copy()
width,height = img.size
index = 0
for row in range(height):
for col in range(width):
if img.mode != 'RGB':
r,g,b,a = img.getpixel((col,row))
elif img.mode == 'RGB':
r,b = img.getpixel((col,row))
# first value is length of msg
if row == 0 and col == 0 and index < length:
asc = length
elif index <= length:
c = msg[index -1]
asc = ord(c)
else:
asc = b
encoded.putpixel((col,row),(r,asc))
index += 1
return encoded
Unused variable 'a' pylint(unused-variable)
Unused variable 'r' pylint(unused-variable)
Unused variable 'g' pylint(unused-variable)
Unused variable 'b' pylint(unused-variable)
r,row))
TypeError: cannot unpack non-iterable int object
解决方法
您的支票 if img.mode !='RGB'
不够。看起来你的图像是灰度的,因此 getpixel()
只会返回一个整数值,因此它不能将一个整数分成 4 个变量。 (即不能解压到 4 个变量)
使用 img.getbands()
查找有多少条带,然后相应地解包。