1

I'm running this code,

def extract_features(filename, model):
    try:
        image = Image.open(filename)

    except:
        print("ERROR: Couldn't open image! Make sure the image path and extension is correct")
        
    image = image.resize((299,299))
    image = np.array(image)
    # for images that has 4 channels, we convert them into 3 channels
    if image.shape[2] == 4: 
        image = image[..., :3]
    image = np.expand_dims(image, axis=0)
    image = image/127.5
    image = image - 1.0
    feature = model.predict(image)
    return feature

It gives me this error:

UnboundLocalError: local variable 'image' referenced before assignment

This line

print("ERROR: Couldn't open image! Make sure the image path and extension is correct")

is printed by the interpreter.

Can someone explain why this error occurred?

2
  • Because since the code inside the try-block has thrown, the variable image was not initialized inside it. To avoid this error, you can return inside your except-block. Commented Jun 10, 2021 at 4:12
  • It means Image.open failed, so image is never defined. You should abort rest of code since it's useless without image. You should also print out the raw/actual error message instead of defining your own print(...), to get a better understanding of why you are getting an error. There are other errors, not just about paths. Commented Jun 10, 2021 at 4:15

1 Answer 1

1

UnboundLocalError: local variable 'image' referenced before assignment

The issue is here:

def extract_features(filename, model):
    try:
        image = Image.open(filename)
    except:
        print("ERROR: Couldn't open image! Make sure the image path and extension is correct")

    image = image.resize((299, 299))
    ...

When an Exception occurs, it goes to the except block, and then image is never assigned a proper value. Then, the code continued to run outside the try-except block, where you tried to reference image in image.resize(...). But, since it's still undefined, you get the mentioned error.

The other answer suggests a solution, but I don't recommend the solution to put all the code inside the try-except block. I would say the code you have now is "better", in that it's more readable which particular lines/operations can raise an Exception, and then handle those Exceptions appropriately.

In your case, you just need to skip the rest of the code when an Exception occurs:

def extract_features(filename, model):
    try:
        image = Image.open(filename)
    except:
        print("ERROR: Couldn't open image! Make sure the image path and extension is correct")
        return None 
   
    # If the code gets here, image is now *assigned* and can be *referenced* 
    image = image.resize((299, 299))
    ...

Here, you can return immediately when something has gone wrong. You can return something to indicate an error state, like a None here, then handle it in some other part of your program. Or, if you just wanted to print a friendlier error message, then print it out then just re-raise the same Exception:

except:
    print("ERROR: Couldn't open image! Make sure the image path and extension is correct")
    raise

Either you then handle the re-raised Exception somewhere else, or it will stop your program completely (which makes sense if it will not work without a working image).

Also, as I suggested in the comments, it's better to not hide the Exception. Get it and log it using the built-in logging module. It can provide more information or there might be other errors other than wrong paths:

import logging

def extract_features(filename, model):
    try:
        image = Image.open(filename)
    except Exception as exc:
        logging.error("Couldn't open image! Make sure the image path and extension is correct", exc_info=exc)
        raise

    # If the code gets here, image is now *assigned* and can be *referenced*
    image = image.resize((299, 299))
    ...
ERROR:root:Couldn't open image! Make sure the image path and extension is correct
Traceback (most recent call last):
  File "test.py", line 8, in extract_features
    image = Image.open(filename)
  File "/path/to/PIL/Image.py", line 2967, in open
    raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file 'test.png'
Sign up to request clarification or add additional context in comments.

Comments

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.