0

I am using the below code to load the trained custom Yolov5 model and perform detections.

import cv2
import torch
from PIL import Image

model = torch.hub.load('ultralytics/yolov5', 'custom', 
 path='yolov5/runs/train/exp4/weights/best.pt', force_reload=True) 

img = cv2.imread('example.jpeg')[:, :, ::-1]  # OpenCV image (BGR to RGB)

results = model(img, size=416)

#To display and save results I am using:

results.print()  
results.save() 
results.show()

My question is how can I save the results in different directory so that I can use them in my web-based application. For your reference I am using Streamlit. For instance, at the moment, results (image) are being saved in runs\detect\exp*. I want to change it. Can anyone please guide me.

4 Answers4

4

You can make changes in the function definition of results.save(), the function can be found in the file yolov5/models/common.py. By default the definition is:

def save(self, labels=True, save_dir='runs/detect/exp'):
        save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True)  # increment save_dir
        self.display(save=True, labels=labels, save_dir=save_dir)  # save results

You can make changes in the save_dir argument to the desired save location and the files should be saved in the new directory.

Azhan Mohammed
  • 340
  • 2
  • 8
1

This worked for me all you have to do is use few arguments.

--exist-ok --name(path_where_to_save)

For example :

  {dataset.location}/data.yaml --weights yolov5l.pt **--exist-ok --name 
      'path_where_to_save'**

For better understanding you can refer here.

Fatemeh Sangin
  • 558
  • 1
  • 4
  • 19
0

Just pass the save_dir params to your desired directory.

Example

results.save(save_dir='data/output/images') 
Techuila
  • 1,237
  • 8
  • 12
0

YOLO always saves its labels-results to project/name/labels/.

So you should add few additional arguments for your purpose:

  1. --project {dir1}, path to dir where {dir2}==name will be created!
  2. --name {dir2}, where YOLO's results (labels, etc.) will be placed.
  3. --nosave, if you don't want to save in {dir2} your input (images/videos).
  4. --exist-ok, if you don't want to increment dir2{N} folder. (In this case yolo rewrite existing files in {dir2})

For better understanding pet example:

You RUN YOLO's detect.py in /home/yolov5/ dir for your source /home/train/images/, but you want to save only labels txt results in folder /home/train/labels/ without saving input images in result folder. And also no need to increment dir)

your command will look like:

!python detect.py --weights yolov5x6.pt --img 1280 --conf 0.45  --save-txt --source ../train/images/ --project ../ --name train/ --nosave --exist-ok

Only labels (txt files) with detected bboxes will be placed in /home/train/labels/. Because YOLO always saves its label-files in dir labels/

Alex
  • 316
  • 2
  • 5