Pyqt5视频流中画出框框住对象
时间: 2024-04-10 17:10:31 浏览: 112
Python3使用PyQt5制作简单的画板/手写板实例
要在PyQt5视频流中画出框来框住对象,可以使用OpenCV库的诸多功能,其中包括在图像上绘制框框。下面是一个简单的示例代码,可以在视频流中框出人脸。
```python
import cv2
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(0, 0, 640, 480))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.timer = QTimer()
self.timer.timeout.connect(self.update_frame)
self.capture = cv2.VideoCapture(0)
self.timer.start(5)
def update_frame(self):
ret, frame = self.capture.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
self.label.setPixmap(pixmap)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
```
在这个示例代码中,我们使用了OpenCV的`cv2.CascadeClassifier`函数来检测人脸,并使用`cv2.rectangle`在视频帧上绘制矩形框。最后将帧转换为QImage并在PyQt5窗口中显示。
阅读全文