Open ali0806 opened 1 year ago
It is happen because In Python's multiprocessing
module, each process runs in its own separate memory space, so it's possible for two processes to try to open the same camera without being aware of each other.
For resolve this problem, you can use a Lock
or a Value
object to synchronize access to the camera, or use a process manager like concurrent.futures.ProcessPoolExecutor
to control the number of processes running at the same time.
Here in concurrent.futures.ProcessPoolExecutor(n)
we can pass the number of processes running at the same time. This will resolve our probelm
In multiprocessing, i can't access camera from the constructor. I need to define camera in get_frame
. For example,
class resizer:
def __init__(self):
self.cap = cv2.VideoCapture(0)
def image_resize(self):
succ, image = self.cap.read()
image = cv2.resize(image, (224, 224))
image = image.astype(np.float32)
image /= 255.0
return image
if __name__ == '__main__':
with concurrent.futures.ProcessPoolExecutor(1) as excutor:
future1=excutor.submit(resizer().image_resize)
future2=excutor.submit(resizer().image_resize)
future3=excutor.submit(resizer().image_resize)
future4=excutor.submit(resizer().image_resize)
cv2.imshow('a',future1.result())
cv2.imshow('b',future2.result())
cv2.imshow('c',future3.result())
cv2.imshow('d',future4.result())
cv2.waitKey(0)
Here I can't open camera. To open the camera I need to initialize self.cap =
cv2.VideoCapture(0)` inside the
image_resize` function.
def image_resize(self):
self.cap = cv2.VideoCapture(0)
succ, image = self.cap.read()
image = cv2.resize(image, (224, 224))
image = image.astype(np.float32)
image /= 255.0
return image
Article for multiprocessing: https://superfastpython.com/processpoolexecutor-in-python/
Why i can't access camera from constructor? @shivazi22 dada
It gives a error "can't open camera by index"