日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python多进程优化_如何利用多进程优化Python视频应用

發(fā)布時間:2024/9/18 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python多进程优化_如何利用多进程优化Python视频应用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

如果要用Python播放視頻,或者打開攝像頭獲取視頻流,我們可以用OpenCV Python。但是在視頻幀獲取的時候同時做一些圖像識別和處理,可能會因為耗時多而導致卡頓。一般來說,我們首先會想到把這些工作放入到線程中處理。但是由于Python GIL的存在,用不用線程幾乎沒有區(qū)別。所以要解決這個問題,必須通過多進程。這里分享下使用Dynamsoft Barcode Reader開發(fā)Python條形碼掃碼的例子。

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

安裝Dynamsoft Barcode Reader:

pip install dbr

安裝OpenCV Python

pip install opencv-python

在主程序中創(chuàng)建一個新的掃碼進程和共享內存:

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不斷獲取視頻幀插入到隊列中:

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

條形碼讀取進程不斷從隊列中拿出數(shù)據(jù)進行解碼:

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退出的時候會看到一些錯誤信息:

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

記得在結束應用之前要清空隊列中的數(shù)據(jù):

def clear_queue(queue):

try:

while True:

queue.get_nowait()

except:

pass

queue.close()

queue.join_thread()

程序運行效果:

源碼

總結

以上是生活随笔為你收集整理的python多进程优化_如何利用多进程优化Python视频应用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。