我在OpenCV中使用threading
模块时,遇到了一个奇怪的问题。当使用线程时,我无法再次启动摄像头来获取视频输入。我会拍一帧然后停下来。而在使用multiprocessing
模块时却没有这样的问题。我不能理解是什么导致了这种奇怪的行为。
这段代码总结了我遇到的问题,当第二次创建线程时,程序会卡住。
import cv2
import time
import threading
def open_cam():
count = 0
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
print(ret_val)
cv2.imshow("Image", img)
count += 1
if count == 100:
break
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
cv2.destroyAllWindows()
def start_thread():
print("CREATING THREAD")
cam_thread = threading.Thread(target=open_cam)
print("STARTING THREAD")
cam_thread.start()
start_thread()
time.sleep(5)
start_thread()
但是,这段代码的工作方式完全符合我的期望,它使用了multiprocessing
模块而不是threading
import cv2
import time
import multiprocessing
def open_cam():
count = 0
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
print(ret_val)
cv2.imshow("Image", img)
count += 1
if count == 100:
break
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
cv2.destroyAllWindows()
def start_process():
print("CREATING process")
cam_process = multiprocessing.Process(target=open_cam)
print("STARTING process")
cam_process.start()
start_process()
time.sleep(5)
start_process()
问题的根本原因是什么?我如何解决它?
https://stackoverflow.com/questions/56651537
复制相似问题