Hello! I am using opencv-python~=4.10.0.84
with flask
In my code, when flask app starts I push to global array cameras_list
entities (cameras) from sqlite database:
with app.app_context():
# Register main tasks
t = Thread(target=camera_stream_task, daemon=True)
t.start()
camera_stream_task:
def camera_stream_task():
while True:
with app.app_context():
cameras = Camera.query.all()
for camera in cameras:
if camera.id not in cameras_list:
cameras_list[camera.id] = OpenCV(camera)
task = Thread(target=camera_opencv_task, args=[camera], daemon=True)
task.start()
time.sleep(10)
OpenCV is my wrapper for cv2 and its look like this:
class OpenCV:
path: str | int = None
camera_directory: str = None
cameras_root: str = None
cap: cv.VideoCapture = None
camera: Camera = None
cover_timeout = 3
ret = None
frame: Mat = None
_cv = None
def __init__(self, _camera: Camera = None):
self._cv = cv
_path = Crypt.decrypt(_camera.path)
self.path = _path
self.cameras_root = os.path.join(_camera.storage.path, 'cameras')
self.camera_directory = os.path.join(_camera.storage.path, 'cameras', str(_camera.id))
self.cap = cv.VideoCapture(self.path)
self.camera = _camera
self.create_camera_directory()
print('Initialize class Opencv for camera', self.camera.id, 'path', self.path, 'cap is ', self.cap.isOpened())
def loop_frames():
while True:
if self.cap.isOpened():
ret, frame = self.cap.read()
if ret:
self.ret = ret
self.frame = frame
task = Thread(daemon=True, target=loop_frames)
task.start()
# other stuff
For tests I created 6 cameras (id 1,2,3,4,5,6) with the same urls:
- Three with
rtsp://...ip.../stream1
(id 1,2,3) - Three with
rtsp://...ip.../stream2
(id 4,5,6)
The problem is that cap is not opened for id (2,3,5,6)
Then I create a separate file with content:
def motionDetection():
# capturing video in real time
cap = cv2.VideoCapture('rtsp://...ip.../stream1')
print(cap.isOpened())
cap.release() # or without this line
if __name__ == "__main__":
motionDetection() # true
motionDetection() # true
motionDetection() # true
What could be the problem?