ultralytics / yolov5

YOLOv5 ๐Ÿš€ in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
50.39k stars 16.26k forks source link

AttributeError: 'NoneType' object has no attribute 'shape'. #6916

Closed Hrrsmjd closed 2 years ago

Hrrsmjd commented 2 years ago

I am trying to get YOLOV5 (with --source 0) working on my Raspberry PI. If I provide a folder or .jpg files as the source, the code runs with the expected output.

Here is my input:

python detect.py --weights best.pt --source 0

Here is the error:

/usr/local/lib/python3.9/dist-packages/torchvision/io/image.py:11: UserWarning: Failed to load image Python extension: 
  warn(f"Failed to load image Python extension: {e}")
detect: weights=['birds200.pt'], source=0, data=data/coco128.yaml, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False
YOLOv5 ๐Ÿš€ b578d6c torch 1.10.2 CPU

Fusing layers... 
Model Summary: 213 layers, 7549525 parameters, 0 gradients, 17.5 GFLOPs
[ WARN:0@40.749] global /io/opencv/modules/videoio/src/cap_v4l.cpp (1910) getProperty VIDEOIO(V4L2:/dev/video0): Unable to get camera FPS
1/1: 0...  Success (inf frames 640x480 at 99.00 FPS)

Traceback (most recent call last):
  File "/home/pi/detect_birds/detect.py", line 257, in <module>
    main(opt)
  File "/home/pi/detect_birds/detect.py", line 252, in main
    run(**vars(opt))
  File "/usr/local/lib/python3.9/dist-packages/torch/autograd/grad_mode.py", line 28, in decorate_context
    return func(*args, **kwargs)
  File "/home/pi/detect_birds/detect.py", line 105, in run
    dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
  File "/home/pi/detect_birds/utils/datasets.py", line 323, in __init__
    s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])
  File "/home/pi/detect_birds/utils/datasets.py", line 323, in <listcomp>
    s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])
  File "/home/pi/detect_birds/utils/augmentations.py", line 93, in letterbox
    shape = im.shape[:2]  # current shape [height, width]
AttributeError: 'NoneType' object has no attribute 'shape'
terminate called without an active exception
Aborted

Again, if the source is a folder or .jpg files, the code runs with the expected output.

What should I try?

github-actions[bot] commented 2 years ago

๐Ÿ‘‹ Hello @Hrrsmjd, thank you for your interest in YOLOv5 ๐Ÿš€! Please visit our โญ๏ธ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a ๐Ÿ› Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training โ“ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email support@ultralytics.com.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.

glenn-jocher commented 2 years ago

@Hrrsmjd your YOLOv5 code appears out of date. To update your code:

github-actions[bot] commented 2 years ago

๐Ÿ‘‹ Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 ๐Ÿš€ resources:

Access additional Ultralytics โšก resources:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 ๐Ÿš€ and Vision AI โญ!

BillySalcedo commented 2 years ago

Good day, I have the same issue with my Raspi 4 using Yolov5. Tried installing the latest version of the code, still the same error. Any fix?

glenn-jocher commented 2 years ago

@BillySalcedo ๐Ÿ‘‹ hi, thanks for letting us know about this possible problem with YOLOv5 ๐Ÿš€. We've created a few short guidelines below to help users provide what we need in order to start investigating a possible problem.

How to create a Minimal, Reproducible Example

When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimum reproducible example. Your code that reproduces the problem should be:

For Ultralytics to provide assistance your code should also be:

If you believe your problem meets all the above criteria, please close this issue and raise a new one using the ๐Ÿ› Bug Report template with a minimum reproducible example to help us better understand and diagnose your problem.

Thank you! ๐Ÿ˜ƒ

binmus commented 1 year ago

hey bro! do you know how to try?

glenn-jocher commented 1 year ago

@binmus hello,

I would be happy to assist you with your question. However, I'm unsure what you are asking. Could you please provide more details about the issue you are facing with YOLOv5?

