Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
1 task done
HouLingLXH opened this issue May 19, 2022 · 10 comments
Closed
1 task done

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

HouLingLXH opened this issue May 19, 2022 · 10 comments
Labels
question Further information is requested Stale

Comments

@HouLingLXH
Copy link

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

@HouLingLXH HouLingLXH added the question Further information is requested label May 19, 2022
@github-actions
Copy link
Contributor

github-actions bot commented May 19, 2022

👋 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
Copy link
Member

glenn-jocher commented May 19, 2022

@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
Copy link
Author

HouLingLXH commented May 20, 2022

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
Copy link
Contributor

github-actions bot commented Jun 19, 2022

👋 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
Copy link

jpinzonc commented Jan 1, 2023

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
Copy link

jpinzonc commented Jan 3, 2023

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
Copy link

hbphuc commented Nov 13, 2023

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
Copy link
Member

@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
Copy link

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
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested Stale
Projects
None yet
Development

No branches or pull requests

4 participants