I was using threading module with OpenCV, I came accross a bizarre issue. When using thread I was unable to start the camera again to take video input. I would take one frame and then stop. While there was no problem like this when using multiprocessing module. I am unable to understand what causes this strange behaviour.
This code summarizes the problem I have, The program will stuck when the thread is created second time.
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()
However, This code works exactly how I desire, This uses multiprocessing module instead of 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()
What is the root cause of the problem and How can I fix it?