函数内部的变量未定义,尽管在全局范围内已经定义。

huangapple go评论117阅读模式
英文:

variable inside function not defined despite having it defined globally

问题

I define my dictionary 'frame_dict' outside my for loop. However, when it gets to my forFrame function, despite setting it has a global variable, I get an error saying that frame_dict is not defined. Any help?

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 occurred. It may be that your input video is invalid. Ensure you specified a proper string value for 'output_file_path' and '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>

I tried setting my frame_dict variable as global inside the forFrame function expecting it to recognize it.

英文:

I define my dictionary 'frame_dict' outside my for loop. However, when it gets to my forFrame function, despite setting it has a global variable, I get an error saying that frame_dict is not defined. Any help?

import os
from imageai.Detection import VideoObjectDetection
import pickle


PATH_TO_STORE_VIDEOS = &quot;/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/Videos&quot;

tv_commercial_videos = os.listdir(&#39;Videos/&#39;)


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,&quot;yolov3.pt&quot;))
            vid_obj_detect.loadModel()

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

            if not os.path.exists(&quot;output_from_model_yolov3/&quot;):
                os.makedirs(&quot;output_from_model_yolov3/&quot;)
            output_file_path = os.path.join(execution_path,&quot;output_from_model_yolov3/&quot;, &quot;model_yolov3_output_&quot; + 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(&quot;yolo_dict.pkl&quot;, &quot;wb&quot;)

        # 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 &#39;output_file_path&#39; is &#39;save_detected_video&#39; 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 &quot;/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py&quot;, line 35, in forFrame
    frame_dict[tv_c].append(output_count)
NameError: name &#39;frame_dict&#39; is not defined

During handling of the above exception, another exception occurred:

  File &quot;/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py&quot;, line 38, in yolo_neural_network
    vid_obj_detect.detectObjectsFromVideo(
  File &quot;/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py&quot;, line 59, in &lt;module&gt;

I tried setting my frame_dict variable as global inside the forframe function expecting it to recognise it.

答案1

得分: 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 仅在你需要给变量赋新值时有用。

英文:

frame_dict is not a global, it is just in an outer scope, remove global keyword

Since you mutate the object, you don't need to do anything more:

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

Since you don't assign anything to frame_dict, even if the variable were a global variable, you wouldn't need to add the global keyword if you mutate the object. global is useful only if you need to assign a new value to the variable.

答案2

得分: 0

你面临的问题是frame_dict实际上不是一个全局变量。它是在yolo_neural_network内部定义的。虽然它确实在forFrame之外,但它不是一个全局变量。

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

英文:

The problem you are facing is that frame_dict is actually not a global variable. It is defined inside of yolo_neural_network. While this is indeed outside forFrame, it is not a global variable.

In this scenario, you should simply remove the global statement, because it is not a global variable you are importing.

huangapple
  • 本文由 发表于 2023年2月14日 21:29:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定