gpt4 book ai didi

python线程: only one Python thread is running

转载 作者:行者123 更新时间:2023-12-01 01:47:54 27 4
gpt4 key购买 nike

我正在使用 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 似乎没有运行。而且它永远不会打印“准备打印!”。我该如何修复它?非常感谢!

最佳答案

根据documentationThread 构造函数的 target 参数是

the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

您正在传递webcam0_read(),它不是可调用的。您实际上正在调用 webcam0_read 函数,该函数陷入 while 循环中并且永远不会返回。其余代码甚至没有执行。

target 参数更改为 webcam0_readwebcam1_read:

t0=Thread(target=webcam0_read)
t0.setDaemon(True)
t0.start()
t1=Thread(target=webcam1_read)
t1.setDaemon(True)
t1.start()

关于python线程: only one Python thread is running,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51062255/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com