'Print 1 once when object is identified in endless while loop

flag = True
while True:
    cap = cv2.VideoCapture(0)
    cap.set(3, 640)
    cap.set(4, 480)

    if flag:
        success, img = cap.read()

        result, objectInfo = getObjects(img, 0.72, 0.2)
       
        if result:
            cv2.imshow("Output", img)
            print('1')
        else:
            print('no dog or cat')
    cv2.waitKey(0)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Error is referring to line "if result:"

That is the error I get. I mainly want it to print 1 only once when the web camera identifies an object



Solution 1:[1]

@ghernandez. You are not writing code probably. Here is snipped:

def getObjects(img, thres, nms, draw=True):
    classIds, confs, bbox = net.detect(img,confThreshold=thres,nmsThreshold=nms)
    #print(classIds,bbox)
    objectInfo =[]
    if len(classIds) != 0:
        for classId, confidence,box in zip(classIds.flatten(),confs.flatten(),bbox):
            className = classNames[classId - 1]

            # here we need to insert some lines of code
            if className in ooi:
                print('something')
            else:
                print('something else')

            objectInfo.append([box,className])
            if (draw):
                cv2.rectangle(img,box,color=(0,255,0),thickness=2)
                cv2.putText(img,classNames[classId-1].upper(),(box[0]+10,box[1]+30),
                cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)
                cv2.putText(img,str(round(confidence*100,2)),(box[0]+200,box[1]+30),
                cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)
    
    return img,objectInfo


if __name__ == "__main__":
    cap = cv2.VideoCapture(0)
    cap.set(3,640)
    cap.set(4,480)

    while True:
        success, img = cap.read()
        result, objectInfo = getObjects(img,0.45,0.2)
        #print(objectInfo)
        cv2.imshow("Output",img)

        # break the loop if Esc is pressed
        if cv2.waitKey(1) == 27:
            break

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 toyota Supra