opencvobject-tracking

How to fix - AttributeError: module 'cv2' has no attribute 'legacy'


I am running a facial recognition code that I have from a programmer a while back that I ran on google colab. Reason was that I didn't have gpu on my computer and colab has.

I am not working with the programmer anymore and am now trying to run the code on a computer with gpu.

I finished setting up all packages needed for running the code (python 3.10, cuda, cudnn, opencv-contrib-python==4.5.5.62, opencv-python==4.7.0.72, tensorflow==2.10 etc.) and the only thing I changed was to downgrade the tensorflow from version 2.12 to 2.10 so it will work on windows.

I am now receiving the following error which I haven't received before stating that cv2 has no attribute 'legacy'. I searched online but only saw a mention that cv2 has move things to legacy from version ~4.5. Anyone know how to get around this?

The code I have is working on colab. The script does manage to recognize gpu.

Thanks to all reference.

Error:

Cell In[10], line 1
----> 1 dict_with_frames, fps = main(videoname=video_name, x_frame_to_check=frame_to_check, database_folder=database_folder, tracker_type=tracker_type,path_to_the_video=path_to_the_video, output_folder=output_folder, frame_of_early_stop=stop_frame, frame_of_start=frame_of_start )
      3 save_the_dict(dict_with_frames, output_path='Database/', output_file_name='dict_with_frames.txt')
      5 #gpu_or_cpu = 'cpu.config.yml'    - for cpu
      6 #gpu_or_cpu = 'gpu.config.yml'    - for gpu

Cell In[8], line 88, in main(videoname, x_frame_to_check, database_folder, tracker_type, path_to_the_video, output_folder, frame_of_early_stop, frame_of_start)
     84 ret, frame = cap.read()
     85 if frame_id % x_frame_to_check == 0:
     86     
     87     # multi object tracker initialization
---> 88     multi_tracker = cv2.legacy.MultiTracker_create()
     89     dict_with_objects = {}
     90     print(f'Frame number {frame_id}/{number_of_frames}')

AttributeError: module 'cv2' has no attribute 'legacy'

I tried searching about it online but not much comes up to do with cv2.legacy. What does come up is that after version 4.5 the tracking module was moved to the cv2.legacy, but that is what works. I just ran the file again, as it is (tensorflow 2.12), on colab and it is working.


Solution

  • it's usually the same issue: multiple opencv-python* packages conflict with each other. Especially if the versions don't even match, but matching versions may still conflict.

    1. Remove all opencv-python* packages
    2. Install exactly one package

    All of them contain the base modules. The *-contrib package is not an add-on, it's complete.

    Any other package depending on opencv-python will be perfectly happy with opencv-contrib-python, even if Python package dependencies can't model that.