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

How to train yolov9-s or yolov9-m? #128

Closed
319769805 opened this issue Feb 29, 2024 · 4 comments
Closed

How to train yolov9-s or yolov9-m? #128

319769805 opened this issue Feb 29, 2024 · 4 comments

Comments

@319769805
Copy link

I want to compare the lantency of yolov9-s and m with the yolov8-s

@Akshaykushawaha
Copy link

You can download the yolov9 models explicitly from here :
https://github.com/WongKinYiu/yolov9?tab=readme-ov-file#evaluation (under the heading there, you can see the various models)

Also, you can check out this comment since in order for you to run yolov9 without the CLI command, you would need some additional user-defined functions and a few more imports, mentioned here: #84 (comment) (This has resources for beginners.)

Then you can either train that model and use it, or you can use the downloaded model directly.
Now, for the comparison of latency, you can use the code below:

from ultralytics import YOLO
import cv2
import time
from PIL import Image

# Load the models
model_1 = YOLO("model1.pt")  # Replace with your yolo v8 model path

# use the code for initiating the Yolo v9 model mentioned in the link. The below one is for Yolo v8.
model_2 = YOLO("model2.pt")  # Replace with your model path

# Load a test image
img = Image.open('./test_img.jpg')  # Replace with your image path

# Run multiple iterations for each model to get an average
num_iters = 100
total_time_model_1 = 0
total_time_model_2 = 0

for _ in range(num_iters):
  # Run model_1
  start_time = time.time()
  model_1(img)
  end_time = time.time()
  total_time_model_1 += (end_time - start_time)

  # Run model_2
  start_time = time.time()
  model_2(img)
  end_time = time.time()
  total_time_model_2 += (end_time - start_time)

# Calculate average latency
avg_latency_model_1 = total_time_model_1 / num_iters
avg_latency_model_2 = total_time_model_2 / num_iters

# Print the results
print("Average Latency (ms):")
print("model_1:", avg_latency_model_1 * 1000)
print("model_2:", avg_latency_model_2 * 1000)

Please point out if there's any mistake!
Happy coding!😊

@Akshaykushawaha
Copy link

Akshaykushawaha commented Feb 29, 2024

I wrote the code to initiate yolov9 from the link provided; you can use this to initiate (clone the yolov9 repo and use this code in that directory) :

! pip install supervision
# ML/DL
import numpy as np
import torch

# CV
import cv2
import supervision as sv

# YOLOv9
from models.common import DetectMultiBackend, AutoShape
from utils.torch_utils import select_device
from utils.general import set_logging

# Video Demonstration
from IPython.display import HTML
from base64 import b64encode

from supervision import Detections as BaseDetections
from supervision.config import CLASS_NAME_DATA_FIELD

# Image loading
from PIL import Image

class ExtendedDetections(BaseDetections):
    @classmethod
    def from_yolov9(cls, yolov9_results) -> 'ExtendedDetections':
        """
        Creates a Detections instance from YOLOv9 inference results.
        
        Args:
            yolov9_results (yolov9.models.common.Detections):
                The output Detections instance from YOLOv9.

        Returns:
            ExtendedDetections: A new Detections object that includes YOLOv9 detections.

        Example:
            results = model(image)
            detections = ExtendedDetections.from_yolov9(results)
        """
        xyxy, confidences, class_ids = [], [], []

        for det in yolov9_results.pred:
            for *xyxy_coords, conf, cls_id in reversed(det):
                xyxy.append(torch.stack(xyxy_coords).cpu().numpy())
                confidences.append(float(conf))
                class_ids.append(int(cls_id))

        class_names = np.array([yolov9_results.names[i] for i in class_ids])
        
        if not xyxy:
            return cls.empty()  
        
        return cls(
            xyxy=np.vstack(xyxy),
            confidence=np.array(confidences),
            class_id=np.array(class_ids),
            data={CLASS_NAME_DATA_FIELD: class_names},
        )


set_logging(verbose=False)
# Device 0 is gpu
device = select_device('0')
# Original arguments: (weights='weights/yolov9-e.pt', device=device, data='data/coco.yaml', fuse=True ")
# Here, I removed the fuse because I don't want to train it, I want to use it as is.
# I named it model_2 so that you can use it directly in the code provided in the previous [comment.] https://github.com/WongKinYiu/yolov9/issues/128#issuecomment-1971831927)
model_2 = DetectMultiBackend(weights='yolov9-c.pt', device=device, fuse=False)
model_2 = AutoShape(model)

I tried it and tested yolov8x with yolov9-c, got these results:
image

Let me know if you have any issues running the code!
Remember to close the issue if it's resolved; thanks!! 😊

@WongKinYiu
Copy link
Owner

#3 (comment)

@WongKinYiu
Copy link
Owner

yolov9-s and yolov9-m are released.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants