如何在循环"while True:"的特定时间段内打印项目



I在这种情况下,由于循环,"黑白像素数:"被打印了数百万次。但是,我希望每五秒钟打印一次。

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

相关内容

  • 没有找到相关文章

最新更新