读取本地摄像头比较简单,下面直接看代码就行。
原始版
import cv2
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret,frame = cap.read()
cv2.imshow("frame",frame)
cv2.waitKey(1)
优化版本
使用了多进程程和队列处理摄像头传输过来的图像帧,程序更加流畅
multiprocessing是pyhton下的进程管理包,像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多.
import cv2
import multiprocessing as mp
def queue_img_put(q):
cap = cv2.VideoCapture(0)
# cap.set(3,1280) #设置分辨率
# cap.set(4,720)
# cap.set(3,640) #设置分辨率
# cap.set(4,480)
while True:
is_opened, frame = cap.read()
q.put(frame) #if is_opened else None
def queue_img_get(q, window_name):
while True:
frame = q.get()
cv2.imshow("frame",frame)
#需要进行wait 不然窗口一闪而过
cv2.waitKey(1)
def run():
mp.set_start_method(method='spawn') # multi-processing init
queue = mp.Queue(maxsize=2)
processes = [mp.Process(target=queue_img_put, args=(queue)),
mp.Process(target=queue_img_get, args=(queue))]
[setattr(process, "daemon", True) for process in processes] # process.daemon = True
[process.start() for process in processes]
[process.join() for process in processes]
if __name__ == '__main__':
run()
pass
为什么要使用python多进程?
因为python使用全局解释器锁(GIL),他会将进程中的线程序列化,也就是多核cpu实际上并不能达到并行提高速度的目的,而使用多进程则是不受限的,所以实际应用中都是推荐多进程的。
如果每个子进程执行需要消耗的时间非常短(执行+1操作等),这不必使用多进程,因为进程的启动关闭也会耗费资源。
当然使用多进程往往是用来处理CPU密集型(科学计算)的需求,如果是IO密集型(文件读取,爬虫等)则可以使用多线程去处理。
网友评论