UnboundLocalError: local variable 'img' referenced before assignment, however variable is a function argument

Consider the following Python code snippet:

In utils.py:

...
def get_all_fd(image_id, img, label):
    """Get all feature descriptors of a given image"""
    img_shape = np.array(img).shape
    true_channels
    if img_shape[0] >= 3:
        true_channels = 3
    else:
        # stacking the grayscale channel on itself thrice to get RGB dimensions
        img = torch.tensor(np.stack((np.array(img[0, :, :]),) * 3, axis=0))
    ...

In an .ipynb file in the same directory:

from utils import *

get_all_fd(0,[1,2,3,4],0)

I am getting this error:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
c:\some_path\task_0.ipynb Cell 8 line 3
      1 from utils import *
----> 3 get_all_fd(0,[1,2,3,4],0)

File c:\some_path\utils.py:267, in get_all_fd(image_id, image, label)
    264 img_shape = np.array(img).shape
    266 if img_shape[0] >= 3:
--> 267     true_channels = 3
    268 else:
    269     # stacking the grayscale channel on itself thrice to get RGB dimensions
    270     img = torch.tensor(np.stack((np.array(img[0, :, :]),) * 3, axis=0))

UnboundLocalError: local variable 'img' referenced before assignment

Other imported functions work perfectly, it’s just this one. The error message isn’t really helpful here, it says img isn’t assigned, even though it’s an argument to the function. What’s happening here?

NB: This question seems similar, but as shown in the example, even when I pass a constant value, I get the same error.

>Solution :

In your trace, the argument to get_all_fd() is named image. But in your code snippet at the top, it’s img. Try saving utils.py and re-running the code. That should work.

Leave a Reply