0

Hello I'm a newbie at python. In my function, I keep getting warnings of unused variables r,g,b,a. Can someone explain it for me?

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, g, 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, g , 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, g, b ,a = img.getpixel((col, row))
TypeError: cannot unpack non-iterable int object
3
  • 1
    See stackoverflow.com/questions/59723475/… Commented Jan 16, 2021 at 21:29
  • tksm! what about the unused variables? Should I care about it? Commented Jan 16, 2021 at 22:03
  • 1
    That's just a lint warning as others have said. You don't use the variables after defining them, so you don't need to define them at all Commented Jan 16, 2021 at 22:29

1 Answer 1

1

Your check if img.mode !='RGB' is not sufficient. Seems like your image is greyscale, hence getpixel() will only return one integer value, hence it cannot split an integer into 4 variables. (i.e. can't unpack to 4 variables)

Use img.getbands() to find how many bands are there and then unpack accordingly.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello it seems like it work with RGB image and not with P-mode, meaning white-ish picture results in this error. But I still don't understand the unused variables warnings, should I do anything about it?
Pylint is a code checker, it tells you the unused variables in your code, hence saving system resources. You can ignore this for now. Its useful for large projects where every byte counts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.