How to capture Multi camera with Opencv Multi threading (python) [closed]
I am trying to achieve to get the streams from multiple ip cameras and display it. I have two ipcamera with urls : rtsp and rtsp1
When i run the following program, Only first window loads and works fine until the second thread kicks in.
Things works fine with multiple streams in the following methods :
- Works without threads. i.e
:
cam0 = cv2.VideoCapture(rtsp)
cam1 = cv2.VideoCapture(rtsp1)
ret, frame0 = cam0.read()
ret, frame1 = cam1.read()
show imshow(frame0) & (frame1)
But this method is primitive and get lags. Moreover not scalable with more cameras.
- If i run only one thread, the video streaming works fine.
- if i run it as two different python program targeting each rtsp stream, i have no issue. Again not practical for more cameras.
But the objective was to run multiple ipcamera from one single program. Any help to highlight the mistake i made would be highly appreciated.
import cv2
import os
import time
import threading
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
rtsp1 = 'rtsp://userid:[email protected]:8080/h264_ulaw.sdp'
rtsp='rtsp://userid:[email protected]:10554/udp/av0_0'
def getPicture(url):
cam = cv2.VideoCapture(url)
a=cam.get(cv2.CAP_PROP_BUFFERSIZE)
cam.set(cv2.CAP_PROP_BUFFERSIZE,3)
start_frame_number = 20
cam.set(cv2.CAP_PROP_POS_FRAMES, start_frame_number)
print("buffer"+str(a))
while True:
ret, frame = cam.read()
small_frame = cv2.resize(frame, (0, 0), fx=.50, fy=.50)
small_frame = cv2.cvtColor(small_frame,cv2.COLOR_BGR2GRAY)
cv2.imshow("camera",small_frame)
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
# When everything done, release the video capture object
cam.release()
# Closes all the frames
cv2.destroyAllWindows()
if __name__ == '__main__':
t1 = threading.Thread(target=getPicture, args=(rtsp,))
t2 = threading.Thread(target=getPicture, args=(rtsp1,))
t1.start()
t2.start()
you probably DONT need multithreading at all for this.
but IF SO, -- you have to keep all gui related code (imshow(),waitKey(),etc) on the main thread
As @berak, said that you don't need threading. OpenCV will take care for you. You indentation isn't correct in in
getPicture
function.@supra56. The indentation is not an issue. It could be due to cut copy paste. I am still able to get into the method. I will try @berak method.
@berak Noted thanks.As you suggested moved the imshow to the main method and implemented threads to process the face recognition and works absolutely fine.
Could you link to the final code please?