[英]How to print statement only once inside a for loop
這是我的實時對象檢測代碼的一部分。(完整腳本: https : //github.com/aswinr22/waste-model/blob/master/picamera1.py )
for i in range (classes.size): # here is my classes id is retrieved
if(classes[0][i] == 2 and scores[0][i]>0.5):
print("e waste detected")
我的輸出是這樣的:
e waste detected
e waste detected
e waste detected
e waste detected..
.....
.... and so on.
我想要的只是打印一次這個聲明。 我該怎么辦請幫助我
如果您的條件被觸發,您可以使用break語句退出for循環。
編輯:沒有數據文件很難使這個工作完全與您在github上的代碼,但這是一個類似於您的用例的玩具示例:
classes= [0,2,2,1,2]
for item in (classes): # here is my classes id is retrieved
if(item == 2):
print("e waste detected")
break
print("post-loop")
刪除中斷,您將看到您現在看到的行為 - 但請注意縮進,它應該在if語句中。
試試這個(添加的代碼標有#NEW注釋)
...
waste_found = False # NEW
for frame1 in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
t1 = cv2.getTickCount()
# Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
frame = np.copy(frame1.array)
frame.setflags(write=1)
frame_expanded = np.expand_dims(frame, axis=0)
# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: frame_expanded})
# Draw the results of the detection (aka 'visulaize the results')
vis_util.visualize_boxes_and_labels_on_image_array(
frame,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8,
min_score_thresh=0.40)
# p = GPIO.PWM(servoPIN, 50)
# p.start(2.5)
for i in range(classes.size):
if (classes[0][i] == 2 and scores[0][i] > 0.5):
print("e waste detected")
waste_found = True # NEW
break # NEW
# elif(classes[0][i] == 1 and scores[0][i]>0.5):
# print("recycle detected")
# p.start(2.5) # Initialization
## p.ChangeDutyCycle(5)
# time.sleep(4)
# p.ChangeDutyCycle(10)
# time.sleep(4)
# except KeyboardInterrupt:
# p.stop()
# GPIO.cleanup()
if waste_found: # NEW
break # NEW
# return image_np
wasted = (c==2 and s>0.5 for c, s in zip(classes, scores))
if any(wasted):
print("wasted detected")
雙括號意味着生成器理解,當any
創建的第一個真值時它停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.