AttributeError: ‘Prediction’ object has no attribute ‘label’

200 views Asked by At

I have code for recognizing road signs. Everything is implemented on Raspberry Pi 4. I'm using Python 3.9 and roboflow 1.1.12. 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="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)

I tried different attributes, like class/classes/class_id, and I have no idea what I need here in this block.

1

There are 1 answers

0
kvipe On

Jackob, it looks like you forgot to call .json() before trying to access predictions. Roboflow-python documentation shows an example how to use it. Below I will provide some of the code from there.

predictions = model.predict(img_url, hosted=True).json()
print(predictions)

YOUR code could look something like this

import json

# ...

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

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

for detection in detections:
    class_name = detection["class"]
    confidence = detection["confidence"]
    # some output here?

Keep in mind that there may be a situation where your roboflow model detect nothing on the picture. Hence the predictions list will be empty. You may have to do some additional checking for this.

You can easily try any model in action and see what data it outputs. Go to Roboflow Universe, search for "traffic signs" or "road signs". Next, select the model with which you want to test road signs recognition. I would focus on the number of images on which the model has been trained (the bigger the better). Next, click "Try Pre-Trained Model" and you get running in the cloud roboflow model (something like Hugging Face Spaces). Select an image and see what result the model produces. For example, I tried doing the steps I wrote above and got the following JSON, see my attached screenshot below. Such JSON you can get in your program if you adjust your code like I suggest you above.

Roboflow Universe playground