pyqt5结合python实现人脸检测
时间: 2024-06-21 19:01:10 浏览: 104
要使用PyQt5结合Python实现人脸检测,你需要先安装`opencv-python`和`PyQt5`库。可以使用以下命令进行安装:
```bash
pip install opencv-python
pip install PyQt5
```
接下来,你可以使用以下代码实现一个简单的人脸检测程序:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QFileDialog
from PyQt5.QtGui import QPixmap
import cv2
class FaceDetectionApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('人脸检测')
self.label = QLabel(self)
layout = QVBoxLayout()
layout.addWidget(self.label)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
self.statusBar().showMessage('请选择一张图片进行人脸检测')
self.setGeometry(300, 300, 800, 600)
self.show()
def detect_faces(self, image_path):
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
return img
def open_image(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "选择图片", "", "Images (*.png *.xpm *.jpg *.bmp);;All Files (*)", options=options)
if file_name:
detected_image = self.detect_faces(file_name)
height, width, channel = detected_image.shape
bytes_per_line = 3 * width
q_img = QPixmap.fromImage(QImage(detected_image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped())
self.label.setPixmap(q_img)
self.label.setAlignment(Qt.AlignCenter)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = FaceDetectionApp()
ex.show()
sys.exit(app.exec_())
```
这个程序会创建一个简单的窗口,你可以通过点击窗口中的按钮来选择一张图片进行人脸检测。检测到的人脸会被用矩形框标出。
阅读全文