【问题标题】:Python threading problem for "self.running=Bool"“self.running=Bool”的 Python 线程问题
【发布时间】:2021-10-21 08:41:17
【问题描述】:

我想为立体视觉创建相机程序。因此我认为左右相机的程序。因为我想为我的相机单独工作。否则程序减速和相机会降低 fps。总之……

当我尝试 True 状态时;程序真正启动,但是当我按下停止按钮时,程序停止没有问题,但当我按下启动按钮时不会再次启动。

或者我尝试了无状态;当我按下开始按钮时,程序启动没有问题,但当我按下停止按钮时出现凸轮窗口。

from threading import Thread
import time
import cv2
import keyboard

class Left_Frame(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.running = False # True or False or None i tried...

    def run(self):
        cap = cv2.VideoCapture(0)
        while self.running:
            success, img = cap.read()
            cv2.imshow("qwe", img)
            tecla = cv2.waitKey(1) & 0xFf

    def stop(self):
        self.running = False

    def ss(self):
        self.running=True

left=Left_Frame()

if not left.is_alive():
    left.start()

while True:
    if keyboard.is_pressed('f'):
        left.stop()
        time.sleep(1)

    if keyboard.is_pressed('s'):
        left.ss()
        time.sleep(1)

【问题讨论】:

  • 如果你按下skey,你不应该将你的线程的状态设置为运行,你应该启动它(只要它还没有运行)。 start 方法应将状态设置为 running。
  • 那么,你能解释一下我必须做什么吗?
  • 看看你的代码。它指出:if keyboard.is_pressed('s'): left.ss()。而ss() 函数除了设置self.running = True 之外什么也不做。相反,您应该首先检查线程是否仍在运行。如果是这样,请忽略按下的键。如果它没有运行,请再次调用left.start()(这都可以在函数ss() 中完成)。 run()method 应该在输入时将 running 设置为 True。

标签: python multithreading class self


【解决方案1】:

这是解决方案。

from threading import Thread
import time
import urllib.request
import cv2
import keyboard


class left_Frame(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.running = True

    def run(self):
        cap = cv2.VideoCapture("http://192.168.137.109/stream")
        state=True
        while self.running:
            # print(state)

            if state==True:
                success, img = cap.read()
                cv2.imshow("left", img)
                tecla = cv2.waitKey(1) & 0xFf

            if keyboard.is_pressed('f'):
                state = False
                cap.release()
                cv2.destroyAllWindows()

            if keyboard.is_pressed('s'):
                if not state==True:
                    cap = cv2.VideoCapture("http://192.168.137.109/stream")
                    state = True

left=left_Frame()
left.start()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    相关资源
    最近更新 更多