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

Time:01-28

I in this condition, 'Number of white and black pixels:' is printed millions of time owing to the loop. However, I want it to be printed every five seconds.

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

CodePudding user response:

You should be able to do that using the time module. You can set t1 as the start time and t2 as the current time, updating every time the loop runs. Once t1 and t2 are 5 seconds apart, you can print the information and set the start time to t2. Here is the code that should work

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
  •  Tags:  
  • Related