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

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

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?

  1. import os
  2. from imageai.Detection import VideoObjectDetection
  3. import pickle
  4. PATH_TO_STORE_VIDEOS = "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/Videos"
  5. tv_commercial_videos = os.listdir('Videos/')
  6. def yolo_neural_network(path_to_videos, tv_commercials):
  7. execution_path = os.getcwd()
  8. frame_dict = {}
  9. for tv_c in tv_commercials:
  10. frame_dict.setdefault(tv_c,[])
  11. # Use pre trained neural network to label things in videos
  12. vid_obj_detect = VideoObjectDetection()
  13. # Set and load Yolo model
  14. vid_obj_detect.setModelTypeAsYOLOv3()
  15. vid_obj_detect.setModelPath(os.path.join(execution_path,"yolov3.pt"))
  16. vid_obj_detect.loadModel()
  17. input_file_path = os.path.join(path_to_videos, tv_c)
  18. if not os.path.exists("output_from_model_yolov3/"):
  19. os.makedirs("output_from_model_yolov3/")
  20. output_file_path = os.path.join(execution_path, "output_from_model_yolov3/", "model_yolov3_output_" + tv_c)
  21. def forFrame(frame_number, output_array, output_count):
  22. global frame_dict
  23. frame_dict[tv_c].append(output_count)
  24. return frame_dict
  25. vid_obj_detect.detectObjectsFromVideo(
  26. input_file_path=input_file_path,
  27. output_file_path=output_file_path,
  28. log_progress=True,
  29. frame_detection_interval= 60,
  30. minimum_percentage_probability=70,
  31. per_frame_function=forFrame,
  32. save_detected_video=True
  33. )
  34. # save dictionary
  35. f = open("yolo_dict.pkl", "wb")
  36. # write dict to pickle file
  37. pickle.dump(frame_dict, f)
  38. # close file
  39. f.close()
  40. return frame_dict
  41. yolo = yolo_neural_network(PATH_TO_STORE_VIDEOS, tv_commercial_videos)
  1. Exception has occurred: ValueError
  2. 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.
  3. File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 35, in forFrame
  4. frame_dict[tv_c].append(output_count)
  5. NameError: name 'frame_dict' is not defined
  6. During handling of the above exception, another exception occurred:
  7. File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 38, in yolo_neural_network
  8. vid_obj_detect.detectObjectsFromVideo(
  9. 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?

  1. import os
  2. from imageai.Detection import VideoObjectDetection
  3. import pickle
  4. PATH_TO_STORE_VIDEOS = &quot;/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/Videos&quot;
  5. tv_commercial_videos = os.listdir(&#39;Videos/&#39;)
  6. def yolo_neural_network(path_to_videos, tv_commercials):
  7. execution_path = os.getcwd()
  8. frame_dict = {}
  9. for tv_c in tv_commercials:
  10. frame_dict.setdefault(tv_c,[])
  11. # Use pre trained neural network to label things in videos
  12. vid_obj_detect = VideoObjectDetection()
  13. # Set and load Yolo model
  14. vid_obj_detect.setModelTypeAsYOLOv3()
  15. vid_obj_detect.setModelPath(os.path.join(execution_path,&quot;yolov3.pt&quot;))
  16. vid_obj_detect.loadModel()
  17. input_file_path = os.path.join(path_to_videos, tv_c)
  18. if not os.path.exists(&quot;output_from_model_yolov3/&quot;):
  19. os.makedirs(&quot;output_from_model_yolov3/&quot;)
  20. output_file_path = os.path.join(execution_path,&quot;output_from_model_yolov3/&quot;, &quot;model_yolov3_output_&quot; + tv_c)
  21. def forFrame(frame_number, output_array, output_count):
  22. global frame_dict
  23. frame_dict[tv_c].append(output_count)
  24. return frame_dict
  25. vid_obj_detect.detectObjectsFromVideo(
  26. input_file_path=input_file_path,
  27. output_file_path=output_file_path,
  28. log_progress=True,
  29. frame_detection_interval= 60,
  30. minimum_percentage_probability=70,
  31. per_frame_function=forFrame,
  32. save_detected_video=True
  33. )
  34. # save dictionary
  35. f = open(&quot;yolo_dict.pkl&quot;, &quot;wb&quot;)
  36. # write dict to pickle file
  37. pickle.dump(frame_dict, f)
  38. # close file
  39. f.close()
  40. return frame_dict
  41. yolo = yolo_neural_network(PATH_TO_STORE_VIDEOS, tv_commercial_videos)
  1. Exception has occurred: ValueError
  2. 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.
  3. File &quot;/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py&quot;, line 35, in forFrame
  4. frame_dict[tv_c].append(output_count)
  5. NameError: name &#39;frame_dict&#39; is not defined
  6. During handling of the above exception, another exception occurred:
  7. File &quot;/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py&quot;, line 38, in yolo_neural_network
  8. vid_obj_detect.detectObjectsFromVideo(
  9. 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 关键字

由于你修改了对象,你不需要再做任何事情:

  1. def forFrame(frame_number, output_array, output_count):
  2. frame_dict[tv_c].append(output_count)
  3. 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:

  1. def forFrame(frame_number, output_array, output_count):
  2. frame_dict[tv_c].append(output_count)
  3. 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:

确定