【发布时间】:2023-03-06 09:56:01
【问题描述】:
我开发了一个包含按钮的应用程序。单击按钮后,它开始运行网络摄像头以使用 OpenCV 在无限循环中捕获帧。当用户按下“Q”时,程序会释放网络摄像头实例。当我关闭应用程序时,应用程序成功关闭,但网络摄像头实例没有被释放并继续运行。如何确保在关闭应用程序时释放网络摄像头资源。
网络摄像头.py:-
import cv2
def hello():
camera = cv2.VideoCapture(0)
top, right, bottom, left = 10, 350, 225, 590
num_frames = 0
while True:
_, frame = camera.read()
clone = frame.copy()
roi = frame[top:bottom, right:left]
cv2.rectangle(clone, (left, top), (right, bottom), (0, 255, 0), 2)
num_frames += 1
cv2.imshow("Video Feed", clone)
keypress = cv2.waitKey(1) & 0xFF
if keypress == ord("q"):
break
camera.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
hello()
Application.py:-
from PyQt5 import QtCore, QtGui, QtWidgets
from Webcam import hello
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.window = MainWindow
self.window.setObjectName("self.window")
self.window.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(self.window)
self.centralwidget.setObjectName("centralwidget")
self.startButton = QtWidgets.QPushButton(self.centralwidget)
self.startButton.setText("&Start")
self.startButton.clicked.connect(self.open_cam)
self.window.setCentralWidget(self.centralwidget)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def open_cam(self):
hello()
class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setupUi(self)
def closeEvent(self, event):
result = QtWidgets.QMessageBox.question(self,
"Confirm Exit...",
"Are you sure you want to exit ?",
QtWidgets.QMessageBox.Yes| QtWidgets.QMessageBox.No)
event.ignore()
if result == QtWidgets.QMessageBox.Yes:
event.accept()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
【问题讨论】:
-
尝试将
from PyQt5 import QtCore行添加到Webcam.py模块 -
不行还是无法释放资源
-
它对我有用。然后尝试在
cv2.destroyAllWindows ()行之后添加行QtCore.QCoreApplication.quit () -
好的,我现在明白了。您正在做的是尝试通过按“q”来关闭应用程序,这会首先释放网络摄像头实例并关闭应用程序。但我正在寻找的是关闭应用程序按下“X”,这也应该释放网络摄像头资源,但在这种情况下,网络摄像头资源没有被释放并且应用程序正在关闭。
标签: python python-3.x opencv pyqt pyqt5