Object Detection Using Yolov8

I want to detect objects using yolov8 and then I want to print names of objects detected, like if person is detected then my program should print “person”.

Below code is detecting the objects, but I don’t know how to print names of objects deteted?
can somebody plz guide me?

from ultralytics import YOLO
from ultralytics.yolo.v8.detect.predict import DetectionPredictor
import cv2

model = YOLO(‘yolov8x.pt’)

results = model.predict(source = ‘0’, show=True)
#print(type(results))
print(results)

Output ::

0: 480x640 3 persons, 1447.4ms
0: 480x640 3 persons, 2 chairs, 1 dining table, 1391.4ms
0: 480x640 2 persons, 2 chairs, 2 dining tables, 1428.3ms
0: 480x640 2 persons, 2 chairs, 2 dining tables, 1397.4ms
0: 480x640 3 persons, 1 tie, 2 chairs, 2 dining tables, 1491.4ms
0: 480x640 3 persons, 1 tie, 2 chairs, 1 dining table, 1804.1ms
0: 480x640 3 persons, 2 chairs, 2 dining tables, 1425.5ms
0: 480x640 3 persons, 2 chairs, 1 dining table, 1355.4ms
0: 480x640 2 persons, 3 chairs, 2 dining tables, 1341.5ms
0: 480x640 2 persons, 1 tie, 2 chairs, 2 dining tables, 1387.3ms
0: 480x640 3 persons, 2 chairs, 1 dining table, 1397.6ms
0: 480x640 3 persons, 1 chair, 2 dining tables, 1448.9ms

I want to print only names of objects like person, chair.
can somebody plz tell me how can I do it

Hi @RehanAhmed

The results variable in your code seems to be a string that contains the information about the objects detected, including the names of the objects. To extract only the names of the objects, you can use string manipulation techniques such as splitting the string by comma and space, and then iterating through the resulting list to print the names of the objects.

objects = results.split(', ‘)
for obj in objects:
name = obj.split(’ ')[-1]
print(name)

This code first splits the results string by comma and space, resulting in a list of strings that contain the information about each object. Then, it iterates through the list, and for each string, it splits the string again by space. The last element of the resulting list is the name of the object, which is printed.

Also, it looks like you are using ultralytics package, it has its own built-in function for getting class names, you can use the function class_names() to get the names of the objects detected by model.
class_names = model.class_names()

Hope this helps!

Regards:
Muhammad John Abbas

1 Like

Hello @RehanAhmed, also try adding some parameters like results = model.predict(source = ‘0’, yolo task=detect, mode=predict, show=True) Thank you

results variable is not string, its list of torch.Tensors()

Hey @RehanAhmed
Thank you for clearing
You can use the function class_names() to get the objects detected by the model.
You can extract the class indices for each detection from the tensors in the results list. Each tensor in the list contains the information for each detection