欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Python實(shí)現(xiàn)簡(jiǎn)單的人臉識(shí)別系統(tǒng)

 更新時(shí)間:2024年04月08日 11:51:50   作者:肆十二  
這篇文章主要介紹了如何通過(guò)Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的人臉識(shí)別系統(tǒng),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的可以跟隨小編一起試一試

前言

最近又多了不少朋友關(guān)注,先在這里謝謝大家。關(guān)注我的朋友大多數(shù)都是大學(xué)生,而且我簡(jiǎn)單看了一下,低年級(jí)的大學(xué)生居多,大多數(shù)都是為了完成課程設(shè)計(jì),作為一個(gè)過(guò)來(lái)人,還是希望大家平時(shí)能多抽出點(diǎn)時(shí)間學(xué)習(xí)一下,這種臨時(shí)抱佛腳的策略要少用嗷。今天我們來(lái)python實(shí)現(xiàn)一個(gè)人臉識(shí)別系統(tǒng),主要是借助了dlib這個(gè)庫(kù),相當(dāng)于我們直接調(diào)用現(xiàn)成的庫(kù)來(lái)進(jìn)行人臉識(shí)別,就省去了之前教程中的數(shù)據(jù)收集和模型訓(xùn)練的步驟了。

B站視頻:用300行代碼實(shí)現(xiàn)人臉識(shí)別系統(tǒng)_嗶哩嗶哩_bilibili

碼云地址:face_dlib_py37_42: 用300行代碼開發(fā)一個(gè)人臉識(shí)別系統(tǒng)-42 (gitee.com)

基本原理

人臉識(shí)別和目標(biāo)檢測(cè)這些還不太一樣,比如大家傳統(tǒng)的訓(xùn)練一個(gè)目標(biāo)檢測(cè)模型,你只有對(duì)這個(gè)目標(biāo)訓(xùn)練了之后,你的模型才能找到這樣的目標(biāo),比如你的目標(biāo)檢測(cè)模型如果是檢測(cè)植物的,那顯然就不能檢測(cè)動(dòng)物。但是人臉識(shí)別就不一樣,以你的手機(jī)為例,你發(fā)現(xiàn)你只錄入了一次你的人臉信息,不需要訓(xùn)練,他就能準(zhǔn)確的識(shí)別你,這里識(shí)別的原理是通過(guò)人臉識(shí)別的模型提取你臉部的特征向量,然后將實(shí)時(shí)檢測(cè)到的你的人臉同數(shù)據(jù)庫(kù)中保存的人臉進(jìn)行比對(duì),如果相似度超過(guò)一定的閾值之后,就認(rèn)為比對(duì)成功。不過(guò)我這里說(shuō)的只是簡(jiǎn)化版本的人臉識(shí)別,現(xiàn)在手機(jī)和門禁這些要復(fù)雜和安全的多,也不是簡(jiǎn)單平面上的人臉識(shí)別。

總結(jié)下來(lái)可以分為下面的步驟:

1.上傳人臉到數(shù)據(jù)庫(kù)

2.人臉檢測(cè)

3.數(shù)據(jù)庫(kù)比對(duì)并返回結(jié)果

這里我做了一個(gè)簡(jiǎn)答的示意圖,可以幫助大家簡(jiǎn)單理解一下。

代碼實(shí)現(xiàn)

廢話不多說(shuō),這里就是我們的代碼實(shí)現(xiàn),代碼我已經(jīng)上傳到碼云,大家直接下載就行,地址就在博客開頭。

不會(huì)安裝python環(huán)境的兄弟請(qǐng)看這里:如何在pycharm中配置anaconda的虛擬環(huán)境

創(chuàng)建虛擬環(huán)境

創(chuàng)建虛擬環(huán)境前請(qǐng)大家先下載博客開頭的碼云源碼到本地。

本次我們需要使用到python3.7的虛擬環(huán)境,命令如下:

conda create -n face python==3.7.3
conda activate face

安裝必要的庫(kù)

pip install -r requirements.txt

愉快地開始你的人臉識(shí)別吧!

執(zhí)行下面的主文件即可

python UI.py

或者在pycharm中按照下面的方式直接運(yùn)行即可

首先將你需要識(shí)別的人臉上傳到數(shù)據(jù)庫(kù)中

通過(guò)第二個(gè)視頻檢測(cè)功能識(shí)別實(shí)時(shí)的人臉

