Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import cv2
- import mediapipe as mp
- import numpy as np
- from PyQt5 import QtGui, uic
- from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QThread
- from PyQt5.QtGui import QPixmap
- from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QPushButton, QDialog
- find_faces = False
- class VideoThread(QThread):
- change_pixmap_signal = pyqtSignal(np.ndarray)
- def run(self):
- global find_faces
- mp_face_detection = mp.solutions.face_detection
- mp_drawing = mp.solutions.drawing_utils
- # capture from web cam
- cap = cv2.VideoCapture(0)
- with mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5) as face_detection:
- while cap.isOpened():
- success, image = cap.read()
- if not success:
- print("Ignoring empty camera frame.")
- # If loading a video, use 'break' instead of 'continue'.
- continue
- if find_faces:
- # To improve performance, optionally mark the image as not writeable to
- # pass by reference.
- image.flags.writeable = False
- image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
- results = face_detection.process(image)
- # Draw the face detection annotations on the image.
- image.flags.writeable = True
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
- if results.detections:
- for detection in results.detections:
- mp_drawing.draw_detection(image, detection)
- image = cv2.flip(image, 1)
- self.change_pixmap_signal.emit(image)
- form_class = uic.loadUiType("face_detection.ui")[0]
- class App(QDialog, form_class):
- def __init__(self):
- super().__init__()
- self.setupUi(self)
- self.find_button.clicked.connect(self.find_button_clicked)
- # create the video capture thread
- self.thread = VideoThread()
- # connect its signal to the update_image slot
- self.thread.change_pixmap_signal.connect(self.update_image)
- # start the thread
- self.thread.start()
- @pyqtSlot(np.ndarray)
- def update_image(self, cv_img):
- """Updates the image_label with a new opencv image"""
- qt_img = self.convert_cv_qt(cv_img)
- self.image_label.setPixmap(qt_img)
- def convert_cv_qt(self, cv_img):
- """Convert from an opencv image to QPixmap"""
- rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
- h, w, ch = rgb_image.shape
- bytes_per_line = ch * w
- convert_to_Qt_format = QtGui.QImage(rgb_image.data, w, h, bytes_per_line, QtGui.QImage.Format_RGB888)
- p = convert_to_Qt_format.scaled(800, 600, Qt.KeepAspectRatio)
- return QPixmap.fromImage(p)
- def find_button_clicked(self):
- global find_faces
- find_faces = not find_faces
- if __name__ == "__main__":
- app = QApplication(sys.argv)
- a = App()
- a.show()
- sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement