ultralytics / yolov5

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

Different result between detect.py and torch.hub.load? #7887

Closed HouLingLXH closed 2 years ago

HouLingLXH commented 2 years ago

Search before asking

Question

For a same texture and my best.pt, I can get aim better when I use detect.py to inference it ,

Buy if I use torch.hub.load,like:

model = torch.hub.load("./","custom",path_or_model=’./my_py/best.pt’,source='local')

img = cv2.imread("data/images_my/1.png")

result = model(img)

I will not get the aim.

Why different result ?

Additional

No response

github-actions[bot] commented 2 years ago

πŸ‘‹ Hello @HouLingLXH, 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

@HouLingLXH πŸ‘‹ Hello! Thanks for asking about handling inference results. Your cv2 example is not correct. Correct Usage is shown in the YOLOv5 πŸš€ PyTorch Hub tutorial.

Simple Inference Example

This example loads a pretrained YOLOv5s model from PyTorch Hub as model and passes an image for inference. 'yolov5s' is the YOLOv5 'small' model. For details on all available models please see the README. Custom models can also be loaded, including custom trained PyTorch models and their exported variants, i.e. ONNX, TensorRT, TensorFlow, OpenVINO YOLOv5 models.

import torch

# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')  # or yolov5m, yolov5l, yolov5x, etc.
# model = torch.hub.load('ultralytics/yolov5', 'custom', 'path/to/best.pt')  # custom trained model

# Images
im = 'https://ultralytics.com/images/zidane.jpg'  # or file, Path, URL, PIL, OpenCV, numpy, list

# Inference
results = model(im)

# Results
results.print()  # or .show(), .save(), .crop(), .pandas(), etc.

results.xyxy[0]  # im predictions (tensor)
results.pandas().xyxy[0]  # im predictions (pandas)
#      xmin    ymin    xmax   ymax  confidence  class    name
# 0  749.50   43.50  1148.0  704.5    0.874023      0  person
# 2  114.75  195.75  1095.0  708.0    0.624512      0  person
# 3  986.00  304.00  1028.0  420.0    0.286865     27     tie

See YOLOv5 PyTorch Hub Tutorial for details.

Good luck πŸ€ and let us know if you have any other questions!

HouLingLXH commented 2 years ago

About the first parameter of model(x), I try it: if x is picture path like "data/x.jpg", will get aim if x from cv2.imread, means x is a mat of BGR, will not get aim if x from cv2.imread, and change to RGB, means x is a mat of RGB, will get aim

It means x can be picture path or mat of RGB, but can not be mat or BGR,right?

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 ⭐!

jpinzonc commented 1 year ago

I would like to know if this issue was resolved? I am trying this:

!python detect.py --weights yolov5x.pt --img 640 --conf 0.25 --source videot.mp4 --name cmd_line --save-txt --save-conf --class 32

vs

from typing import Generator import matplotlib.pyplot as plt import numpy as np import cv2 %matplotlib inline

def generate_frames(video_file: str) -> Generator[np.ndarray, None, None]: video = cv2.VideoCapture(video_file) while video.isOpened(): success, frame = video.read() if not success: break yield frame video.release()

import torch frame_iterator = iter(generate_frames(video_file='video.mp4)) frame = next(frame_iterator)

model = torch.hub.load('ultralytics/yolov5', 'yolov5x') model.classes = [32] model.iou = 0.45 model.conf = 0.25 results = model(frame) results.pandas() results.show()

but keep getting difference 0.65 vs 0.32 confidence for the class I am trying to detect. It is the ball, only one in the frame.

Is there a setting I am missing? Thanks.

jpinzonc commented 1 year ago

I hope this helps.

I figure my issue. Do not know the technical explanation, but pythorch on Mac Book Pro reads jpg and video frames different. The solution was to convert the frame with PIL:

        converted = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        converted = Image.fromarray(converted)

and run the prediction on converted frame.

hbphuc commented 1 year ago

I hope this helps.

I figure my issue. Do not know the technical explanation, but pythorch on Mac Book Pro reads jpg and video frames different. The solution was to convert the frame with PIL:

        converted = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        converted = Image.fromarray(converted)

and run the prediction on converted frame.

Hello Jpinzonc,

I must sign in and thank you for your comment. It really helped me a lot. I trained a model in two days and got a precision of 0.9999 at a confidence of 1. When I use the model with detect.py, it's excellent. But when I use the model with torch.hub.load in my codes, it's too bad. It took me a day but I didn't know why. I was too lazy to check the codes in detect.py and related files. I didn't notice the color spaces either. Wish you the best and thank you again :)))

James

glenn-jocher commented 1 year ago

@hbphuc you're very welcome. I'm glad to hear that the provided solution helped you resolve the issue. It's fantastic to see that you were able to identify and address the root cause of the problem. Feel free to reach out if you have any further questions or require assistance with anything else. Good luck with your future endeavors!

jpinzonc commented 7 months ago

I hope this helps. I figure my issue. Do not know the technical explanation, but pythorch on Mac Book Pro reads jpg and video frames different. The solution was to convert the frame with PIL:

        converted = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        converted = Image.fromarray(converted)

and run the prediction on converted frame.

Hello Jpinzonc,

I must sign in and thank you for your comment. It really helped me a lot. I trained a model in two days and got a precision of 0.9999 at a confidence of 1. When I use the model with detect.py, it's excellent. But when I use the model with torch.hub.load in my codes, it's too bad. It took me a day but I didn't know why. I was too lazy to check the codes in detect.py and related files. I didn't notice the color spaces either. Wish you the best and thank you again :)))

James

James, just saw your message. I am glad my solution worked for you.

glenn-jocher commented 7 months ago

Hello James,

Thrilled to hear the solution was a success for you! πŸŽ‰ Figuring out those tricky discrepancies, especially with color spaces, can really be a game-changer. You've clearly done an amazing job with your modelβ€”precision like that is no small feat. Remember, the YOLOv5 community is here for you, whether for sharing solutions or tackling new challenges. Keep up the fantastic work, and don't hesitate to dive back into the docs or community discussions if you hit another snag.