Thank you.

almonz1 commented 7 months ago

nz@raspberrypi:~/yolov5 $ python detect.py --source 0 --weights yolov5s.pt --conf 0.25 /home/almonz/.local/lib/python3.11/site-packages/matplotlib/projections/init.py:63: UserWarning: Unable to import Axes3D. This may be due to multiple versions of Matplotlib being installed (e.g. as a system package and as a pip package). As a result, the 3D projection is not available. warnings.warn("Unable to import Axes3D. This may be due to multiple versions of " detect: weights=['yolov5s.pt'], source=0, data=data/coco128.yaml, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_csv=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False, vid_stride=1 YOLOv5 รฐลธลกโ‚ฌ v7.0-294-gdb125a20 Python-3.11.2 torch-2.2.1 CPU

Fusing layers... YOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients, 16.4 GFLOPs qt.qpa.plugin: Could not find the Qt platform plugin "wayland" in "/home/almonz/.local/lib/python3.11/site-packages/cv2/qt/plugins" [ WARN:0@9.044] global cap_v4l.cpp:2092 getProperty VIDEOIO(V4L2:/dev/video0): Unable to get camera FPS 1/1: 0... Success (inf frames 640x480 at 99.00 FPS)

Traceback (most recent call last): File "/home/almonz/yolov5/detect.py", line 312, in main(opt) File "/home/almonz/yolov5/detect.py", line 307, in main run(*vars(opt)) File "/home/almonz/.local/lib/python3.11/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/almonz/yolov5/detect.py", line 123, in run dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/almonz/yolov5/utils/dataloaders.py", line 472, in init s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/almonz/yolov5/utils/dataloaders.py", line 472, in s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/almonz/yolov5/utils/augmentations.py", line 123, in letterbox shape = im.shape[:2] # current shape [height, width] ^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'shape' terminate called without an active exception Aborted

almonz1 commented 7 months ago

can someone tell me whats the problem

glenn-jocher commented 7 months ago

@almonz1, it looks like you're encountering an issue where the program is unable to properly access or interpret the video stream from your device (in this case, --source 0 typically refers to your default webcam). The error AttributeError: 'NoneType' object has no attribute 'shape' suggests that the video frame being read is None, which usually happens if the video source is not correctly initialized or accessible.

Here are a few steps you can try to resolve this issue:

  1. Check Camera Access: Ensure your Raspberry Pi has access to the webcam and that no other process is using the camera. You can test this by using a simple OpenCV script to capture video frames.

  2. Permissions: Make sure you have the necessary permissions to access the camera on your Raspberry Pi.

  3. Dependencies: The error message regarding Qt platform plugin "wayland" suggests there might be an issue with your PyQt5 installation or environment setup. Ensure all dependencies are correctly installed and your environment is properly configured. You might need to set the QT_QPA_PLATFORM environment variable to offscreen if you're running headless, or ensure the correct Qt plugins are installed.

  4. OpenCV Version: Ensure you're using a compatible version of OpenCV. Sometimes, specific versions of OpenCV might have issues with camera access on certain platforms.

  5. Update YOLOv5: Make sure you're using the latest version of YOLOv5. If not, update your repository and try again.

  6. Alternative Video Source: As a test, try using a different video source (e.g., a video file) to see if the issue persists. This can help determine if the problem is specifically related to accessing the webcam.

If after trying these steps you're still facing issues, it might be helpful to provide more details about your setup, including the Raspberry Pi model, the camera model, and the versions of the key libraries you're using (PyTorch, OpenCV). This information can help in diagnosing the problem more accurately.

almonz1 commented 7 months ago

I am using raspberry pi4b 8gb RAM 64bits OS "2023-12-05-raspios-bookworm-arm64-full" and I use RPI 8MP Camera Board Raspberry Pi Camera V2. I already updated my yolov5 version into the latest using "git pull origin master" and I also install again "git clone https://github.com/ultralytics/yolov5" I already tried the to change the source in to jpg file and .mp4 file and it works

almonz1 commented 7 months ago

and after I set QT_QPA_PLATFORM to offscreen it shows this error

almonz@raspberrypi:~/yolov5 $ python detect.py --source 0 --weights yolov5s.pt --conf 0.25 /home/almonz/.local/lib/python3.11/site-packages/matplotlib/projections/init.py:63: UserWarning: Unable to import Axes3D. This may be due to multiple versions of Matplotlib being installed (e.g. as a system package and as a pip package). As a result, the 3D projection is not available. warnings.warn("Unable to import Axes3D. This may be due to multiple versions of " detect: weights=['yolov5s.pt'], source=0, data=data/coco128.yaml, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_csv=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False, vid_stride=1 YOLOv5 รฐลธลกโ‚ฌ v7.0-294-gdb125a20 Python-3.11.2 torch-2.2.1 CPU

Fusing layers... YOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients, 16.4 GFLOPs qt.qpa.plugin: Could not find the Qt platform plugin "offscreen" in "/home/almonz/.local/lib/python3.11/site-packages/cv2/qt/plugins" This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: xcb.

Aborted

glenn-jocher commented 5 months ago

Hey @almonz1! It looks like the issue is related to the Qt platform configuration on your Raspberry Pi. Since setting QT_QPA_PLATFORM to offscreen didn't resolve the issue and led to a new error about Qt platform plugins, you might want to try setting it to xcb instead, which is listed as available in your error message.

You can set the environment variable like this before running your script:

export QT_QPA_PLATFORM=xcb
python detect.py --source 0 --weights yolov5s.pt --conf 0.25

This directs Qt to use the X11 backend (xcb), which might solve the initialization problem. Give it a try and let us know how it goes! ๐Ÿ˜Š

SHP50c commented 3 months ago

This is my input os.system("cd yolov5/ && python detect.py --weights best.pt --img 640 --conf 0.5 --source 0")

and this is what I'm getting

detect: weights=['best.pt'], source=0, data=data\coco128.yaml, imgsz=[640, 640], conf_thres=0.5, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_csv=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs\detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False, vid_stride=1 YOLOv5 2024-7-10 Python-3.8.19 torch-2.3.1+cpu CPU

Fusing layers... custom_YOLOv5s summary: 182 layers, 7262700 parameters, 0 gradients [ WARN:0@59.349] global cap_msmf.cpp:1769 CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638 1/1: 0... Success (inf frames 640x480 at 30.00 FPS)

Traceback (most recent call last): File "detect.py", line 317, in <module> main(opt) File "detect.py", line 312, in main run(**vars(opt)) File "D:\my_stuff\New_Courses\DeepLearning\Computer_vision_project\Sign_language_Using_object_detection_YOLO_V5\venv\lib\site-packages\torch\utils\_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "detect.py", line 128, in run dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) File "D:\my_stuff\New_Courses\DeepLearning\Computer_vision_project\Sign_language_Using_object_detection_YOLO_V5\yolov5\utils\dataloaders.py", line 473, in __init__ s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs]) File "D:\my_stuff\New_Courses\DeepLearning\Computer_vision_project\Sign_language_Using_object_detection_YOLO_V5\yolov5\utils\dataloaders.py", line 473, in <listcomp> s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs]) File "D:\my_stuff\New_Courses\DeepLearning\Computer_vision_project\Sign_language_Using_object_detection_YOLO_V5\yolov5\utils\augmentations.py", line 123, in letterbox shape = im.shape[:2] # current shape [height, width] AttributeError: 'NoneType' object has no attribute 'shape'

can someone please help me out, I tried all the above mentioned suggestion but none of them seem to work in my case.

glenn-jocher commented 3 months ago

Hello @SHP50c,

Thank you for reaching out and providing detailed information about the issue you're encountering. It looks like you're running into an error where the video frame being read is None, which typically indicates a problem with accessing the video source.

To help us better understand and diagnose the issue, could you please provide a minimal, reproducible example of your code? This will allow us to replicate the problem on our end and investigate a solution. You can find guidelines for creating a minimal, reproducible example here. Ensuring we can reproduce the issue is crucial for us to provide effective assistance.

Additionally, please verify that you are using the latest versions of torch and the YOLOv5 repository. You can update YOLOv5 with the following commands:

git pull origin master

And ensure your torch version is up to date:

pip install --upgrade torch

Given the error message, it seems there might be an issue with the video capture backend. Here are a few steps you can try:

  1. Check Camera Access: Ensure your camera is properly connected and accessible. You can test this with a simple OpenCV script to capture video frames.

  2. Permissions: Make sure you have the necessary permissions to access the camera.

  3. Alternative Video Source: As a test, try using a different video source (e.g., a video file) to see if the issue persists. This can help determine if the problem is specifically related to accessing the webcam.

  4. Environment Configuration: If you are running this on a headless setup, ensure that your environment is correctly configured for video capture. Setting the QT_QPA_PLATFORM environment variable to xcb might help:

    export QT_QPA_PLATFORM=xcb
  5. OpenCV Version: Ensure you're using a compatible version of OpenCV. Sometimes, specific versions of OpenCV might have issues with camera access on certain platforms.

If you continue to experience issues, please share the minimal reproducible example and any additional details about your setup, such as the operating system, camera model, and versions of key libraries. This information will help us assist you more effectively.

Thank you for your patience and cooperation! ๐Ÿ˜Š

SHP50c commented 3 months ago

Hello @SHP50c,

Thank you for reaching out and providing detailed information about the issue you're encountering. It looks like you're running into an error where the video frame being read is None, which typically indicates a problem with accessing the video source.

To help us better understand and diagnose the issue, could you please provide a minimal, reproducible example of your code? This will allow us to replicate the problem on our end and investigate a solution. You can find guidelines for creating a minimal, reproducible example here. Ensuring we can reproduce the issue is crucial for us to provide effective assistance.

Additionally, please verify that you are using the latest versions of torch and the YOLOv5 repository. You can update YOLOv5 with the following commands:

git pull origin master

And ensure your torch version is up to date:

pip install --upgrade torch

Given the error message, it seems there might be an issue with the video capture backend. Here are a few steps you can try:

  1. Check Camera Access: Ensure your camera is properly connected and accessible. You can test this with a simple OpenCV script to capture video frames.
  2. Permissions: Make sure you have the necessary permissions to access the camera.
  3. Alternative Video Source: As a test, try using a different video source (e.g., a video file) to see if the issue persists. This can help determine if the problem is specifically related to accessing the webcam.
  4. Environment Configuration: If you are running this on a headless setup, ensure that your environment is correctly configured for video capture. Setting the QT_QPA_PLATFORM environment variable to xcb might help:
    export QT_QPA_PLATFORM=xcb
  5. OpenCV Version: Ensure you're using a compatible version of OpenCV. Sometimes, specific versions of OpenCV might have issues with camera access on certain platforms.

If you continue to experience issues, please share the minimal reproducible example and any additional details about your setup, such as the operating system, camera model, and versions of key libraries. This information will help us assist you more effectively.

Thank you for your patience and cooperation! ๐Ÿ˜Š

Hello Thank you, my issue was solved after I upgraded the torch library.

glenn-jocher commented 3 months ago

Hello @SHP50c,

Thank you for the update! I'm glad to hear that upgrading the torch library resolved your issue. ๐ŸŽ‰

If you have any more questions or run into any other issues, feel free to reach out. The YOLO community and the Ultralytics team are always here to help!

Happy coding! ๐Ÿ˜Š