How can i print something in a For with no repeat?

Viewed 94

I have the following problem: I am using Yolo for a project to detect objects on videos, when the code detect an object i need a warning but the code send a lot of them and i only need once, I have understood that you can put a condition so the print is not repeated but I have no idea how to do it, this is part of the code:

for detection in detections:
    if detection is not None:
        detection = rescale_boxes(detection, opt.img_size, RGBimg.shape[:2])
        for x1, y1, x2, y2, conf, cls_conf, cls_pred in detection:
            box_w = x2 - x1
            box_h = y2 - y1                       
            color = [int(c) for c in colors[int(cls_pred)]]
            print("there is {}".format(classes[int(cls_pred)]))
            frame = cv2.rectangle(frame, (x1, y1 + box_h), (x2, y1), color, 5)
            cv2.putText(frame, classes[int(cls_pred)], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 5) 
            cv2.putText(frame, str("%.2f" % float(conf)), (x2, y2 - box_h), cv2.FONT_HERSHEY_SIMPLEX, 0.5,color, 5)

i solved the issue with this:

x=0
def add():
    global x
    x=x+1

i dont know if its the best way to solve it but it actually worked.

for detection in detections:
        if detection is not None:
            detection = rescale_boxes(detection, opt.img_size, RGBimg.shape[:2])
            for x1, y1, x2, y2, conf, cls_conf, cls_pred in detection:
                                 
                if x<=0:
                    add()
                    print("Se detectó posible {}".format(classes[int(cls_pred)]))
                box_w = x2 - x1
                box_h = y2 - y1                       
                color = [int(c) for c in colors[int(cls_pred)]]
                frame = cv2.rectangle(frame, (x1, y1 + box_h), (x2, y1), color, 5)
                cv2.putText(frame, classes[int(cls_pred)], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 5)# Nombre de la clase detectada
                cv2.putText(frame, str("%.2f" % float(conf)), (x2, y2 - box_h), cv2.FONT_HERSHEY_SIMPLEX, 0.5,color, 5) # Certeza de prediccion de la clase
1 Answers

If you only want to do something (e.g. print) on the first iteration, you can just set a flag:

first = True
for .........
            # somewhere inside your loop
            if first:
                # print or whatever
                first = False
Related