I am using opencv to detect the cars, buses and trucks in a video, using this annotate_image function but my loop keeps running even though I tried putting breaks at every juncture, the labels and boxes still change at every frame and I assume the counting of the cars will work once I figure out how to freeze the boxes and labels but that is also a second part I need working.
My code is below:
cars_count = 0found_car = Falsedef annotate_image(image): global cars_count, found_car # perform precidtion image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = model(image_rgb) 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 'car' in label: found_car = True else: found_car = False break #this break should have broken the for loop above but no luck cars_count_label = "{}:".format(cars_count) cv2.putText(image, cars_count_label, (600, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2) return image, found_carvideo_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) if found_car == True: cars_count = cars_count + 1 # 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[0])# release the file pointersprint("\n[INFO] cleaning up...")v_out.release()v_in.release()