I have a set of four IP cameras that stream over RTSP. I'm trying to read from all four cameras by creating four separate camera threads that continually read from the stream and then display on an OpenCV window. But so far I can read one single image and it won't display on the window. Below is the code:
import cv2
import threading
class CameraThread(threading.Thread):
def __init__(self, address, camera_id):
super(CameraThread, self).__init__()
self.camid = camera_id
self.addr = address
self.cap = cv2.VideoCapture(self.addr)
self.win = f'Camera {self.camid}'
cv2.namedWindow(self.win, cv2.WINDOW_NORMAL)
def show(self, im):
cv2.imshow(self.win, im)
key = cv2.waitKey(1)
if key == ord('q'):
self.finish()
def finish(self):
self.cap.release()
cv2.destroyWindow(self.win)
def capture(self):
if self.cap.isOpened():
ok, im = self.cap.read()
print('captured')
while True:
#cv2.imshow(self.win, im)
ok, im = self.cap.read()
print('capped')
self.show(im)
if not ok:
break
print('done')
self.finish()
def run(self):
self.capture()
def main():
url = 'rtsp://user:pwd@host:port/defaultPrimary-2?streamType=u'
t0 = CameraThread(url, '0')
t0.start()
if __name__ == '__main__':
main()
The code is almost verbatim from this SO post.
I have tried without threading and I can get a single video to stream and display. I also thought that maybe OpenCV GUI didn't work because work because I'm updating the GUI outside of the main thread.
Does anyone know why this doesn't work and have suggestions for a better way to do this?