詳細(xì)的代碼如下:

# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: yolov5-jungong
File Name: window.py.py
Author: chenming
Create Date: 2021/11/8
Description:圖形化界面,可以檢測(cè)攝像頭、視頻和圖片文件
-------------------------------------------------
"""
# 應(yīng)該在界面啟動(dòng)的時(shí)候就將模型加載出來(lái),設(shè)置tmp的目錄來(lái)放中間的處理結(jié)果
import shutil
import PyQt5.QtCore
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import threading
import argparse
import os
import sys
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
import os.path as osp
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr,
                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync


# 添加一個(gè)關(guān)于界面
# 窗口主類
class MainWindow(QTabWidget):
    # 基本配置不動(dòng),然后只動(dòng)第三個(gè)界面
    def __init__(self):
        # 初始化界面
        super().__init__()
        self.setWindowTitle('Target detection system')
        self.resize(1200, 800)
        self.setWindowIcon(QIcon("images/UI/lufei.png"))
        # 圖片讀取進(jìn)程
        self.output_size = 480
        self.img2predict = ""
        self.device = 'cpu'
        # # 初始化視頻讀取線程
        self.vid_source = '0'  # 初始設(shè)置為攝像頭
        self.stopEvent = threading.Event()
        self.webcam = True
        self.stopEvent.clear()
        self.model = self.model_load(weights="runs/train/exp_yolov5s/weights/best.pt",
                                     device="cpu")  # todo 指明模型加載的位置的設(shè)備
        self.initUI()
        self.reset_vid()

    '''
    ***模型初始化***
    '''
    @torch.no_grad()
    def model_load(self, weights="",  # model.pt path(s)
                   device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
                   half=False,  # use FP16 half-precision inference
                   dnn=False,  # use OpenCV DNN for ONNX inference
                   ):
        device = select_device(device)
        half &= device.type != 'cpu'  # half precision only supported on CUDA
        device = select_device(device)
        model = DetectMultiBackend(weights, device=device, dnn=dnn)
        stride, names, pt, jit, onnx = model.stride, model.names, model.pt, model.jit, model.onnx
        # Half
        half &= pt and device.type != 'cpu'  # half precision only supported by PyTorch on CUDA
        if pt:
            model.model.half() if half else model.model.float()
        print("模型加載完成!")
        return model

    '''
    ***界面初始化***
    '''
    def initUI(self):
        # 圖片檢測(cè)子界面
        font_title = QFont('楷體', 16)
        font_main = QFont('楷體', 14)
        # 圖片識(shí)別界面, 兩個(gè)按鈕,上傳圖片和顯示結(jié)果
        img_detection_widget = QWidget()
        img_detection_layout = QVBoxLayout()
        img_detection_title = QLabel("圖片識(shí)別功能")
        img_detection_title.setFont(font_title)
        mid_img_widget = QWidget()
        mid_img_layout = QHBoxLayout()
        self.left_img = QLabel()
        self.right_img = QLabel()
        self.left_img.setPixmap(QPixmap("images/UI/up.jpeg"))
        self.right_img.setPixmap(QPixmap("images/UI/right.jpeg"))
        self.left_img.setAlignment(Qt.AlignCenter)
        self.right_img.setAlignment(Qt.AlignCenter)
        mid_img_layout.addWidget(self.left_img)
        mid_img_layout.addStretch(0)
        mid_img_layout.addWidget(self.right_img)
        mid_img_widget.setLayout(mid_img_layout)
        up_img_button = QPushButton("上傳圖片")
        det_img_button = QPushButton("開始檢測(cè)")
        up_img_button.clicked.connect(self.upload_img)
        det_img_button.clicked.connect(self.detect_img)
        up_img_button.setFont(font_main)
        det_img_button.setFont(font_main)
        up_img_button.setStyleSheet("QPushButton{color:white}"
                                    "QPushButton:hover{background-color: rgb(2,110,180);}"
                                    "QPushButton{background-color:rgb(48,124,208)}"
                                    "QPushButton{border:2px}"
                                    "QPushButton{border-radius:5px}"
                                    "QPushButton{padding:5px 5px}"
                                    "QPushButton{margin:5px 5px}")
        det_img_button.setStyleSheet("QPushButton{color:white}"
                                     "QPushButton:hover{background-color: rgb(2,110,180);}"
                                     "QPushButton{background-color:rgb(48,124,208)}"
                                     "QPushButton{border:2px}"
                                     "QPushButton{border-radius:5px}"
                                     "QPushButton{padding:5px 5px}"
                                     "QPushButton{margin:5px 5px}")
        img_detection_layout.addWidget(img_detection_title, alignment=Qt.AlignCenter)
        img_detection_layout.addWidget(mid_img_widget, alignment=Qt.AlignCenter)
        img_detection_layout.addWidget(up_img_button)
        img_detection_layout.addWidget(det_img_button)
        img_detection_widget.setLayout(img_detection_layout)

        # todo 視頻識(shí)別界面
        # 視頻識(shí)別界面的邏輯比較簡(jiǎn)單,基本就從上到下的邏輯
        vid_detection_widget = QWidget()
        vid_detection_layout = QVBoxLayout()
        vid_title = QLabel("視頻檢測(cè)功能")
        vid_title.setFont(font_title)
        self.vid_img = QLabel()
        self.vid_img.setPixmap(QPixmap("images/UI/up.jpeg"))
        vid_title.setAlignment(Qt.AlignCenter)
        self.vid_img.setAlignment(Qt.AlignCenter)
        self.webcam_detection_btn = QPushButton("攝像頭實(shí)時(shí)監(jiān)測(cè)")
        self.mp4_detection_btn = QPushButton("視頻文件檢測(cè)")
        self.vid_stop_btn = QPushButton("停止檢測(cè)")
        self.webcam_detection_btn.setFont(font_main)
        self.mp4_detection_btn.setFont(font_main)
        self.vid_stop_btn.setFont(font_main)
        self.webcam_detection_btn.setStyleSheet("QPushButton{color:white}"
                                                "QPushButton:hover{background-color: rgb(2,110,180);}"
                                                "QPushButton{background-color:rgb(48,124,208)}"
                                                "QPushButton{border:2px}"
                                                "QPushButton{border-radius:5px}"
                                                "QPushButton{padding:5px 5px}"
                                                "QPushButton{margin:5px 5px}")
        self.mp4_detection_btn.setStyleSheet("QPushButton{color:white}"
                                             "QPushButton:hover{background-color: rgb(2,110,180);}"
                                             "QPushButton{background-color:rgb(48,124,208)}"
                                             "QPushButton{border:2px}"
                                             "QPushButton{border-radius:5px}"
                                             "QPushButton{padding:5px 5px}"
                                             "QPushButton{margin:5px 5px}")
        self.vid_stop_btn.setStyleSheet("QPushButton{color:white}"
                                        "QPushButton:hover{background-color: rgb(2,110,180);}"
                                        "QPushButton{background-color:rgb(48,124,208)}"
                                        "QPushButton{border:2px}"
                                        "QPushButton{border-radius:5px}"
                                        "QPushButton{padding:5px 5px}"
                                        "QPushButton{margin:5px 5px}")
        self.webcam_detection_btn.clicked.connect(self.open_cam)
        self.mp4_detection_btn.clicked.connect(self.open_mp4)
        self.vid_stop_btn.clicked.connect(self.close_vid)
        # 添加組件到布局上
        vid_detection_layout.addWidget(vid_title)
        vid_detection_layout.addWidget(self.vid_img)
        vid_detection_layout.addWidget(self.webcam_detection_btn)
        vid_detection_layout.addWidget(self.mp4_detection_btn)
        vid_detection_layout.addWidget(self.vid_stop_btn)
        vid_detection_widget.setLayout(vid_detection_layout)

        # todo 關(guān)于界面
        about_widget = QWidget()
        about_layout = QVBoxLayout()
        about_title = QLabel('歡迎使用目標(biāo)檢測(cè)系統(tǒng)\n\n 提供付費(fèi)指導(dǎo):有需要的好兄弟加下面的QQ即可')  # todo 修改歡迎詞語(yǔ)
        about_title.setFont(QFont('楷體', 18))
        about_title.setAlignment(Qt.AlignCenter)
        about_img = QLabel()
        about_img.setPixmap(QPixmap('images/UI/qq.png'))
        about_img.setAlignment(Qt.AlignCenter)

        # label4.setText("<a )
        label_super = QLabel()  # todo 更換作者信息
        label_super.setText("<a )
        label_super.setFont(QFont('楷體', 16))
        label_super.setOpenExternalLinks(True)
        # label_super.setOpenExternalLinks(True)
        label_super.setAlignment(Qt.AlignRight)
        about_layout.addWidget(about_title)
        about_layout.addStretch()
        about_layout.addWidget(about_img)
        about_layout.addStretch()
        about_layout.addWidget(label_super)
        about_widget.setLayout(about_layout)

        self.left_img.setAlignment(Qt.AlignCenter)
        self.addTab(img_detection_widget, '圖片檢測(cè)')
        self.addTab(vid_detection_widget, '視頻檢測(cè)')
        self.addTab(about_widget, '聯(lián)系我')
        self.setTabIcon(0, QIcon('images/UI/lufei.png'))
        self.setTabIcon(1, QIcon('images/UI/lufei.png'))
        self.setTabIcon(2, QIcon('images/UI/lufei.png'))

    '''
    ***上傳圖片***
    '''
    def upload_img(self):
        # 選擇錄像文件進(jìn)行讀取
        fileName, fileType = QFileDialog.getOpenFileName(self, 'Choose file', '', '*.jpg *.png *.tif *.jpeg')
        if fileName:
            suffix = fileName.split(".")[-1]
            save_path = osp.join("images/tmp", "tmp_upload." + suffix)
            shutil.copy(fileName, save_path)
            # 應(yīng)該調(diào)整一下圖片的大小,然后統(tǒng)一防在一起
            im0 = cv2.imread(save_path)
            resize_scale = self.output_size / im0.shape[0]
            im0 = cv2.resize(im0, (0, 0), fx=resize_scale, fy=resize_scale)
            cv2.imwrite("images/tmp/upload_show_result.jpg", im0)
            # self.right_img.setPixmap(QPixmap("images/tmp/single_result.jpg"))
            self.img2predict = fileName
            self.left_img.setPixmap(QPixmap("images/tmp/upload_show_result.jpg"))
            # todo 上傳圖片之后右側(cè)的圖片重置,
            self.right_img.setPixmap(QPixmap("images/UI/right.jpeg"))

    '''
    ***檢測(cè)圖片***
    '''
    def detect_img(self):
        model = self.model
        output_size = self.output_size
        source = self.img2predict  # file/dir/URL/glob, 0 for webcam
        imgsz = 640  # inference size (pixels)
        conf_thres = 0.25  # confidence threshold
        iou_thres = 0.45  # NMS IOU threshold
        max_det = 1000  # maximum detections per image
        device = self.device  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img = False  # show results
        save_txt = False  # save results to *.txt
        save_conf = False  # save confidences in --save-txt labels
        save_crop = False  # save cropped prediction boxes
        nosave = False  # do not save images/videos
        classes = None  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms = False  # class-agnostic NMS
        augment = False  # ugmented inference
        visualize = False  # visualize features
        line_thickness = 3  # bounding box thickness (pixels)
        hide_labels = False  # hide labels
        hide_conf = False  # hide confidences
        half = False  # use FP16 half-precision inference
        dnn = False  # use OpenCV DNN for ONNX inference
        print(source)
        if source == "":
            QMessageBox.warning(self, "請(qǐng)上傳", "請(qǐng)先上傳圖片再進(jìn)行檢測(cè)")
        else:
            source = str(source)
            device = select_device(self.device)
            webcam = False
            stride, names, pt, jit, onnx = model.stride, model.names, model.pt, model.jit, model.onnx
            imgsz = check_img_size(imgsz, s=stride)  # check image size
            save_img = not nosave and not source.endswith('.txt')  # save inference images
            # Dataloader
            if webcam:
                view_img = check_imshow()
                cudnn.benchmark = True  # set True to speed up constant image size inference
                dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt and not jit)
                bs = len(dataset)  # batch_size
            else:
                dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt and not jit)
                bs = 1  # batch_size
            vid_path, vid_writer = [None] * bs, [None] * bs
            # Run inference
            if pt and device.type != 'cpu':
                model(torch.zeros(1, 3, *imgsz).to(device).type_as(next(model.model.parameters())))  # warmup
            dt, seen = [0.0, 0.0, 0.0], 0
            for path, im, im0s, vid_cap, s in dataset:
                t1 = time_sync()
                im = torch.from_numpy(im).to(device)
                im = im.half() if half else im.float()  # uint8 to fp16/32
                im /= 255  # 0 - 255 to 0.0 - 1.0
                if len(im.shape) == 3:
                    im = im[None]  # expand for batch dim
                t2 = time_sync()
                dt[0] += t2 - t1
                # Inference
                # visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
                pred = model(im, augment=augment, visualize=visualize)
                t3 = time_sync()
                dt[1] += t3 - t2
                # NMS
                pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
                dt[2] += time_sync() - t3
                # Second-stage classifier (optional)
                # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
                # Process predictions
                for i, det in enumerate(pred):  # per image
                    seen += 1
                    if webcam:  # batch_size >= 1
                        p, im0, frame = path[i], im0s[i].copy(), dataset.count
                        s += f'{i}: '
                    else:
                        p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
                    p = Path(p)  # to Path
                    s += '%gx%g ' % im.shape[2:]  # print string
                    gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
                    imc = im0.copy() if save_crop else im0  # for save_crop
                    annotator = Annotator(im0, line_width=line_thickness, example=str(names))
                    if len(det):
                        # Rescale boxes from img_size to im0 size
                        det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()

                        # Print results
                        for c in det[:, -1].unique():
                            n = (det[:, -1] == c).sum()  # detections per class
                            s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                        # Write results
                        for *xyxy, conf, cls in reversed(det):
                            if save_txt:  # Write to file
                                xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(
                                    -1).tolist()  # normalized xywh
                                line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
                                # with open(txt_path + '.txt', 'a') as f:
                                #     f.write(('%g ' * len(line)).rstrip() % line + '\n')

                            if save_img or save_crop or view_img:  # Add bbox to image
                                c = int(cls)  # integer class
                                label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                                annotator.box_label(xyxy, label, color=colors(c, True))
                                # if save_crop:
                                #     save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg',
                                #                  BGR=True)
                    # Print time (inference-only)
                    LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
                    # Stream results
                    im0 = annotator.result()
                    # if view_img:
                    #     cv2.imshow(str(p), im0)
                    #     cv2.waitKey(1)  # 1 millisecond
                    # Save results (image with detections)
                    resize_scale = output_size / im0.shape[0]
                    im0 = cv2.resize(im0, (0, 0), fx=resize_scale, fy=resize_scale)
                    cv2.imwrite("images/tmp/single_result.jpg", im0)
                    # 目前的情況來(lái)看,應(yīng)該只是ubuntu下會(huì)出問(wèn)題,但是在windows下是完整的,所以繼續(xù)
                    self.right_img.setPixmap(QPixmap("images/tmp/single_result.jpg"))

    # 視頻檢測(cè),邏輯基本一致,有兩個(gè)功能,分別是檢測(cè)攝像頭的功能和檢測(cè)視頻文件的功能,先做檢測(cè)攝像頭的功能。

    '''
    ### 界面關(guān)閉事件 ### 
    '''
    def closeEvent(self, event):
        reply = QMessageBox.question(self,
                                     'quit',
                                     "Are you sure?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.close()
            event.accept()
        else:
            event.ignore()

    '''
    ### 視頻關(guān)閉事件 ### 
    '''

    def open_cam(self):
        self.webcam_detection_btn.setEnabled(False)
        self.mp4_detection_btn.setEnabled(False)
        self.vid_stop_btn.setEnabled(True)
        self.vid_source = '0'
        self.webcam = True
        th = threading.Thread(target=self.detect_vid)
        th.start()

    '''
    ### 開啟視頻文件檢測(cè)事件 ### 
    '''

    def open_mp4(self):
        fileName, fileType = QFileDialog.getOpenFileName(self, 'Choose file', '', '*.mp4 *.avi')
        if fileName:
            self.webcam_detection_btn.setEnabled(False)
            self.mp4_detection_btn.setEnabled(False)
            # self.vid_stop_btn.setEnabled(True)
            self.vid_source = fileName
            self.webcam = False
            th = threading.Thread(target=self.detect_vid)
            th.start()

    '''
    ### 視頻開啟事件 ### 
    '''

    # 視頻和攝像頭的主函數(shù)是一樣的,不過(guò)是傳入的source不同罷了
    def detect_vid(self):
        # pass
        model = self.model
        output_size = self.output_size
        # source = self.img2predict  # file/dir/URL/glob, 0 for webcam
        imgsz = 640  # inference size (pixels)
        conf_thres = 0.25  # confidence threshold
        iou_thres = 0.45  # NMS IOU threshold
        max_det = 1000  # maximum detections per image
        # device = self.device  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img = False  # show results
        save_txt = False  # save results to *.txt
        save_conf = False  # save confidences in --save-txt labels
        save_crop = False  # save cropped prediction boxes
        nosave = False  # do not save images/videos
        classes = None  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms = False  # class-agnostic NMS
        augment = False  # ugmented inference
        visualize = False  # visualize features
        line_thickness = 3  # bounding box thickness (pixels)
        hide_labels = False  # hide labels
        hide_conf = False  # hide confidences
        half = False  # use FP16 half-precision inference
        dnn = False  # use OpenCV DNN for ONNX inference
        source = str(self.vid_source)
        webcam = self.webcam
        device = select_device(self.device)
        stride, names, pt, jit, onnx = model.stride, model.names, model.pt, model.jit, model.onnx
        imgsz = check_img_size(imgsz, s=stride)  # check image size
        save_img = not nosave and not source.endswith('.txt')  # save inference images
        # Dataloader
        if webcam:
            view_img = check_imshow()
            cudnn.benchmark = True  # set True to speed up constant image size inference
            dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt and not jit)
            bs = len(dataset)  # batch_size
        else:
            dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt and not jit)
            bs = 1  # batch_size
        vid_path, vid_writer = [None] * bs, [None] * bs
        # Run inference
        if pt and device.type != 'cpu':
            model(torch.zeros(1, 3, *imgsz).to(device).type_as(next(model.model.parameters())))  # warmup
        dt, seen = [0.0, 0.0, 0.0], 0
        for path, im, im0s, vid_cap, s in dataset:
            t1 = time_sync()
            im = torch.from_numpy(im).to(device)
            im = im.half() if half else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0
            if len(im.shape) == 3:
                im = im[None]  # expand for batch dim
            t2 = time_sync()
            dt[0] += t2 - t1
            # Inference
            # visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(im, augment=augment, visualize=visualize)
            t3 = time_sync()
            dt[1] += t3 - t2
            # NMS
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
            dt[2] += time_sync() - t3
            # Second-stage classifier (optional)
            # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
            # Process predictions
            for i, det in enumerate(pred):  # per image
                seen += 1
                if webcam:  # batch_size >= 1
                    p, im0, frame = path[i], im0s[i].copy(), dataset.count
                    s += f'{i}: '
                else:
                    p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
                p = Path(p)  # to Path
                # save_path = str(save_dir / p.name)  # im.jpg
                # txt_path = str(save_dir / 'labels' / p.stem) + (
                #     '' if dataset.mode == 'image' else f'_{frame}')  # im.txt
                s += '%gx%g ' % im.shape[2:]  # print string
                gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
                imc = im0.copy() if save_crop else im0  # for save_crop
                annotator = Annotator(im0, line_width=line_thickness, example=str(names))
                if len(det):
                    # Rescale boxes from img_size to im0 size
                    det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()

                    # Print results
                    for c in det[:, -1].unique():
                        n = (det[:, -1] == c).sum()  # detections per class
                        s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                    # Write results
                    for *xyxy, conf, cls in reversed(det):
                        if save_txt:  # Write to file
                            xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(
                                -1).tolist()  # normalized xywh
                            line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
                            # with open(txt_path + '.txt', 'a') as f:
                            #     f.write(('%g ' * len(line)).rstrip() % line + '\n')

                        if save_img or save_crop or view_img:  # Add bbox to image
                            c = int(cls)  # integer class
                            label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                            annotator.box_label(xyxy, label, color=colors(c, True))
                            # if save_crop:
                            #     save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg',
                            #                  BGR=True)
                # Print time (inference-only)
                LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
                # Stream results
                # Save results (image with detections)
                im0 = annotator.result()
                frame = im0
                resize_scale = output_size / frame.shape[0]
                frame_resized = cv2.resize(frame, (0, 0), fx=resize_scale, fy=resize_scale)
                cv2.imwrite("images/tmp/single_result_vid.jpg", frame_resized)
                self.vid_img.setPixmap(QPixmap("images/tmp/single_result_vid.jpg"))
                # self.vid_img
                # if view_img:
                # cv2.imshow(str(p), im0)
                # self.vid_img.setPixmap(QPixmap("images/tmp/single_result_vid.jpg"))
                # cv2.waitKey(1)  # 1 millisecond
            if cv2.waitKey(25) & self.stopEvent.is_set() == True:
                self.stopEvent.clear()
                self.webcam_detection_btn.setEnabled(True)
                self.mp4_detection_btn.setEnabled(True)
                self.reset_vid()
                break
        # self.reset_vid()

    '''
    ### 界面重置事件 ### 
    '''

    def reset_vid(self):
        self.webcam_detection_btn.setEnabled(True)
        self.mp4_detection_btn.setEnabled(True)
        self.vid_img.setPixmap(QPixmap("images/UI/up.jpeg"))
        self.vid_source = '0'
        self.webcam = True

    '''
    ### 視頻重置事件 ### 
    '''

    def close_vid(self):
        self.stopEvent.set()
        self.reset_vid()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

以上就是基于Python實(shí)現(xiàn)簡(jiǎn)單的人臉識(shí)別系統(tǒng)的詳細(xì)內(nèi)容,更多關(guān)于Python人臉識(shí)別系統(tǒng)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python ljust rjust center輸出

    Python ljust rjust center輸出

    Python中打印字符串時(shí)可以調(diào)用ljust(左對(duì)齊),rjust(右對(duì)齊),center(中間對(duì)齊)來(lái)輸出整齊美觀的字符串,使用起來(lái)非常簡(jiǎn)單,包括使用第二個(gè)參數(shù)填充(默認(rèn)為空格)。
    2008-09-09
  • Python利用pandas計(jì)算多個(gè)CSV文件數(shù)據(jù)值的實(shí)例

    Python利用pandas計(jì)算多個(gè)CSV文件數(shù)據(jù)值的實(shí)例

    下面小編就為大家分享一篇Python利用pandas計(jì)算多個(gè)CSV文件數(shù)據(jù)值的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • 在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式

    在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式

    今天小編就為大家分享一篇在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02
  • flask框架url與重定向操作實(shí)例詳解

    flask框架url與重定向操作實(shí)例詳解

    這篇文章主要介紹了flask框架url與重定向操作,結(jié)合實(shí)例形式詳細(xì)分析了flask框架URL映射、傳參、重定向等相關(guān)概念、原理與操作注意事項(xiàng),需要的朋友可以參考下
    2020-01-01
  • Python字符串切片操作知識(shí)詳解

    Python字符串切片操作知識(shí)詳解

    這篇文章主要介紹了Python中字符串切片操作 的相關(guān)資料,需要的朋友可以參考下
    2016-03-03
  • python數(shù)據(jù)可視化自制職位分析生成崗位分析數(shù)據(jù)報(bào)表

    python數(shù)據(jù)可視化自制職位分析生成崗位分析數(shù)據(jù)報(bào)表

    之前網(wǎng)上也有不少關(guān)于行業(yè)的分析數(shù)據(jù),今天我們就根據(jù)不同崗位,公司類型規(guī)模,學(xué)歷要求,薪資分布等來(lái)進(jìn)行分析,把職位分析功能集合封裝起來(lái),做成一個(gè)小工具分享給大家吧
    2021-09-09
  • python tkinter實(shí)現(xiàn)界面切換的示例代碼

    python tkinter實(shí)現(xiàn)界面切換的示例代碼

    今天小編就為大家分享一篇python tkinter實(shí)現(xiàn)界面切換的示例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • python裝飾器中@property屬性的使用解析

    python裝飾器中@property屬性的使用解析

    這篇文章主要介紹了python裝飾器中@property屬性的使用解析,property屬性是一種用起來(lái)像是使用的實(shí)例屬性一樣的特殊屬性,可以對(duì)應(yīng)于某個(gè)方法,需要的朋友可以參考下
    2023-09-09
  • pyEcharts安裝及詳細(xì)使用指南(最新)

    pyEcharts安裝及詳細(xì)使用指南(最新)

    這篇文章主要介紹了pyEcharts安裝及詳細(xì)使用指南(最新),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Python基礎(chǔ)之字符串操作常用函數(shù)集合

    Python基礎(chǔ)之字符串操作常用函數(shù)集合

    這篇文章主要介紹了Python基礎(chǔ)之字符串操作常用函數(shù)集合,需要的朋友可以參考下
    2020-02-02

最新評(píng)論