以下代碼在 MacOS Big Sur 和 Windows 10 上的 python 3.8 上運行良好:使用“q”退出并且可以多次重新運行。
但是在 Ubuntu 20.04 上,它不會在 'q' 上釋放網路攝像頭資源,隨后的運行回傳VIDIOC_QBUF: No buffer space available. 系統需要硬重啟才能解決這個問題。
如果我注釋掉該行cam_process.terminate(),則代碼不會在 'q' 上退出,直到CTRL-C被按下。
我應該如何:
- 更正代碼以
cam_process.terminate()在 Ubuntu 上發布網路攝像頭資源? - 更正代碼以在沒有
cam_process.terminate()?
任何對原因的技術見解都是最受贊賞的。
編輯:修復 f 字串拼寫錯誤。
import multiprocessing
import cv2
# Notes:
# 0. Tested on python 3.8 on all platforms.
# 1. Code works fine on MacOS and Windows. Can quit and run many times.
# 2. Code does NOT release webcam on Ubuntu, needs hard reboot!
# Problem caused by line *: cam_process.terminate()
# Subsequent runs gets VIDIOC_QBUF: No buffer space available error
# 3. If comment out line *, then subprocess does not end, needs CTRL-C to break.
def cam_loop(cam_image_queue, msg_queue):
cap = cv2.VideoCapture(0)
while True:
hello, img = cap.read()
cam_image_queue.put(img)
if not msg_queue.empty():
print("got quit msg")
break
print(f"before cap release, isOpened={cap.isOpened()}")
cap.release()
print(f"after cap release, isOpened={cap.isOpened()}")
def main():
cam_image_queue = multiprocessing.Queue()
msg_queue = multiprocessing.Queue()
cam_process = multiprocessing.Process(
target=cam_loop,
args=(cam_image_queue, msg_queue,),
)
print("starting process...")
cam_process.start()
while True:
if cam_image_queue.empty():
continue
img = cam_image_queue.get()
cv2.imshow("from queue", img)
key = cv2.waitKey(1)
if key == ord("q"):
msg_queue.put("quit")
break
print("closing process...")
# using terminate() or close() will hang webcam resource on Ubuntu!
cam_process.terminate() # *
all_done = False
while not all_done:
cam_process.join(1)
if cam_process.exitcode is not None:
all_done = True
else:
print("code=", cam_process.exitcode)
print("after cam_process join")
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
uj5u.com熱心網友回復:
好的,在過去 2 個小時的作業之后,我終于得到了自己的答案 2,在沒有cam_process.terminate().
代碼無法正確退出(掛起),因為cam_image_queue不是空的。它包含cam_loop. 重繪 后cam_image_queue,程式按預期正常退出并正確釋放網路攝像頭資源。與 MacOS 或 Windows 相比,Ubuntu 似乎更注重重繪 佇列。
回答1:不要呼叫,cam_process.terminate()因為它會在沒有正確釋放資源的情況下殺死行程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/346583.html
標籤:Python opencv 乌本图 python-多处理
上一篇:指標(GoLang)
