【问题标题】:Python Sleep() function disturbing my video motionPython Sleep() 函数干扰了我的视频运动
【发布时间】:2022-01-18 08:01:43
【问题描述】:

我正在使用 python 进行我的最后一年项目(面罩检测)。我做了所有的事情,但我的指南建议在我的项目中附加一个通用警报系统。所以我附上了警报系统。这意味着如果有人没有戴口罩,那么它通常会以三种语言(泰米尔语、印地语、英语)发出警报。

但它需要一个单独的时间来运行这三个音频(泰米尔语 3 秒、印地语 2 秒和英语 1 秒)。所以我在我的程序中使用了睡眠功能sleep()。我成功连接了它,但是这个睡眠功能干扰了视频运动。这意味着如果我移动(带面具)并且有人移动(不带面具)它将在 6 秒后显示。所以它是慢动作。我什至尝试过多线程概念,但我无法实现它,所以我想要这个(如果有人没有戴口罩,那么它会播放这些音频,但不会干扰视频帧(慢动作))。

代码:

from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from imutils.video import VideoStream
import numpy as np
import imutils
import time
import cv2
import os
import voice
import threading
from pygame import mixer
mixer.init()
#sound=mixer.Sound('mixkit-security-facility-breach-alarm-994.wav')
alert1=mixer.Sound('Tamilalert.mp3')
alert2=mixer.Sound('Hindialert.mp3')
alert3=mixer.Sound('Englishalert.mp3')
#t2=threading.Thread(target=voice.alertsystem())
def detect_and_predict_mask(frame, faceNet, maskNet):
    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),
        (104.0, 177.0, 123.0))

    faceNet.setInput(blob)
    detections = faceNet.forward()
    print(detections.shape)

    faces = []
    locs = []
    preds = []

    for i in range(0, detections.shape[2]):
        
            confidence = detections[0, 0, i, 2]

            if confidence > 0.5:
                
                            
                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                (startX, startY, endX, endY) = box.astype("int")

                            
                (startX, startY) = (max(0, startX), max(0, startY))
                (endX, endY) = (min(w - 1, endX), min(h - 1, endY))

                    
                face = frame[startY:endY, startX:endX]
                face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
                face = cv2.resize(face, (224, 224))
                face = img_to_array(face)
                face = preprocess_input(face)

            
                faces.append(face)
                locs.append((startX, startY, endX, endY))

    if len(faces) > 0:
        
        faces = np.array(faces, dtype="float32")
        preds = maskNet.predict(faces, batch_size=32)

    return (locs, preds)


prototxtPath = r"face_detector\deploy.prototxt"
weightsPath = r"face_detector\res10_300x300_ssd_iter_140000.caffemodel"
faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)


maskNet = load_model("mask_detector.model")


print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()

while True:
    frame = vs.read()
    frame = imutils.resize(frame, width=1000)

  
    (locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet)


    for (box, pred) in zip(locs, preds):
        
        
          
        (startX, startY, endX, endY) = box
        (mask, withoutMask) = pred

        
        if mask>withoutMask:
            label = "Mask"
            color = (0, 255, 0)
            print("Normal")
        else:
            label = "No Mask"
            color = (0, 0, 255)
            alert1.play()
            time.sleep(3)
            alert2.play()
            time.sleep(2)
            alert3.play()
            time.sleep(1)
            #sound.play()
            #t2=threading.Thread(target=voice.alertsystem())
            #voice.alertsystem()
            print("Alert!!!")
            
        
        label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)

    
                   
        cv2.putText(frame, label, (startX, startY - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
        cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)

    
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

  
    if key == ord("q"):
            break


cv2.destroyAllWindows()
vs.stop()

    ```

    

    so kindly see else part of my program. and I hope you understood my problem kindly give solution 

【问题讨论】:

  • 您在线程方面做得对,我认为您需要尝试使其工作。排队“睡觉”当然会干扰您尝试执行的任何实时处理。
  • 使用 playsound 模块。
  • 首先,感谢您的回复,但这里的问题是睡眠功能每个音频都必须运行一些特定的时间示例泰米尔语 3 秒,所以我设置了 sleep(3),所以所有进程都停止到 3 秒,所以我想要同步.但我无法在那里实现多线程概念

标签: python tensorflow keras


【解决方案1】:

这里是更新的代码,所以你可以瘫痪睡眠功能。

我创建了一个使用线程模块调用的辅助函数。

# helper function 
def wait(time,alert):
    alert.play()
    sleep(time)

.

# the updated for loop
for (box, pred) in zip(locs, preds):
      
   (startX, startY, endX, endY) = box
   (mask, withoutMask) = pred

    
   if mask>withoutMask:

       label = "Mask"
       color = (0, 255, 0)
       print("Normal")

   else:

       label = "No Mask"
       color = (0, 0, 255)
       Thread(target=wait, args=(3,alert1,)).start()
       Thread(target=wait, args=(2,alert2,)).start()
       Thread(target=wait, args=(1,alert3,)).start()
       #sound.play()
       #t2=threading.Thread(target=voice.alertsystem())
       #voice.alertsystem()
       print("Alert!!!")

EDIT2

此代码运行 for 循环,如果 i == 2 则开始播放声音,然后在 3 秒后停止。但请注意我是如何定义警报的。我做了不同的事情。

from threading import Thread
from time import perf_counter, sleep
import pygame
import cv2

alert = pygame.mixer
alert.init()
alert.music.load("path_to_your_mp3_file")


def wait(time, alert):
    alert.music.play()            # starts the music
    #start = perf_counter()
    sleep(time)                   # waits 3 seconds
    #print(perf_counter() - start)
    alert.stop()                  # stops the music


for i in range(10):

    if i == 2:

        Thread(target=wait, args=(3, alert,)).start()

        print("Alert")

【讨论】:

  • 不,它不能正常工作。我尝试了这种方法。这就是为什么我提到我已经在我的问题中尝试过多线程概念。因为睡眠功能在线程之间不起作用。这意味着音频未完全播放(泰米尔语未播放 3 秒,印地语未播放 2 秒,英语未播放 1 秒)。所以请告诉任何其他方法。我想要这个(如果有小伙伴没有戴口罩,那么它会完全播放这三个音频,但不会影响视频运动)
  • 不,它不起作用。我已经尝试过这种方法,这就是为什么我提到我无法在我的问题中实现多线程概念。睡眠功能无法正常工作。这意味着泰米尔语音频也没有像所有其他音频一样播放 3 秒。所以请提供任何其他解决方案。请
  • @Aravindrajamani 我编辑了代码
  • 抱歉回复晚了。现在我也面临同样的问题。这意味着音频没有完全播放。我也实现了这个循环概念。同样的问题。睡眠功能持续时间不起作用,请帮我同步。
  • 音乐加载功能不起作用,播放变量显示错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多