如何在python中的if语句之后运行视频

2024-09-02 03:42:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用OpenCV创建了一个代码来检测视频中的火灾,该技术使用HSV颜色空间来检测颜色并标记报警,但问题是报警何时启动视频窗口停止,或者从程序开始就不显示。有人能帮忙吗

警报和视频可下载here

import cv2
import numpy as np
import playsound

Alarm_Status = False

def play_sound():
    playsound.playsound("Alarm Sound.mp3",True)

# Importing the video
cam = cv2.VideoCapture("Fire.mp4")

while True:
    # Reading the camera
    ret, frame = cam.read()
    
    # Converting the color to HSV
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    
    # Set the color boundaries
    lower = np.array([18, 50, 50], dtype = "uint8")
    upper = np.array([35, 255, 255], dtype = "uint8")
    
    # Color detection
    mask = cv2.inRange(hsv_frame, lower, upper)
    
    # Create the Output video
    output = cv2.bitwise_and(frame, hsv_frame, mask = mask)
    
    # Count the number of red pixels
    redPixels = cv2.countNonZero(mask)
    
    if int(redPixels) > 1000 and Alarm_Status == False:
        playsound()
        Alarm_Status = True
        pass
    
    # Showing the video
    cv2.imshow("Output", output)
    
    # Stoping the code
    if cv2.waitKey(25) == ord("q"):
        break
        
# Destroy the window
cv2.destroyAllWindows()
cam.release()

1条回答
网友
1楼 · 发布于 2024-09-02 03:42:15

您可以在其他过程中启动警报。创建alarm.py文件:

import playsound
playsound.playsound("Alarm Sound.mp3",True)

在主应用程序中,您可以调用alarm.py

import cv2
import numpy as np
import playsound
import subprocess
Alarm_Status = False


# Importing the video
cam = cv2.VideoCapture("Fire.mp4")

while True:
    # Reading the camera
    ret, frame = cam.read()
    
    # Converting the color to HSV
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    
    # Set the color boundaries
    lower = np.array([18, 50, 50], dtype = "uint8")
    upper = np.array([35, 255, 255], dtype = "uint8")
    
    # Color detection
    mask = cv2.inRange(hsv_frame, lower, upper)
    
    # Create the Output video
    output = cv2.bitwise_and(frame, hsv_frame, mask = mask)
    
    # Count the number of red pixels
    redPixels = cv2.countNonZero(mask)
    
    if int(redPixels) > 1000 and Alarm_Status == False:
        subprocess.Popen(["/usr/bin/python3","./alarm.py"])
        Alarm_Status = True
        pass
    
    # Showing the video
    cv2.imshow("Output", output)
    
    # Stoping the code
    if cv2.waitKey(25) == ord("q"):
        break
        
# Destroy the window
cv2.destroyAllWindows()
cam.release()

相关问题 更多 >