When working with object detection using Ultralytics YOLO v8 in Python and attempting to add bounding boxes for classified objects to the camera image, it is possible to encounter a problem with the boxes field being undefined (equal to None).
The solution is to make sure you are using the yolov8n.pt model and not yolov8n-cls.pt: the latter does not seem to have this value set.
The -cls version of the model only returns text descriptions and not the bounding boxes.
In short the solution is to load the model using:
YOLO("yolov8n.pt")
instead of:
YOLO("yolov8n-cls.pt")
The following code shows a complete example of classifying objects using YOLO and adding bounding boxes.
Comments indicate where the problem with boxes being equal to None appears.
import cv2
from ultralytics import YOLO
captureObject = cv2.VideoCapture(0)
captureObject.set(3, 840)
captureObject.set(4, 780)
# Do not use yolov8n-cls.pt unless you do not need bounding boxes.
yoloModel = YOLO("yolov8n.pt")
# Get all class labels.
classLabels = list(yoloModel.names.values())
# Main loop.
while True:
ret, img = captureObject.read()
cv2.imshow("webcam", img)
# Classify objects.
results = yoloModel(img, stream=True)
for r in results:
boundingBoxes = r.boxes
# The value of boxes is None if using yolov8n-cls.pt
if boundingBoxes != None:
for box in boundingBoxes:
# Get coordinates.
x1, y1, x2, y2 = box.xyxy[0]
# Convert to integer types.
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
# Draw bounding box rectangle inside camera image.
cv2.rectangle(img,
(x1, y1),
(x2, y2),
(255, 0, 255),
3)
# Add classification label on top of bounding box.
classIndex = int(box.cls[0])
label = classLabels[classIndex]
cv2.putText(img,
label,
[x1, y1],
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255, 0, 0),
2)
# Re-paint with overlay rectangles.
cv2.imshow("webcam", img)
# Exit with 'q' key.
if cv2.waitKey(1) == ord("q"):
break
captureObject.release()
cv2.destroyAllWindows()