I am trying to count the number of cars within a video, but for some reason the count keeps resetting to zero and when I put cars_count = 0 outside of def annotate_image it says that I am referencing a variable before assignment, I also tried putting it above the annotated_img = annotate_image(frame) line too and it’s the same error referencing variable before assignment
def annotate_image(image):
# perform precidtion
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = model(image_rgb)
cars_count = 0
for i in range(len(results.pandas().xyxy[0].name)):
name = results.pandas().xyxy[0].name[i]
startX = int(results.pandas().xyxy[0].xmin[i])
startY = int(results.pandas().xyxy[0].ymin[i])
endX = int(results.pandas().xyxy[0].xmax[i])
endY = int(results.pandas().xyxy[0].ymax[i])
confidence = results.pandas().xyxy[0].confidence[i]
label = "{}: {:.2f}%".format(name, confidence * 100)
if confidence > 0.6:
cv2.rectangle(image, (startX, startY), (endX, endY),
(255,0,0), 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(image, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)
if name == "car":
cars_count = cars_count + 1
cars_count_label = "{}:".format(cars_count)
cv2.putText(image, cars_count_label, (400, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)
return image
video_in_file = "/content/drive/MyDrive/Colab_Notebooks/data/toycars.mp4"
video_out_file = "/content/drive/MyDrive/Colab_Notebooks/data/out.mp4"
print("[INFO] accessing video stream...")
v_out = None
v_in = cv2.VideoCapture(video_in_file)
total_frame = int(v_in.get(cv2.CAP_PROP_FRAME_COUNT ))
for frame_no in tqdm(range(total_frame), desc="Processing Video..."):
(grabbed, frame) = v_in.read()
# if the frame was not grabbed then we've reached the end of
# the video stream so exit the script
if not grabbed:
print("[INFO] no frame read from stream - exiting")
break
annotated_img = annotate_image(frame)
# check if the video writer is None
if v_out is None:
# initialize our video writer
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
v_out = cv2.VideoWriter(video_out_file, fourcc,
int(v_in.get(cv2.CAP_PROP_FPS)),
(frame.shape[1], frame.shape[0]), True)
# write the output frame to disk
v_out.write(annotated_img)
# release the file pointers
print("\n[INFO] cleaning up...")
v_out.release()
v_in.release()