I am trying to conduct traffic analysis of an intersection by counting the number of cars entering and exiting each "arm" of the intersection. I followed ultralytics' docs to create one cross line and modified it to create and observe 4 cross lines. While all of the lines appear, the only one that actually seems to count cars is whichever that is defined first in my code. If I rearrange them, whatever is listed first will provide a count while the other 3 appear to flicker on the screen and do not provide any counts.
Here is my code:
from ultralytics import solutions, YOLO
model = YOLO("yolo26n.pt")
import cv2
cap = cv2.VideoCapture("intersection.mp4")
assert cap.isOpened(), "Error reading video file"
#creating cross lines
a = [(200, 275), (625, 250)]
b = [(150, 325), (175, 475)]
c = [(700, 275), (910, 400)]
d = [(375, 500), (910, 450)]
#Video writer
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH,
cv2.CAP_PROP_FRAME_HEIGHT,
cv2.CAP_PROP_FPS))
video_writer = cv2.VideoWriter("car_counting_output.avi",
cv2.VideoWriter_fourcc(*"mp4v"),
fps, (w, h))
#Initialize object counter object
counter1 = solutions.ObjectCounter(
region=a,
show=True,
show_conf=False,
line_width=5,
classes=[2, 7],
model="yolo26n.pt"
)
counter2 = solutions.ObjectCounter(
region=b,
show=True,
show_conf=False,
line_width=5,
classes=[2, 7],
model="yolo26n.pt"
)
counter3 = solutions.ObjectCounter(
region=c,
show=True,
show_conf=False,
line_width=5,
classes=[2, 7],
model="yolo26n.pt"
)
counter4 = solutions.ObjectCounter(
region=d,
show=True,
show_conf=False,
line_width=5,
classes=[2, 7],
model="yolo26n.pt"
)
#Process video
while cap.isOpened():
success, im0=cap.read()
if not success:
print("Video frame is empty or processing is complete.")
break
results1 = counter1(im0)
results2 = counter2(im0)
results3 = counter3(im0)
results4 = counter4(im0)
And a link to the video I used:
How can I provide a count from all four of these lines?