Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python UnboundLocalError:局部变量';图像';分配前参考_Python - Fatal编程技术网

Python UnboundLocalError:局部变量';图像';分配前参考

Python UnboundLocalError:局部变量';图像';分配前参考,python,Python,我正在运行这个代码 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((29

我正在运行这个代码

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
它给了我这个错误:

UnboundLocalError:赋值前引用了局部变量“image”

这条线

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

有人能解释为什么会发生这个错误吗

UnboundLocalError:赋值前引用了局部变量“image”

问题在于:

def extract_功能(文件名、型号):
尝试:
image=image.open(文件名)
除:
打印(“错误:无法打开图像!请确保图像路径和扩展名正确”)
image=image.resize((299299))
...
当异常发生时,它会转到
except
块,然后
image
永远不会指定正确的值。然后,代码继续在
try-except
块之外运行,您尝试
image.resize(…)
中引用
image
。但是,由于它仍然是未定义的,所以您会得到上面提到的错误

建议了一个解决方案,但我不建议将所有代码放在try-except块中。我想说,您现在拥有的代码“更好”,因为它更可读,哪些特定的行/操作可以引发异常,然后适当地处理这些异常

在您的情况下,发生异常时只需跳过代码的其余部分:

def extract_功能(文件名、型号):
尝试:
image=image.open(文件名)
除:
打印(“错误:无法打开图像!请确保图像路径和扩展名正确”)
一无所获
#如果代码到达这里,图像现在被*分配*并且可以*引用*
image=image.resize((299299))
...
在这里,当出现问题时,您可以
立即返回
。您可以返回指示错误状态的内容,如此处的
None
,然后在程序的其他部分处理它。或者,如果您只是想打印一条更友好的错误消息,那么请将其打印出来,然后重新引发相同的异常:

除了:
打印(“错误:无法打开图像!请确保图像路径和扩展名正确”)
提升
然后,您可以在其他地方处理重新引发的
异常,或者它将完全停止您的程序(如果没有正常运行的
图像,程序将无法运行,这是有意义的)

另外,最好不要隐藏异常。获取它并使用内置的。它可以提供更多信息,或者可能存在错误路径以外的其他错误:

导入日志
def extract_功能(文件名、型号):
尝试:
image=image.open(文件名)
除作为exc的例外情况外:
logging.error(“无法打开映像!请确保映像路径和扩展名正确”,exc_info=exc)
提升
#如果代码到达这里,图像现在被*分配*并且可以*引用*
image=image.resize((299299))
...
错误:root:无法打开映像!确保映像路径和扩展名正确
回溯(最近一次呼叫最后一次):
文件“test.py”,第8行,在extract_features中
image=image.open(文件名)
文件“/path/to/PIL/Image.py”,第2967行,打开
引发无法识别的图像错误(
PIL.UnidentifiedImageError:无法识别图像文件“test.png”

因为try块中的代码已经抛出,所以变量
image
没有在它里面初始化。为了避免这个错误,你可以在except-block里面返回。这意味着
image。open
失败,所以
image
永远不会被定义。你应该中止其余的代码,因为没有image它是无用的。你还应该打印原始/实际错误消息,而不是定义自己的
print(…)
,以便更好地理解出现错误的原因。还有其他错误,而不仅仅是路径错误。