Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading