[英]Trigger Event using key press?
我試圖讓我的程序僅在按下一個鍵時拍攝 8 張照片,但我找不到解決方案。 我嘗試了鍵盤 package 並且每當我按下鍵時都會拋出錯誤。 順便說一下,這是我的代碼-
import numpy as np
import cv2
import time
cap = cv2.VideoCapture('morning.mp4')
img_counter = 0
start_time = time.time()
x=0
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(47) & 0xFF == ord('q'):
break
#here is where the image capturing comes into play
if time.time() - start_time > 14: #<---- Check if 15 sec passed
img_name = "frame_{}.png".format(x)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_counter))
start_time = time.time()
x += 1
img_counter += 1
if x == 8:
break
cap.release()
cv2.destroyAllWindows()
在評論“#這里是圖像捕獲發揮作用的地方”之后,直到 break 語句是我為視頻拍照的地方,我想用按鍵觸發那部分代碼。 知道我應該如何 go 嗎?
問題是您在按鍵后中斷了while循環。 您應該使用一些 boolean 變量來指示腳本何時應該捕獲圖像。
代碼:
import numpy as np
import cv2
import time
cap = cv2.VideoCapture('morning.mp4')
img_counter = 0
start_time = time.time()
x=0
capture_images = False
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(47) & 0xFF == ord('q'):
capture_images = True
if capture_images:
#here is where the image capturing comes into play
if time.time() - start_time > 14: #<---- Check if 15 sec passed
img_name = "frame_{}.png".format(x)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_counter))
start_time = time.time()
x += 1
img_counter += 1
if x == 8:
break
cap.release()
cv2.destroyAllWindows()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.