python - python线程不工作。解决方案是什么?
问题描述
这部分代码已将 pysimple gui 应用于 yolo。
我想试试这段代码中的线程,
我想在“while”中运行一个线程并每 2.5 秒打印一个句子。
但是,这个函数不是每 2.5 秒运行一次,而是每一个 when 循环。
在while循环中每2.5秒运行一次的方式是什么
import PySimpleGUIQt as sg
##########thread test########################
def print_text():
print("yolo run")
threading.Timer(2.5, print_text).start()
################################################
线程测试方法
# loop over frames from the video file stream
win_started = False
if use_webcam:
cap = cv2.VideoCapture(0)
while True:
print_text()###########################################test thread
何时在while循环中声明线程函数
# read the next frame from the file or webcam
if use_webcam:
grabbed, frame = cap.read()
else:
grabbed, frame = vs.read()
# if the frame was not grabbed, then we have reached the end
# of the stream
if not grabbed:
break
# if the frame dimensions are empty, grab them
if W is None or H is None:
(H, W) = frame.shape[:2]
# construct a blob from the input frame and then perform a forward
# pass of the YOLO object detector, giving us our bounding boxes
# and associated probabilities
blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),
swapRB=True, crop=False)
net.setInput(blob)
start = time.time()
layerOutputs = net.forward(ln)
end = time.time()
# initialize our lists of detected bounding boxes, confidences,
# and class IDs, respectively
boxes = []
confidences = []
classIDs = []
# apply non-maxima suppression to suppress weak, overlapping
# bounding boxes
idxs = cv2.dnn.NMSBoxes(boxes, confidences, gui_confidence, gui_threshold)
# ensure at least one detection exists
if len(idxs) > 0:
# loop over the indexes we are keeping
for i in idxs.flatten():
# extract the bounding box coordinates
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
# draw a bounding box rectangle and label on the frame
color = [int(c) for c in COLORS[classIDs[i]]]
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
text = "{}: {:.4f}".format(LABELS[classIDs[i]],
confidences[i])
cv2.putText(frame, text, (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
imgbytes = cv2.imencode('.png', frame)[1].tobytes() # ditto
解决方案
也许您将 while 循环放在线程将执行的代码中。
import time
from threading import Thread
def print_text():
while True:
print('yolo run')
time.sleep(2.5)
# Thread waits 2.5 seconds and then return to the beginning of the while loop
对于您的主要代码
# creating thread
print_thread = threading.Thread(target=print_text(), args=(1,))
# start thread
print_thread.start()
# wait thread to finish
print_thread.join()
此代码将创建一个能够进行计算的单个线程,直到满足某些停止条件。
推荐阅读
- tensorflow2.0 - 如何在本地从 tensorflow 数据集下载数据集
- xml - 如何在 MSIX 安装程序包模板中指定自动启动扩展节点
- sql - 尝试在 Linux 中通过 shell 脚本向 oracle 数据库表插入记录时出错
- python - 在while循环之外避免ValueError?
- swift - 在 SwiftUI 中使用 Image 和 SFSymbols 时如何获得统一的视图大小?
- python - 如何使用字符串从列表中找到正确的字符串或 3 个最相似的字符串?
- r - 如何使用 R 中连续 id 计数的开始和结束时间戳合并行,但基于每个组?
- javascript - 单击时 AddEventListener 没有进入他的回调函数
- git - git clone 找不到远程仓库
- python-3.x - 如何获取存储在 sqlite3 数据库中的数据并将其分配给 tkinter python 中的变量