python - python线程:只有一个Python线程在运行
问题描述
我正在使用 python 和 opencv 处理网络摄像头,它似乎在阅读第一个和第二个之间滞后。所以我想用python线程来修复它。这是我的代码:
from cv2 import *
from threading import Thread, currentThread, activeCount
import numpy as np
webcam_address0="rtsp://192.168.1.109:6554/stream_0"
webcam_address1="rtsp://192.168.1.106:6554/stream_0"
cap0=VideoCapture(webcam_address0)
cap1=VideoCapture(webcam_address1)
count=0
flag_l=False
flag_r=False
def webcam0_read():
global frame0
global flag_l
while 1:
print('start reading l')
ret0, frame0 = cap0.read()
print('l done')
flag_l=True
def webcam1_read():
global frame1
global flag_r
while 1:
print('start reading r')
ret1, frame1 = cap1.read()
print('r done')
flag_r=True
t0=Thread(target=webcam0_read())
t0.setDaemon(True)
t0.start()
t1=Thread(target=webcam1_read())
t1.setDaemon(True)
t1.start()
while 1:
print('ready to print!')
if flag_l==True and flag_r==True:
frame0=resize(frame0,(640,360))
frame1=resize(frame1,(640,360))
imshow("Video Stream0", frame0)
imshow("Video Stream1", frame1)
if waitKey(5) == 's':
path0="~/images/"+str(count)+"l.jpg"
path1="~/images/"+str(count)+"r.jpg"
imwrite(path0,frame0)
imwrite(path1,frame1)
elif waitKey(5)==27:
break
当我运行它时,我只得到如下结果:开始阅读 l
我完成了
开始阅读 l
我完成了
开始阅读 l
我完成了
似乎线程 t1 没有运行。而且它从不打印“准备打印!”。我该如何解决?十分感谢!
解决方案
根据文档,构造函数的target
参数Thread
是
run() 方法调用的可调用对象。默认为 None,表示不调用任何内容。
您正在传递webcam0_read()
,这不是可调用的。您实际上是在调用该webcam0_read
函数,该函数卡在其while
循环中并且永远不会返回。其余的代码甚至没有执行。
target
将您的论点更改为webcam0_read
and webcam1_read
:
t0=Thread(target=webcam0_read)
t0.setDaemon(True)
t0.start()
t1=Thread(target=webcam1_read)
t1.setDaemon(True)
t1.start()
推荐阅读
- sql - 如何查询分组结果集中只有一条记录满足条件?
- java - javax.xml.bind.JAXBException 休眠 Java 10
- javascript - 如何使用 react 在 jquery 中添加 props 功能
- python - 在 Windows 上离线安装 tensorflow 时遇到问题
- ember.js - 如何在 Ember 中使用 thenable 和计算属性?
- javascript - Javascript 未加载到刀片引导模板中
- git - 如何将 git checkout 更改为原始
- java - 如何从 volley 方法更改本地/全局或返回变量
- gradle - 通过 gradle 执行 linux 命令返回退出状态 127
- r - 更改直方图 x 轴刻度