如何用pyqt5调用摄像头
时间: 2023-07-04 16:20:56 浏览: 142
要使用PyQt5调用摄像头,需要使用OpenCV库。以下是一个简单的示例代码:
```python
import cv2
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建QLabel用于显示图像
self.image_label = QLabel(self)
self.setCentralWidget(self.image_label)
# 打开摄像头
self.capture = cv2.VideoCapture(0)
# 设置定时器
self.timer = self.startTimer(5)
def timerEvent(self, event):
# 从摄像头获取图像
ret, frame = self.capture.read()
# 将OpenCV图像转换成QImage
image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
# 显示图像
self.image_label.setPixmap(pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
该代码创建了一个主窗口,其中包含一个QLabel用于显示摄像头图像。在定时器事件中,通过OpenCV库从摄像头获取图像,并将其转换为QImage格式,最后将其显示在QLabel中。注意,需要将摄像头的索引传递给VideoCapture()函数,例如0表示使用默认摄像头。
阅读全文
相关推荐

















