torch hub error for yolov5 in ubuntu aws ec2 instance


I install torch and open cv like this

pip3 install torch torchvision torchaudio --extra-index-url

pip install opencv-python

I run this code in ubuntu aws ec2 instance

import torch

# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')

# Image
im = 'car.jpg'

# Inference
results = model(im)


but I get this error

Using cache found in /home/ubuntu/.cache/torch/hub/ultralytics_yolov5_master
Traceback (most recent call last):
  File "/home/ubuntu/web/lib/objd/", line 4, in <module>
    model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
  File "/home/ubuntu/web/myenv/lib/python3.10/site-packages/torch/", line 542, in load
    model = _load_local(repo_or_dir, model, *args, **kwargs)
  File "/home/ubuntu/web/myenv/lib/python3.10/site-packages/torch/", line 572, in _load_local
    model = entry(*args, **kwargs)
  File "/home/ubuntu/.cache/torch/hub/ultralytics_yolov5_master/", line 93, in yolov5s
    return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
  File "/home/ubuntu/.cache/torch/hub/ultralytics_yolov5_master/", line 33, in _create
    from models.common import AutoShape, DetectMultiBackend
  File "/home/ubuntu/.cache/torch/hub/ultralytics_yolov5_master/models/", line 18, in <module>
    import cv2
  File "/home/ubuntu/web/myenv/lib/python3.10/site-packages/cv2/", line 181, in <module>
  File "/home/ubuntu/web/myenv/lib/python3.10/site-packages/cv2/", line 153, in bootstrap
    native_module = importlib.import_module("cv2")
  File "/usr/lib/python3.10/importlib/", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ImportError: cannot open shared object file: No such file or directory

how to solve this, because if I run this code in my local computer, running well


This error message is indicating that the OpenCV library is unable to find the ‘’ shared object file on your AWS EC2 instance.

This is likely because the library is not installed or configured properly on the EC2 instance.

Try running this command on the EC2 instance:

sudo apt-get install -y libgl1-mesa-glx

This command will install the missing library and should resolve the issue.

If the issue persists, you can also try installing the OpenCV library from source instead of using pip. This can be done by following the steps outlined in the OpenCV documentation:

Once you have OpenCV installed and configured properly, you should be able to run your code without any errors.

Answered By: Zanmato