How to save Detected Class Name in Text file Instead of Label

I have a question on this please YOLOv5, as I have been searching all over google and cannot seem to get a fruitful response.

Can I get the same output using this command?

python3 detect.py --weights /Users/yolov5/runs/train/exp6/weights/best.pt  --img 640 --conf 0.25 --iou-thres  0.10 --source '/Users/vids50.mp4' --line-thickness 1 --save-txt

I want to get the output in text file when detect.py runs… The output will be a text file or csv file.

as demonstrate here:

#      xmin    ymin    xmax   ymax  confidence  class    name
      749.50   43.50  1148.0  704.5    0.874023      0  person
     114.75  195.75  1095.0  708.0    0.624512      0  person
     986.00  304.00  1028.0  420.0    0.286865     27     tie

Or it can be like the following in text file

#    
  0  person   749.50   43.50  1148.0  704.5    
  0  person  114.75  195.75  1095.0  708.0    
  27  tie        986.00  304.00  1028.0  420.0         

*** IF yes!! may I request your guidance to this example, please?*** I’ve been struggling with this expression for some weeks now.

I am getting the --saved txt files but not in the about format…please help
Thanx for acknowledging my digital requests.

@Hamad_Younis Yes, using the --save-txt flag, as you provided in your first snippet, is how you save the txt file.

@Mohamed But --save-txt file only save the labels not the classname. Can you modified the code so it can also save the class name

I can take a look at that portion. Of note, the first value in each line of the file is the class ID index value based on your obj.names file.

It will just require accessing the index for the class label name in obj.names and mapping it (as the key) to the class label name (value) in a variable that is of type, dictionary.

Then use the value (class label name) from the key:value pairs to map the index to the label name before appending it to the end of the line being written for the txt file.

  • note, the key is the class ID index value, and the file uses 0-base indexing (0, 1, 2, etc.)
  • make the keys as type string

The classes are listed alphabetically in that obj.names file, too. So if you know all of your class names in your trained model, you can make the dictionary without even viewing obj.names

@Mohamed Thanks

1 Like