Created
November 19, 2016 20:49
-
-
Save Hamza5/569891f678100b96083afced576b45a3 to your computer and use it in GitHub Desktop.
Simple PyQt4/OpenCV2 script which uses the Webcam
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import numpy | |
import cv2 | |
from PyQt4.QtGui import QApplication, QWidget, QLabel, QGroupBox, QVBoxLayout, QImage, QPixmap | |
from PyQt4.QtCore import QSize, QTimer | |
# GUI code | |
app = QApplication(sys.argv) | |
window = QWidget() | |
videoPreviewGroupBox = QGroupBox("Look at your face !", window) | |
videoPreviewLabel = QLabel(videoPreviewGroupBox) | |
videoPreviewLabel.setMinimumSize(QSize(600, 480)) | |
internLayout = QVBoxLayout(videoPreviewGroupBox) | |
videoPreviewGroupBox.setLayout(internLayout) | |
internLayout.addWidget(videoPreviewLabel) | |
layout = QVBoxLayout(window) | |
window.setLayout(layout) | |
layout.addWidget(videoPreviewGroupBox) | |
window.setWindowTitle('Webcam preview') | |
window.move(app.desktop().availableGeometry().center() - window.rect().center()) # Center the window | |
window.show() | |
# Webcam reading code | |
webcam = cv2.VideoCapture(0) # Webcam is the first video capture device | |
def showCapture(): | |
success, frame = webcam.read() # Get a picture from the webcam | |
if success: | |
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert (Blue,Green,Red) to (Red,Green,Blue) | |
assert isinstance(rgb_frame, numpy.ndarray) # An image is just a NumPy array | |
image = QImage(rgb_frame.tobytes(), # The content of the image | |
rgb_frame.shape[1], # The width (number of columns) | |
rgb_frame.shape[0], # The height (number of rows) | |
QImage.Format_RGB888) # The image is stored in 3*8-bit format | |
videoPreviewLabel.setPixmap(QPixmap.fromImage(image)) # Show the image | |
# Timer code | |
timer = QTimer(window) | |
timer.timeout.connect(showCapture) # When timeout is reached, call showCapture | |
timer.start(40) # Updates image every 40 milliseconds | |
sys.exit(app.exec()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment