如何在 "while True:" 循环下的特定时期打印项目

How to print an item in particular period which is under "while True:" loop

我在这种情况下,由于循环,'Number of white and black pixels:' 被打印了数百万次。但是,我希望它每五秒打印一次。

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    low_p = np.array([136, 57, 0])
    high_p = np.array([255, 255, 255])

    mask = cv2.inRange(hsv_frame, low_p, high_p)
    p_mask= cv2.bitwise_and(frame, frame, mask=mask)

    number_of_white_pix = np.sum(mask == 255)
    number_of_black_pix = np.sum(mask == 0)

    print('Number of white pixels:', number_of_white_pix)
    print('Number of black pixels:', number_of_black_pix)

    cv2.imshow("Frame", frame)
    cv2.imshow("Pink mask", mask) 
    cv2.imshow("original mask", p_mask) 
    
    key = cv2.waitKey(1)
    if key == 27: 
        break

您应该可以使用时间模块来做到这一点。您可以将 t1 设置为开始时间,将 t2 设置为当前时间,每次循环运行时更新。一旦 t1t2 相隔 5 秒,您可以打印信息并将开始时间设置为 t2。这是应该工作的代码

import time

cap = cv2.VideoCapture(0)
t1 = time.time()
t2 = t1
while True:
    _, frame = cap.read()
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    low_p = np.array([136, 57, 0])
    high_p = np.array([255, 255, 255])

    mask = cv2.inRange(hsv_frame, low_p, high_p)
    p_mask= cv2.bitwise_and(frame, frame, mask=mask)

    number_of_white_pix = np.sum(mask == 255)
    number_of_black_pix = np.sum(mask == 0)

    if t2 - t1 >= 5:
        print('Number of white pixels:', number_of_white_pix)
        print('Number of black pixels:', number_of_black_pix)
        t1 = t2

    cv2.imshow("Frame", frame)
    cv2.imshow("Pink mask", mask) 
    cv2.imshow("original mask", p_mask) 

    t2 = time.time()
    
    key = cv2.waitKey(1)
    if key == 27: 
        break