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



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

警报和视频可以在这里下载

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()

您可以在其他进程中启动报警。创建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()

最新更新