一、问题
现在我们试图读取一个双目摄像头设备,但其中一个摄像头有着明显的延迟。所以我们试图使用多线程(并行)来解决这一问题。但是在此之前,我们需要看一下串行的延迟所在,下面是一段串行代码的展示:
import cv2
cap = cv2.VideoCapture("rtsp://192.168.1.127/mpeg4/ch1")
cap1 = cv2.VideoCapture("rtsp://192.168.1.127/mpeg4")
# 更改内部缓冲区的帧数
cap.set(cv2.CAP_PROP_BUFFERSIZE, 3)
cap1.set(cv2.CAP_PROP_BUFFERSIZE, 3)
while ret:
ret, frame = cap.read()
ret1, frame1 = cap1.read()
cv2.imshow("frame", frame)
cv2.imshow("frame1", frame1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# End if
# End while
cv2.destroyAllWindows()
cap.release()
在上面的代码中,我们使用网络接口来获取图像,这里程序需要等待read()来完成两次抓取动作,红外部分因为读取速度慢,因而造成了高延迟。为此,我们决定使用两个线程来抓取图像,并且在主线程中显示。
二、使用多线程
import cv2, time
from threading import Thread
# cap1 = cv2.VideoCapture("rtsp://192.168.1.127/mpeg4/ch1")
# cap2 = cv2.VideoCapture("rtsp://192.168.1.127/mpeg4")
class CamWidget:
# Func 00 : init
# path:string, path of capture
def __init__(self, path):
self.cap = cv2.VideoCapture(path)
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3)
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
# End def
# Func 01 : update the frame
def update(self):
while True:
if self.cap.isOpened():
(self.status, self.frame) = self.cap.read()
# End if
time.sleep(.01)
# End while
# End def
# Func 02 : show img in main program
# widgetName: string
def show(self, widgetName):
cv2.imshow(widgetName, self.frame)
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
cv2.destroyAllWindows()
exit(1)
# End if
# End def
# End class
if __name__ == '__main__':
cap1 = CamWidget("rtsp://192.168.1.127/mpeg4/ch1")
cap2 = CamWidget("rtsp://192.168.1.127/mpeg4")
while True:
try:
cap1.show('cap1')
cap2.show('cap2')
except AttributeError:
pass
# End try
# End while
# End if
Comments | NOTHING