'How to turn 'Detections' object into string
I have this code which uses YOLOV5 and the weights of my trained model for inferencing images to detect and recognize the Egyptian currency. The object 'results' is of datatype 'Detections'. Is there someway to convert it into a string object as I need the label output for some purpose? I tried the str() function but it didn't work.
import torch
import os
import cv2
# Model
model = torch.hub.load(r'C:\Users\HAYA\PycharmProjects\curency_recognition\yolov5-master\yolov5-master', 'custom', path=r'C:\Users\HAYA\PycharmProjects\curency_recognition\_best.pt', source='local')
# Image
im = [r'E:\_currency.jpg']
# Inference
results = model(im)
# results
results.print()
results.save() # or .show()
results.show()
results.xyxy[0] # img1 predictions (tensor)
results.pandas().xyxy[0]
Solution 1:[1]
The following function is kind of "buggy" but it can give you the required results
def results_parser(results):
s = ""
if results.pred[0].shape[0]:
for c in results.pred[0][:, -1].unique():
n = (results.pred[0][:, -1] == c).sum() # detections per class
s += f"{n} {results.names[int(c)]}{'s' * (n > 1)}, " # add to string
return s
I run the default yolov5s on Zidane image from the original repository, after getting results object I did the following:
# Model
model = torch.hub.load(r'/content/yolov5//', 'custom', path=r'/content/yolov5/yolov5s.pt', source='local')
# Image
im = [r'runs/detect/exp/zidane.jpg']
# Inference
results = model(im)
print(results_parser(results))
and the output is:
2 persons, 2 ties,
I wish you find this answer helpful, have a good day)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mak13 |
