如何利用多進程優化Python視頻應用

若是要用Python播放視頻,或者打開攝像頭獲取視頻流,咱們能夠用OpenCV Python。可是在視頻幀獲取的時候同時作一些圖像識別和處理,可能會由於耗時多而致使卡頓。通常來講,咱們首先會想到把這些工做放入到線程中處理。可是因爲Python GIL的存在,用不用線程幾乎沒有區別。因此要解決這個問題,必須經過多進程。這裏分享下使用Dynamsoft Barcode Reader開發Python條形碼掃碼的例子。python

用Python和攝像頭打造的桌面條形碼掃碼應用

安裝Dynamsoft Barcode Reader:git

pip install dbr

安裝OpenCV Pythongithub

pip install opencv-python

在主程序中建立一個新的掃碼進程和共享內存:app

from multiprocessing import Process, Queue
frame_queue = Queue(4)
finish_queue = Queue(1)
dbr_proc = Process(target=dbr_run, args=(
        frame_queue, finish_queue))
dbr_proc.start()

經過OpenCV不斷獲取視頻幀插入到隊列中:ide

vc = cv2.VideoCapture(0)
 
if vc.isOpened():  # try to get the first frame
    rval, frame = vc.read()
else:
    return
 
windowName = "Barcode Reader"
base = 2
count = 0
while True:
    cv2.imshow(windowName, frame)
    rval, frame = vc.read()
 
    count %= base
    if count == 0:
        try:
            frame_queue.put_nowait(frame)
        except:
            try:
                while True:
                    frame_queue.get_nowait()
            except:
                pass
 
    count += 1

條形碼讀取進程不斷從隊列中拿出數據進行解碼:線程

def dbr_run(frame_queue, finish_queue):
    dbr.initLicense(config.license)
    while finish_queue.qsize() == 0:
        try:
            inputframe = frame_queue.get_nowait()
            results = dbr.decodeBuffer(inputframe, config.barcodeTypes)
            if (len(results) > 0):
                print(get_time())
                print("Total count: " + str(len(results)))
                for result in results:
                    print("Type: " + result[0])
                    print("Value: " + result[1] + "\n")
        except:
            pass
 
    dbr.destroy()

這樣基本完成。不過在app退出的時候會看到一些錯誤信息:code

Traceback (most recent call last):
 
File "E:\Programs\Python\Python36\lib\multiprocessing\queues.py", line 236, in _feed
 
send_bytes(obj)
 
File "E:\Programs\Python\Python36\lib\multiprocessing\connection.py", line 200, in send_bytes
 
self._send_bytes(m[offset:offset + size])
 
File "E:\Programs\Python\Python36\lib\multiprocessing\connection.py", line 290, in _send_bytes
 
nwritten, err = ov.GetOverlappedResult(True)
 
BrokenPipeError: [WinError 109] The pipe has been ended

記得在結束應用以前要清空隊列中的數據:視頻

def clear_queue(queue):
    try:
        while True:
            queue.get_nowait()
    except:
        pass
    queue.close()
    queue.join_thread()

程序運行效果:隊列

Python條形碼掃碼

源碼

https://github.com/dynamsoft-dbr/python/blob/master/examples/camera/camera_multiprocessing.py進程

相關文章
相關標籤/搜索