我正在尝试为图像处理项目创建一个网络摄像头视频流,并且我想要一种暂停流的方法(因为它对于检查值、掩码等非常有用) 我确实找到了一种使用 time.sleep() 暂停一定时间的简单方法,但这并不是我真正想要的。
我真正想要的是一种在按下空格键时暂停流,并在释放它时取消暂停的方法。 在我看来,按住某个键是最简单的选择,因为这仅意味着检查在帧开始时是否按下了按钮,如果是,则跳过该特定帧。但是,我在这里尝试的代码(使用继续跳过帧)不起作用。
有什么建议吗?
from imutils.video import VideoStream
import imutils
import time
import cv2
vs = VideoStream(src=0).start()
while True:
key = cv2.waitKey(1) & 0xFF
if key == ord("q"): break # quitting when q is pressed
# if key == ord(" "): time.sleep(5)
if key == ord(" "): continue
frame = vs.read()
frame = imutils.resize(frame, width=500)
if frame is None:
print("Oops, something went wrong")
break
# Image processing over here
cv2.imshow("Frame", frame)
vs.stop()
cv2.destroyAllWindows()
此外,如果有人对我的代码有任何其他提示或建议,请告诉我。
最佳答案
您可以将空格键用作开关,而不是连续按下它。按一次停止,再按一次启动,依此类推。为此,只需使用一个标志变量,只要按下空格键,该变量就会更改值。我使用了这段代码并且它有效:
import cv2
cap = cv2.VideoCapture(0)
flag = True
while(True):
if cv2.waitKey(1) & 0xFF == ord(' '):
flag = not(flag)
print(flag)
# Capture frame-by-frame
if flag == True:
ret, frame = cap.read()
if frame is None:
break
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
continue
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
编辑(评论)
我做了一些测试来检查使用以下代码连续按下空格按钮所获得的值:
import cv2
cap = cv2.VideoCapture(0)
while(True):
key = cv2.waitKey(1) & 0xFF
print(key)
if key == ord(' '):
continue
elif key != ord('q'):
# Capture frame-by-frame
ret, frame = cap.read()
if frame is None:
break
# Display the resulting frame
cv2.imshow('frame',frame)
else:
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
但是,即使连续按空格键,打印的值仍然是
.
.
.
255
32
255
32
255
255
32
32
255
32
255
113
其中 255 代表空白,32 代表空格,113 代表“q”。很抱歉,但我不知道发生这种情况的原因,但这需要解决,否则按住空格键将不起作用。
关于python - 如何在按住某个键的同时暂停视频流? Python OpenCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529277/