Python 3 +OpenCV + PyQt6 to display usbcam
A simple exercise run on Windows 11/Python 3.13.0 to capture images from
usbcam display with GUI using OpenCV and PyQt6.
It's tested in
Python virtual environment on Windows 11, with OpenCV aand PyQt6
installed.
pyqt6_cv2_usbcam.py, actually it's provided by MicroSoft Copilot.
import sys
import cv2
from PyQt6.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout
from PyQt6.QtGui import QImage, QPixmap
from PyQt6.QtCore import QTimer
class WebcamViewer(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.cap = cv2.VideoCapture(0)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(20)
def initUI(self):
self.setWindowTitle('Webcam')
self.image_label = QLabel(self)
layout = QVBoxLayout()
layout.addWidget(self.image_label)
self.setLayout(layout)
def update_frame(self):
ret, frame = self.cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
convert_to_Qt_format = QImage(frame.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
self.image_label.setPixmap(QPixmap.fromImage(convert_to_Qt_format))
def closeEvent(self, event):
self.timer.stop()
self.cap.release()
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
viewer = WebcamViewer()
viewer.show()
sys.exit(app.exec())
Comments
Post a Comment