我对这里发生的事情感到茫然。我正在尝试运行一个opencv VideoCapture进程来读取帧并放在队列中供工人处理。
应用程序永远不会完成运行,因为 CameraProcess 实例似乎永远不会终止。经过一番调查,看起来摄像机在调用 #release(( 后被报告为关闭,但在主进程上被视为打开。
我不应该从流程中创建视频捕获实例吗?
示例应用程序:
import cv2
from multiprocessing import Process, Event
from time import sleep
class CameraProcess(Process):
def __init__(self, camera_id, *args, **kwargs):
super(CameraProcess, self).__init__(*args, **kwargs)
self.shutdown = Event()
self.camera = cv2.VideoCapture(camera_id)
sleep(1)
print('Camera is opened? {}'.format(self.camera.isOpened()))
def run(self):
while not self.shutdown.wait(0.05):
print('Doing camera stuff')
sleep(1)
self.camera.release()
print('Camera is closed? {}'.format(not self.camera.isOpened()))
try:
camera = CameraProcess(0)
camera.start()
sleep(5)
camera.shutdown.set()
sleep(2)
print('Camera is closed? {}'.format(not camera.camera.isOpened()))
except KeyboardInterrupt:
pass
finally:
camera.terminate()
应用程序输出:
相机打开了?真做相机的事情做相机的事情做相机的事情做相机的事情做相机的事情相机关闭了?真相机关闭了?假
环境:
- Debian stretch
- 蟒蛇:3.5.3
- CV2: 3.4.0
奇怪的是,它应该被释放。但是相机资源仍然被占用。可能是错误?或者也许这是新事物的新事物...
为了正确释放资源,我定义了一个新方法,如下所示。然后它起作用了。
import cv2
from multiprocessing import Process, Event
from time import sleep
class CameraProcess(Process):
def __init__(self, camera_id, *args, **kwargs):
super(CameraProcess, self).__init__(*args, **kwargs)
self.shutdown = Event()
self.camera = cv2.VideoCapture(camera_id)
print('Camera is opened? {}'.format(self.camera.isOpened()))
def run(self):
while not self.shutdown.wait(0.05):
print('Doing camera stuff')
sleep(1)
self.camera.release()
print('[run ] Camera is closed? {}'.format(not self.camera.isOpened()))
## Defind a new method to release the resourse(again).
def shutup(self):
self.shutdown.set()
if self.camera.isOpened():
self.camera.release()
print('[shutup] Camera is closed? {}'.format(not self.camera.isOpened()))
try:
camera = CameraProcess(0)
camera.start()
sleep(5)
camera.shutup()
sleep(2)
print('[main ] Camera is closed? {}'.format(not camera.camera.isOpened()))
except KeyboardInterrupt:
pass
finally:
camera.terminate()
结果现在OK
。
Camera is opened? True
Doing camera stuff
Doing camera stuff
Doing camera stuff
Doing camera stuff
Doing camera stuff
[shutup] Camera is closed? True
[run ] Camera is closed? True
[main ] Camera is closed? True