首页 > 解决方案 > 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

    

标签: pythonmultithreadinguser-interfaceyolopysimplegui

解决方案


也许您将 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()

此代码将创建一个能够进行计算的单个线程,直到满足某些停止条件。


推荐阅读