- 1 year ago
OpenCV VideoCapture object for image stream from camera
The VideoCapture
object in OpenCV can be used to read image frames from a camera or video file. To read an image stream from a camera, you can use the VideoCapture
constructor and pass the camera device ID as an argument.
Here is an example code snippet that demonstrates how to use VideoCapture
to read frames from a camera and display them in a QWidget
:
pythonimport sys
import cv2
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
class CameraWidget(QWidget):
def __init__(self):
super().__init__()
self.camera_id = 0
self.cap = cv2.VideoCapture(self.camera_id)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
self.label = QLabel(self)
self.label.setGeometry(0, 0, 640, 480)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(50)
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
q_image = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(q_image)
self.label.setPixmap(pixmap)
def closeEvent(self, event):
self.cap.release()
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
camera_widget = CameraWidget()
camera_widget.show()
sys.exit(app.exec_())
In the __init__
method, we initialize the VideoCapture
object with the camera device ID, and set the width and height of the captured frames to 640x480. We then create a QLabel
widget to display the frames, and start a timer to continuously read frames from the camera.
In the update_frame
method, we read a frame from the VideoCapture
object, convert it from BGR to RGB format, and create a QImage
object from the frame data. We then create a QPixmap
object from the QImage
and set it as the label's pixmap.
Finally, in the closeEvent
method, we release the VideoCapture
object when the widget is closed.