简体   繁体   中英

local variable 'orgHigh' referenced before assignment in google colab ( python 3.7 )

I'm having the local variable referenced before the assignment error and I have tried a lot of ways that I can use to fix this. Any help would be greatly appreciated.

error;

Traceback (most recent call last): File "real-time-action-recognition/Offline_Recognition.py", line 272, in one_video()

File "real-time-action-recognition/Offline_Recognition.py", line 242, in one_video

add_status(orig_frame ,x=orgHigh[0] ,y=orgHigh[1] ,s='Frame: {}'.format(frame_count),

UnboundLocalError: local variable 'orgHigh' referenced before assignment

Offline_Recognition.py

def one_video():
  capture = cv2.VideoCapture(args.video)
  fps_vid = capture.get(cv2.CAP_PROP_FPS)
  width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
  height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT) 
  fourcc = cv2.VideoWriter_fourcc(*"XVID")
  out = cv2.VideoWriter('output.mp4', fourcc, fps_vid, (int(width), int(height)))
    

  frames = []  
  frame_count = 0
  
  #Set opencv parameters according to the size of the input frames
  if args.quality == '1080p':
      orgHigh =(0,40) 
      orgDown = (0,1020)
      font = cv2.FONT_HERSHEY_COMPLEX_SMALL
      fontScale = 3
      thickness = 3
      boxcolor= (255,255,255)
      
  if args.quality == '480p':
      orgHigh =(0,20) 
      orgDown = (0,460)
      font = cv2.FONT_HERSHEY_COMPLEX_SMALL
      fontScale = 1.5
      thickness = 2
      boxcolor= (255,255,255)
      
  action_label = label_dic(args.classInd_file)
  
  while (capture.isOpened()):
      ret, orig_frame = capture.read()
     
      if ret is True:
          frame = cv2.cvtColor(orig_frame, cv2.COLOR_BGR2RGB)
      else:
          print('Not getting frames')
          break  
      
      #use .fromarray function to be able to apply different data augmentations
      frame = Image.fromarray(frame)
      
      if frame_count % args.sampling_freq < 6:
          frames.append(frame)
          print('Picked frame, ', frame_count)
      
      if len(frames) == args.delta*6:
          frames = transform(frames).cuda()
          scores_RGB = eval_video(frames[0:len(frames):6], 'RGB')[0,] 
          scores_RGBDiff = eval_video(frames[:], 'RGBDiff')[0,]           
          #Fusion
          final_scores = args.score_weights[0]*scores_RGB + args.score_weights[1] * scores_RGBDiff
          #Just like np.argsort()[::-1]
          scores_indcies = torch.flip(torch.sort(final_scores.data)[1],[0])
          #Prepare List of top scores for action checker
          TopScoresList = []
          for i in scores_indcies[:5]:
              TopScoresList.append(int(final_scores[int(i)]))
          #Check for "no action state"
          action_checker = Evaluation(TopScoresList, args.psi)
          #action_checker = True
          if not action_checker:
              print('No Assigned Action')
          for i in scores_indcies[:5]:
              print('%-22s %0.2f'% (action_label[str(int(i)+1)], final_scores[int(i)]))
          print('<----------------->')
          frames = []     
          

      
      add_status(orig_frame ,x=orgHigh[0] ,y=orgHigh[1] ,s='Frame: {}'.format(frame_count),
                font = font, fontScale = fontScale-.7 ,fontcolor=(0,255,255) ,thickness=thickness-1
                ,box_flag=True, alpha = .5, boxcolor=boxcolor, x_mode='center')
      
      if frame_count <= args.sampling_freq*args.delta:
          add_status(orig_frame ,x=orgDown[0] ,y=orgDown[1] ,s='Start Recognition ...',
                font = font, fontScale = fontScale ,fontcolor=(255,0,0) ,thickness=thickness
                ,box_flag=True, alpha = .5, boxcolor=boxcolor, x_mode='center')              
      else:
          
          if action_checker:
              add_status(orig_frame ,x=orgDown[0] ,y=orgDown[1] ,s='Detected Action: {}'.format(action_label[str(int(scores_indcies[0])+1)]),
               font = font, fontScale = fontScale ,fontcolor=(0,0,0) ,thickness=thickness
                ,box_flag=True, alpha = .5, boxcolor=boxcolor, x_mode='center')
                    
          else:
              add_status(orig_frame ,x=orgDown[0] ,y=orgDown[1] ,s='No Assigned Action',
               font = font, fontScale = fontScale ,fontcolor=(0,0,255) ,thickness=thickness
                ,box_flag=True, alpha = .5, boxcolor=boxcolor, x_mode='center')  
              
      frame_count += 1          
      out.write(orig_frame)
      
  
  # When everything done, release the capture
  capture.release()
  cv2.destroyAllWindows()    
  
  
if __name__ == '__main__':
    one_video()

It looks like there aren't fallback/default values for any of the variables being assigned within your if statements. So if args.quality doesn't have a value or match the if conditions, none of them will be set. That's your main error.

Also, it seems like this script is intended to be run via command line (I haven't used Google Collab, but it seems similar to command line arguments; Google Colab Command Line Args )? I think the way you are passing & parsing your arguments needs to change as well.

If you're running .python Offline_Recognition.py --quality 1080p then you would need something like this code to extract the arguments:

test.py

import sys
import getopt

def main(argv):
   quality = ''
   
   try:
      opts, args = getopt.getopt(argv,"hq:",["ifile=","ofile="])
   except getopt.GetoptError:
      print('test.py -i <inputfile> -o <outputfile>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print('test.py --quality <hd_mode>')
         sys.exit()
      elif opt in ("-q", "--quality"):
         quality = arg
   print('HD Quality is "', quality)

if __name__ == "__main__":
    main(sys.argv[1:])

GetOpt | Python - Command Line Arguments

So you could create a function to extract the arguments and pass them to your function one_video

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM