AttributeError: 'Prediction' object has no attribute 'label'

Hi! I have a code for recognizing road signs. Everything is implemented on Raspberry Pi 4. The code itself is below:

import requests
import cv2
import numpy as np
from picamera import PiCamera
from roboflow import Roboflow

# Инициализируем клиент Roboflow
rf = Roboflow(api_key="my_api_key")
project = rf.workspace().project("project_name")
model = project.version(1).model

# Инициализация камеры
camera = PiCamera()

# Загружаем классы для вывода результатов
classes = ['Stop', '60 km/h', '40 km/h', 'Forward']

# Захватываем видеопоток с камеры
camera.start_preview()
while True:
    # Снимаем фрейм с камеры и сохраняем его
    camera.capture('frame.jpg')

    # Загружаем фрейм и изменяем его размер
    image = cv2.imread('frame.jpg')
    image = cv2.resize(image, (300, 300))

    # Конвертируем изображение в формат RGB
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # Предсказываем на изображении
    result = model.predict(image_rgb)

    # Извлекаем информацию о дорожных знаках из результата
    detections = result.predictions

    for detection in detections:
        class_name = detection.label
        confidence = detection.confidence
        box = detection.bounding_box

        # Извлекаем координаты прямоугольника и делаем преобразования соответствующим образом

        # Рисуем прямоугольник и текст на изображении

    # Выводим результаты на экран
    cv2.imshow("Road Sign Detection", image)

    # Выход из цикла по нажатию клавиши 'q'
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Закрываем окна и освобождаем ресурсы камеры
cv2.destroyAllWindows()
camera.stop_preview()

But I get an error and I don’t understand which correct attribute is needed here.

Traceback (most recent call last): File "/home/rasberrypi/Desktop/Проект 3/ai17.py", 
line 38, in <module> class_name = detection.label 
AttributeError: 'Prediction' object has no attribute 'label' 

The error itself occurs when I show the desired road sign to the camera (that is, at the recognition stage)

Your code seems to be well-structured for running inference on a Raspberry Pi using Roboflow. However, it seems like the code is incomplete, as the last line is cut off.

Here’s a similar code snippet from the extracts that might help you:

from roboflow import Roboflow
rf = Roboflow(api_key="API_KEY")
project = rf.workspace().project("PROJECT_NAME")
model = project.version(MODEL_VERSION, local="http://localhost:9001").model

# infer on a local image
print(model.predict("your_image.jpg", confidence=40, overlap=30).json())

# visualize your prediction
# model.predict("your_image.jpg", confidence=40, overlap=30).save("prediction.jpg")

# infer on an image hosted elsewhere
# print(model.predict("URL_OF_YOUR_IMAGE", hosted=True, confidence=40, overlap=30).json())

Source

In your case, you might want to replace "your_image.jpg" with the image captured from your camera. Also, you might want to adjust the confidence and overlap parameters according to your needs.

For the incomplete part of your code, if you’re trying to break the loop when a certain key is pressed, you can use something like this:

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

This will break the loop when ‘q’ is pressed.

Please note that the code snippets provided are based on the information extracts and might need to be adjusted to fit your specific use case.


Hi! I’m Roboflow’s AI powered bot. This is an automated response powered using AI with knowledge from our docs, blog, and forum. If this solves your issue, please mark it as the solution using the checkbox icon. If this doesn’t solve your issue, please follow up with what you’ve tried/why, and the community will continue to chime in as usual.

Also tried attributes: class/classes/class_id/label

roboflow ver. 1.1.12

Python 3.9

Hi @Yashamaskaev

Sorry to hear you’re having trouble. The hosted inference API, which the Roboflow Python package uses, returns the following format. The class name is returned in a property called class under an array predictions.

If you already tried this, there might be another issue, so could you add a print statement, below that to see what the model result is?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.