Python threading issue in OpenCV

我们两清 提交于 2019-12-24 08:07:05

问题


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?


回答1:


This is caused by the Global Interpreter Lock. Threads share the program memory. To protect against conflicts caused by separate threads changing the same variable, Python locks execution to a specific thread. Meaning that at any moment only one thread runs. When the CPU is idle the program switches between threads, making IO-bound applications run faster. By contrast, Processes run simultaneously on separate cores and do not share memory.

When the second thread starts in your code, both Threads try to access the same variables. This causes the error with threads, while processes run fine.

Here is excellent and more lengthy explanation.



来源:https://stackoverflow.com/questions/56651537/python-threading-issue-in-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!