11import os
22import sys
33import time
4- from getopt import GetoptError as error
54from getopt import error , getopt
65from os .path import join , normpath
76
@@ -35,15 +34,15 @@ def get_model(framework, model_variant):
3534 from tensorflow .keras .backend import set_learning_phase
3635 from tensorflow .keras .models import load_model
3736 set_learning_phase (0 )
38- model = load_model (join ('models' , 'keras' , 'EfficientPose{0 }.h5' .format (model_variant .upper ())), custom_objects = {'BilinearWeights' : helpers .keras_BilinearWeights , 'Swish' : helpers .Swish (helpers .eswish ), 'eswish' : helpers .eswish , 'swish1' : helpers .swish1 })
37+ model = load_model (join ('models' , 'keras' , 'EfficientPose{}.h5' .format (model_variant .upper ())), custom_objects = {'BilinearWeights' : helpers .keras_BilinearWeights , 'Swish' : helpers .Swish (helpers .eswish ), 'eswish' : helpers .eswish , 'swish1' : helpers .swish1 })
3938
4039 # TensorFlow
4140 elif framework in ['tensorflow' , 'tf' ]:
4241 from tensorflow import import_graph_def
4342 from tensorflow .compat .v1 import GraphDef
4443 from tensorflow .compat .v1 .keras .backend import get_session
4544 from tensorflow .python .platform .gfile import FastGFile
46- f = FastGFile (join ('models' , 'tensorflow' , 'EfficientPose{0 }.pb' .format (model_variant .upper ())), 'rb' )
45+ f = FastGFile (join ('models' , 'tensorflow' , 'EfficientPose{}.pb' .format (model_variant .upper ())), 'rb' )
4746 graph_def = GraphDef ()
4847 graph_def .ParseFromString (f .read ())
4948 f .close ()
@@ -54,7 +53,7 @@ def get_model(framework, model_variant):
5453 # TensorFlow Lite
5554 elif framework in ['tensorflowlite' , 'tflite' ]:
5655 from tensorflow import lite
57- model = lite .Interpreter (model_path = join ('models' , 'tflite' , 'EfficientPose{0 }.tflite' .format (model_variant .upper ())))
56+ model = lite .Interpreter (model_path = join ('models' , 'tflite' , 'EfficientPose{}.tflite' .format (model_variant .upper ())))
5857 model .allocate_tensors ()
5958
6059 # PyTorch
@@ -63,13 +62,13 @@ def get_model(framework, model_variant):
6362
6463 from torch import backends , load , quantization
6564 try :
66- MainModel = load_source ('MainModel' , join ('models' , 'pytorch' , 'EfficientPose{0 }.py' .format (model_variant .upper ())))
65+ MainModel = load_source ('MainModel' , join ('models' , 'pytorch' , 'EfficientPose{}.py' .format (model_variant .upper ())))
6766 except :
6867 print ('\n ##########################################################################################################' )
69- print ('Desired model "EfficientPose{0 }Lite" not available in PyTorch. Please select among "RT", "I", "II", "III" or "IV".' .format (model_variant .split ('lite' )[0 ].upper ()))
68+ print ('Desired model "EfficientPose{}Lite" not available in PyTorch. Please select among "RT", "I", "II", "III" or "IV".' .format (model_variant .split ('lite' )[0 ].upper ()))
7069 print ('##########################################################################################################\n ' )
7170 return False , False
72- model = load (join ('models' , 'pytorch' , 'EfficientPose{0 }' .format (model_variant .upper ())))
71+ model = load (join ('models' , 'pytorch' , 'EfficientPose{}' .format (model_variant .upper ())))
7372 model .eval ()
7473 qconfig = quantization .get_default_qconfig ('qnnpack' )
7574 backends .quantized .engine = 'qnnpack'
@@ -183,7 +182,7 @@ def analyze_camera(model, framework, resolution, lite):
183182 cv2 .destroyAllWindows ()
184183
185184 # Print total operation time
186- print ('Camera operated in {0 } seconds' .format (time .time () - start_time ))
185+ print ('Camera operated in {} seconds' .format (time .time () - start_time ))
187186 print ('##########################################################################################################\n ' )
188187
189188 return coordinates
@@ -226,7 +225,7 @@ def analyze_image(file_path, model, framework, resolution, lite):
226225
227226 # Print processing time
228227 print ('\n ##########################################################################################################' )
229- print ('Image processed in {0 } seconds' .format ('%.3f' % (time .time () - start_time )))
228+ print ('Image processed in {} seconds' .format ('%.3f' % (time .time () - start_time )))
230229 print ('##########################################################################################################\n ' )
231230
232231 return coordinates
@@ -266,7 +265,7 @@ def analyze_video(file_path, model, framework, resolution, lite):
266265 frame_height , frame_width = next (vreader (file_path )).shape [:2 ]
267266 except Exception as e :
268267 print ('error' ,e ,'error' )
269- print ('Video "{0 }" could not be loaded. Please verify that the file is working.' .format (file_path ))
268+ print ('Video "{}" could not be loaded. Please verify that the file is working.' .format (file_path ))
270269 print ('##########################################################################################################\n ' )
271270 return False
272271
@@ -279,10 +278,10 @@ def analyze_video(file_path, model, framework, resolution, lite):
279278
280279 # Fetch batch of frames
281280 batch = [next (videogen , None ) for _ in range (batch_size )]
282- if not type (batch [0 ]) == np .ndarray :
281+ if type (batch [0 ]) is not np .ndarray :
283282 break
284- elif not type (batch [- 1 ]) == np .ndarray :
285- batch = [frame if type (frame ) == np .ndarray else np .zeros ((frame_height , frame_width , 3 )) for frame in batch ]
283+ elif type (batch [- 1 ]) is not np .ndarray :
284+ batch = [frame if type (frame ) is np .ndarray else np .zeros ((frame_height , frame_width , 3 )) for frame in batch ]
286285
287286 # Preprocess batch
288287 batch = helpers .preprocess (batch , resolution , lite )
@@ -296,7 +295,7 @@ def analyze_video(file_path, model, framework, resolution, lite):
296295
297296 # Print partial processing time
298297 if batch_num % part_size == 0 :
299- print ('{0 } of {1 }: Part processed in {2 } seconds | Video processed for {3 } seconds' .format (int (batch_num / part_size ), int (np .ceil (num_batches / part_size )), '%.3f' % (time .time () - part_start_time ), '%.3f' % (time .time () - start_time )))
298+ print ('{} of {}: Part processed in {} seconds | Video processed for {} seconds' .format (int (batch_num / part_size ), int (np .ceil (num_batches / part_size )), '%.3f' % (time .time () - part_start_time ), '%.3f' % (time .time () - start_time )))
300299 part_start_time = time .time ()
301300 batch_num += 1
302301
@@ -446,22 +445,19 @@ def save(video, file_path, coordinates):
446445 # Initialize CSV
447446 import csv
448447 csv_path = normpath (file_path .split ('.' )[0 ] + '_coordinates.csv' ) if file_path is not None else normpath ('camera_coordinates.csv' )
449- csv_file = open (csv_path , 'w' )
450448 headers = ['frame' ] if video else []
451449 [headers .extend ([body_part + '_x' , body_part + '_y' ]) for body_part , _ , _ in coordinates [0 ]]
452- writer = csv .DictWriter (csv_file , fieldnames = headers )
453- writer .writeheader ()
454-
455- # Write coordinates to CSV
456- for i , image_coordinates in enumerate (coordinates ):
457- row = {'frame' : i + 1 } if video else {}
458- for body_part , body_part_x , body_part_y in image_coordinates :
459- row [body_part + '_x' ] = body_part_x
460- row [body_part + '_y' ] = body_part_y
461- writer .writerow (row )
462-
463- csv_file .flush ()
464- csv_file .close ()
450+ with open (csv_path , 'w' ) as csv_file :
451+ writer = csv .DictWriter (csv_file , fieldnames = headers )
452+ writer .writeheader ()
453+
454+ # Write coordinates to CSV
455+ for i , image_coordinates in enumerate (coordinates ):
456+ row = {'frame' : i + 1 } if video else {}
457+ for body_part , body_part_x , body_part_y in image_coordinates :
458+ row [body_part + '_x' ] = body_part_x
459+ row [body_part + '_y' ] = body_part_y
460+ writer .writerow (row )
465461
466462def perform_tracking (video , file_path , model_name , framework_name , visualize , store ):
467463 """
@@ -490,19 +486,19 @@ def perform_tracking(video, file_path, model_name, framework_name, visualize, st
490486 model_variant = model_name .lower ()
491487 if framework not in ['keras' , 'k' , 'tensorflow' , 'tf' , 'tensorflowlite' , 'tflite' , 'pytorch' , 'torch' ]:
492488 print ('\n ##########################################################################################################' )
493- print ('Desired framework "{0 }" not available. Please select among "tflite", "tensorflow", "keras" or "pytorch".' .format (framework_name ))
489+ print ('Desired framework "{}" not available. Please select among "tflite", "tensorflow", "keras" or "pytorch".' .format (framework_name ))
494490 print ('##########################################################################################################\n ' )
495491 return False
496492 elif model_variant not in ['efficientposert' , 'rt' , 'efficientposei' , 'i' , 'efficientposeii' , 'ii' , 'efficientposeiii' , 'iii' , 'efficientposeiv' , 'iv' , 'efficientposert_lite' , 'rt_lite' , 'efficientposei_lite' , 'i_lite' , 'efficientposeii_lite' , 'ii_lite' ]:
497493 print ('\n ##########################################################################################################' )
498- print ('Desired model "{0 }" not available. Please select among "RT", "I", "II", "III", "IV", "RT_Lite", "I_Lite" or "II_Lite".' .format (model_name ))
494+ print ('Desired model "{}" not available. Please select among "RT", "I", "II", "III", "IV", "RT_Lite", "I_Lite" or "II_Lite".' .format (model_name ))
499495 print ('##########################################################################################################\n ' )
500496 return False
501497
502498 # LOAD MODEL
503499 else :
504500 model_variant = model_variant [13 :] if len (model_variant ) > 7 else model_variant
505- lite = True if model_variant .endswith ('_lite' ) else False
501+ lite = bool ( model_variant .endswith ('_lite' ))
506502 model , resolution = get_model (framework , model_variant )
507503 if not model :
508504 return True
@@ -540,7 +536,7 @@ def main(file_path, model_name, framework_name, visualize, store):
540536 # LIVE ANALYSIS FROM CAMERA
541537 if file_path is None :
542538 print ('\n ##########################################################################################################' )
543- print ('Click "Q" to end camera-based tracking.' . format ( file_path ) )
539+ print ('Click "Q" to end camera-based tracking.' )
544540 print ('##########################################################################################################\n ' )
545541 perform_tracking (video = True , file_path = None , model_name = model_name , framework_name = framework_name , visualize = False , store = store )
546542
@@ -554,7 +550,7 @@ def main(file_path, model_name, framework_name, visualize, store):
554550
555551 else :
556552 print ('\n ##########################################################################################################' )
557- print ('Ensure supplied file "{0 }" is a video or image' .format (file_path ))
553+ print ('Ensure supplied file "{}" is a video or image' .format (file_path ))
558554 print ('##########################################################################################################\n ' )
559555
560556
0 commit comments