I am trying to out the number of cars within a video that shows cars, trucks and buses, I want to put a counter at the top right to count the number of cars and ignore the rest. I managed everything accept for the counting, the number keeps going back to zero but I have put cars_count = 0 outside def annotate_image and before annotated_img = annotate_image(frame) but I got the error UnboundLocalError: local variable 'cars_count' referenced before assignment. My Code is below.
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, (600, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2) return imagevideo_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 = Nonev_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 pointersprint("\n[INFO] cleaning up...")v_out.release()v_in.release()