I work with YOLO8 My task is to determine the contours of the cars (that is, display them as rectangles), then make a count (for counting: the contour must cross the middle of the frame for two lanes of different traffic: oncoming and passing And at the end, count the total number of cars Loop and request the next frame each time and work should be done with it separately At the moment, I'm trying to draw the contours, but there's nothing on the video. In the output, I get something like this: `0: 384x640 27 cars, 1 truck, 1 tv, 93.0ms Speed: 1.9ms preprocess, 93.0ms inference, 0.4ms postprocess per image at shape (1, 3, 384, 640)
0: 384x640 26 cars, 2 trucks, 88.1ms Speed: 1.7ms preprocess, 88.1ms inference, 0.5ms postprocess per image at shape (1, 3, 384, 640)
0: 384x640 26 cars, 2 trucks, 104.2ms Speed: 1.5ms preprocess, 104.2ms inference, 0.6ms postprocess per image at shape (1, 3, 384, 640)`
My code:
import cv2
from ultralytics import YOLO
model = YOLO('yolov8s.pt')
video_path = 'output2.avi'
video = cv2.VideoCapture(video_path)
if not video.isOpened():
print("Ошибка: Не удается открыть видео.")
exit()
current_frame = 0
while True:
ret, frame = video.read()
if not ret:
break
current_frame += 1
results = model(frame)
car_results = [detection for detection in results if detection[-1] in [2, 5, 7]]
for result in car_results:
x1, y1, x2, y2, confidence, class_id = result.xyxy[0]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
I have tried various ways to fix the problem, but all attempts are unsuccessful
There is a misunderstanding of what the Yolov8 Results object is. Replace these lines of your script:
results = model(frame)
car_results = [detection for detection in results if detection[-1] in [2, 5, 7]]
for result in car_results:
x1, y1, x2, y2, confidence, class_id = result.xyxy[0]
to the following code:
results = model(frame)
for result in results:
for box in result.boxes:
class_id = int(box.cls.item())
if class_id in [2, 5, 7]:
x1, y1, x2, y2 = box.xyxy.tolist()[0]
More detailed answer to a similar question: https://stackoverflow.com/a/77733979/16071964