【问题标题】:variable inside function not defined despite having it defined globally尽管全局定义了函数内部的变量但未定义
【发布时间】:2023-02-14 21:56:48
【问题描述】:

我在我的 for 循环之外定义了我的字典 'frame_dict'。但是,当它到达我的 forFrame 函数时,尽管设置它有一个全局变量,但我收到一条错误消息,指出 frame_dict 未定义。有什么帮助吗?

import os
from imageai.Detection import VideoObjectDetection
import pickle


PATH_TO_STORE_VIDEOS = "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/Videos"

tv_commercial_videos = os.listdir('Videos/')


def yolo_neural_network(path_to_videos, tv_commercials):

        execution_path = os.getcwd()
        frame_dict = {}

        for tv_c in tv_commercials:
            frame_dict.setdefault(tv_c,[])

            # Use pre trained neural network to label things in videos
            vid_obj_detect = VideoObjectDetection()
            # Set and load Yolo model
            vid_obj_detect.setModelTypeAsYOLOv3()
            vid_obj_detect.setModelPath(os.path.join(execution_path,"yolov3.pt"))
            vid_obj_detect.loadModel()

            input_file_path = os.path.join(path_to_videos, tv_c)

            if not os.path.exists("output_from_model_yolov3/"):
                os.makedirs("output_from_model_yolov3/")
            output_file_path = os.path.join(execution_path,"output_from_model_yolov3/", "model_yolov3_output_" + tv_c)


            def forFrame(frame_number, output_array, output_count):
                global frame_dict
                frame_dict[tv_c].append(output_count)
                return frame_dict
            
            vid_obj_detect.detectObjectsFromVideo(
                            input_file_path=input_file_path,
                            output_file_path=output_file_path,
                            log_progress=True,
                            frame_detection_interval= 60,
                            minimum_percentage_probability=70,
                            per_frame_function=forFrame,
                            save_detected_video=True
                            )

        # save dictionary
        f = open("yolo_dict.pkl", "wb")

        # write dict to pickle file
        pickle.dump(frame_dict, f)

        # close file
        f.close()   

        return frame_dict

yolo = yolo_neural_network(PATH_TO_STORE_VIDEOS, tv_commercial_videos)
Exception has occurred: ValueError
An error occured. It may be that your input video is invalid. Ensure you specified a proper string value for 'output_file_path' is 'save_detected_video' is not False. Also ensure your per_frame, per_second, per_minute or video_complete_analysis function is properly configured to receive the right parameters. 
  File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 35, in forFrame
    frame_dict[tv_c].append(output_count)
NameError: name 'frame_dict' is not defined

During handling of the above exception, another exception occurred:

  File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 38, in yolo_neural_network
    vid_obj_detect.detectObjectsFromVideo(
  File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 59, in <module>

我尝试在 forframe 函数中将我的 frame_dict 变量设置为全局变量,希望它能够识别它。

【问题讨论】:

  • 名为frame_dict 的全局变量从未被定义,因此您不能在forFrame() 中将其作为全局变量访问。您根本不需要 global 声明,因为变量在封闭范围内。

标签: python


【解决方案1】:

frame_dict 不是全局的,它只是在外部范围内,删除 global 关键字

因为你改变了对象,你不需要做更多的事情:

            def forFrame(frame_number, output_array, output_count):
                frame_dict[tv_c].append(output_count)
                return frame_dict

由于您没有为 frame_dict 分配任何内容,即使变量是全局变量,如果您改变对象,也不需要添加 global 关键字。 global 仅在需要为变量分配新值时才有用。

【讨论】:

    【解决方案2】:

    您面临的问题是 frame_dict 实际上不是全局变量。它被定义里面来自yolo_neural_network。虽然这确实在forFrame 之外,但它不是全局变量。

    在这种情况下,您应该简单地删除 global 语句,因为它不是您要导入的全局变量。

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      相关资源
      最近更新 更多