问题描述:
最近做直播系统,利用opencv进行图像采集处理,直播推出去的流发现延迟高且会累积延迟.
后面发现是opencv的cap.read()会有一定的缓存,不是读的实时帧.
解决办法:
多进程进行(python多线程不能利用多核,所以处理线程占用高的时候,读取线程会被阻塞)
一个进程进行处理,一个进程进行读取.直接用 Queue列队进行通信.参考文章
读取端进行put,但put之前先判断有多少缓存,然后删除缓存再put;
lenth = que.qsize()
print ("que lenth: ",lenth)
if lenth >2:
for i in range(lenth-2):
frame = que.get() #清除缓存
que.put(img)
处理端get就好.
过程中遇到的问题记录:
1. 使用 multiprocessing.Queue() 后进程不能停止.
解决办法:
manager = multiprocessing.Manager()
que = manager.Queue()
...
pro_read.terminate()
2. 只读了第一帧就卡住.
解决办法:
不把cap=VideoCapture(video)作为全局变量.放在子进程中.
测试代码:
# -*- coding:utf-8
import numpy as np
import multiprocessing
from multiprocessing import Process ,Queue
import random
import cv2
def run1(que,cap):
while 1:
ret,img = cap.read()
for i in range(200):
for j in range(200):
for k in range(3):
img[j,i,k] = random.randint(0,255)
lenth = que.qsize()
print ("que lenth: ",lenth)
if lenth >2:
for i in range(lenth-2):
frame = que.get() #清除缓存
que.put(img)
#pipe.send(img_q)
cv2.imshow("show",img)
cv2.waitKey(1000/23)
cv2.destroyAllWindows()
cap.release()
def test_1(que,cap):
run1(que)
def test_2(que):
while 1:
img = que.get()
#img = pipe.recv()
#img = cv2.resize(img,(360,240))
cv2.imshow("show2",img)
key = cv2.waitKey(1000/23)
if key == 27:
break
cv2.destroyAllWindows()
def cmd_send():
pass
if __name__ == "__main__":
manager = multiprocessing.Manager()
que = manager.Queue()
# que = Queue()
test1_start = 1
test2_start = 1
video = "/home/jiteng/桌面/寻梦环游记.mp4"
cap= cv2.VideoCapture(video)
t1 = Process(target=run1,args=(que,cap,))
# t2 = Process(target=test_2,args=(que,))
t1.start()
# t2.start()
test_2(que)
#
t1.terminate()