pyqt5调用usb摄像头
时间: 2023-11-06 18:05:19 浏览: 161
可以使用OpenCV库和PyQt5来调用USB摄像头。首先,你需要安装OpenCV和PyQt5库。然后,你可以使用OpenCV的VideoCapture函数来获取摄像头的图像。接下来,你可以将图像显示在PyQt5的GUI界面上。
这是一个使用PyQt5调用USB摄像头的简单示例代码:
```python
import sys
import cv2
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class Webcam(QWidget):
def __init__(self):
super().__init__()
self.label = QLabel(self)
self.image = None
self.timer = QTimer()
self.timer.timeout.connect(self.update_frame)
self.timer.start(10)
layout = QVBoxLayout()
layout.addWidget(self.label)
self.setLayout(layout)
def update_frame(self):
ret, frame = self.cap.read()
if ret:
self.image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = self.image.shape
bytes_per_line = ch * w
q_image = QImage(self.image.data, w, h, bytes_per_line, QImage.Format_RGB888)
self.label.setPixmap(QPixmap.fromImage(q_image))
else:
self.timer.stop()
def start_camera(self, device=0):
self.cap = cv2.VideoCapture(device)
def closeEvent(self, event):
self.cap.release()
super().closeEvent(event)
if __name__ == '__main__':
app = QApplication(sys.argv)
webcam = Webcam()
webcam.start_camera()
webcam.show()
sys.exit(app.exec_())
```
阅读全文