yolov8-face 带五个关键点的推理代码

学习 使用 GitHub - derronqi/yolov8-face: yolov8 face detection with landmark的推理代码

import cv2
import numpy as np
import math
import argparse
import time


class YOLOv8_face:
    def __init__(self, path, conf_thres=0.25, iou_thres=0.45):
        self.conf_threshold = conf_thres
        self.iou_threshold = iou_thres
        self.class_names = ['face']
        self.num_classes = len(self.class_names)
        # Initialize model
        # self.net = cv2.dnn.readNet(path)
        self.net = cv2.dnn.readNetFromONNX(path)
        self.input_height = 640
        self.input_width = 640

        self.strides = (8, 16, 32)
        self.feats_hw = [(math.ceil(self.input_height / self.strides[i]), math.ceil(self.input_width / self.strides[i]))
                         for i in range(len(self.strides))]

    def make_anchors(self, feats_hw, grid_cell_offset=0.5):
        """Generate anchors from features."""
        anchor_points = {}
        for i, stride in enumerate(self.strides):
            h, w = feats_hw[i]
            x = np.arange(0, w) + grid_cell_offset  # shift x
            y = np.arange(0, h) + grid_cell_offset  # shift y
            sx, sy = np.meshgrid(x, y)
            # sy, sx = np.meshgrid(y, x)
            anchor_points[stride] = np.stack((sx, sy), axis=-1).reshape(-1, 2)
        return anchor_points

    def softmax(self, x, axis=1):
        x_exp = np.exp(x)
        # 如果是列向量,则axis=0
        x_sum = np.sum(x_exp, axis=axis, keepdims=True)
        s = x_exp / x_sum
        return s

    def resize_image(self, srcimg, keep_ratio=True):
        top, left, newh, neww = 0, 0, self.input_width, self.input_height
        if keep_ratio and srcimg.shape[0] != srcimg.shape[1]:
            hw_scale = srcimg.shape[0] / srcimg.shape[1]
            if hw_scale > 1:
                newh, neww = self.input_height, int(self.input_width / hw_scale)
                img = cv2.resize(srcimg, (neww, newh), interpolation=cv2.INTER_AREA)
                left = int((self.input_width - neww) * 0.5)
                img = cv2.copyMakeBorder(img, 0, 0, left, self.input_width - neww - left, cv2.BORDER_CONSTANT,
                                         value=(0, 0, 0))  # add border
            else:
                newh, neww = int(self.input_height * hw_scale), self.input_width
                img = cv2.resize(srcimg, (neww, newh), interpolation=cv2.INTER_AREA)
                top = int((self.input_height - newh) * 0.5)
                img = cv2.copyMakeBorder(img, top, self.input_height - newh - top, 0, 0, cv2.BORDER_CONSTANT,
                                         value=(0, 0, 0))
        else:
            img = cv2.resize(srcimg, (self.input_width, self.input_height), interpolation=cv2.INTER_AREA)
        return img, newh, neww, top, left

    def detect(self, srcimg):
        [height, width, _] = srcimg.shape
        length = max((height, width))
        image = np.zeros((length, length, 3), np.uint8)
        image[0:height, 0:width] = srcimg
        scale = length / 640

        blob = cv2.dnn.blobFromImage(image, scalefactor=1 / 255, size=(640, 640), swapRB=True)
        self.net.setInput(blob)
        preds = self.net.forward()
        # if isinstance(preds, tuple):
        #     preds = list(preds)
        # if float(cv2.__version__[:3])>=4.7:
        #     preds = [preds[2], preds[0], preds[1]] ###opencv4.7需要这一步,opencv4.5不需要
        # Perform inference on the image
        det_bboxes, det_conf, landmarks = self.post_process(preds, scale)
        return det_bboxes, det_conf, landmarks

    def post_process_1(self, preds, scale):
        preds = preds.transpose((0, 2, 1)).squeeze()

        t_index = np.where(preds[:, 4] > 0.25)
        preds = preds[t_index, :].squeeze()

        x1 = np.expand_dims(preds[:, 0] - (0.5 * preds[:, 2]), -1)
        y1 = np.expand_dims(preds[:, 1] - (0.5 * preds[:, 3]), -1)
        w = np.expand_dims(preds[:, 2], -1)
        h = np.expand_dims(preds[:, 3], -1)
        bboxes = np.concatenate([x1, y1, w, h], axis=-1) * scale
        scores = preds[:, 4]
        landmarks = preds[:, -15:] * scale
        indices = cv2.dnn.NMSBoxes(bboxes, scores, 0.25, 0.45, 0.5)

        if len(indices) > 0:
            bboxes = bboxes[indices]
            scores = scores[indices]
            # classIds = classIds[indices]
            landmarks = landmarks[indices]
            return bboxes, scores, landmarks
        else:
            print('nothing detect')

    def post_process(self, preds, scale):
        bboxes, scores, landmarks = [], [], []
        preds = preds.transpose((0, 2, 1))

        rows = preds.shape[1]
        for i in range(rows):
            score = preds[0][i][4]
            kpt = preds[0][i][-15:]
            if score >= 0.25:
                # xywh
                box = [
                    preds[0][i][0] - (0.5 * preds[0][i][2]), preds[0][i][1] - (0.5 * preds[0][i][3]),
                    preds[0][i][2], preds[0][i][3]]
                bboxes.append(box)
                scores.append(score)
                landmarks.append(kpt)

        bboxes = np.array(bboxes) * scale
        scores = np.array(scores)
        landmarks = np.array(landmarks) * scale
        indices = cv2.dnn.NMSBoxes(bboxes, scores, 0.25, 0.45, 0.5)

        if len(indices) > 0:
            bboxes = bboxes[indices]
            scores = scores[indices]
            # classIds = classIds[indices]
            landmarks = landmarks[indices]
            return bboxes, scores, landmarks
        else:
            print('nothing detect')

    def draw_detections(self, image, boxes, scores, kpts):
        for box, score, kp in zip(boxes, scores, kpts):
            x, y, w, h = box.astype(int)
            # Draw rectangle
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), thickness=2)
            cv2.putText(image, "face:" + str(round(score, 2)), (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255),
                        thickness=2)
            for i in range(5):
                cv2.circle(image, (int(kp[i * 3]), int(kp[i * 3 + 1])), 1, (0, 255, 0), thickness=-1)
                # cv2.putText(image, str(i), (int(kp[i * 3]), int(kp[i * 3 + 1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), thickness=1)
        return image


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--imgpath', type=str, default='images/jihui.png', help="image path")  # big_face.png
    parser.add_argument('--modelpath', type=str, default='weights/yolov8n-face.onnx',
                        help="onnx filepath")
    parser.add_argument('--confThreshold', default=0.45, type=float, help='class confidence')
    parser.add_argument('--nmsThreshold', default=0.5, type=float, help='nms iou thresh')
    args = parser.parse_args()

    # Initialize YOLOv8_face object detector
    YOLOv8_face_detector = YOLOv8_face(args.modelpath, conf_thres=args.confThreshold, iou_thres=args.nmsThreshold)
    srcimg: np.ndarray = cv2.imread(args.imgpath)

    # Detect Objects
    boxes, scores, kpts = YOLOv8_face_detector.detect(srcimg)

    # Draw detections
    dstimg = YOLOv8_face_detector.draw_detections(srcimg, boxes, scores, kpts)
    cv2.imwrite('result.jpg', dstimg)

### 回答1: YOLOv7-Face是一种基于YOLOv7算法的人脸检测模型。YOLOv7是YOLO系列中一种流行的目标检测算法,它采用了单阶段的检测方法,并以其高精度和高效率而受到广泛关注。YOLOv7-Face则是基于YOLOv7算法的人脸检测模型的具体实现。 相比于其他人脸检测算法,YOLOv7-Face具有以下几个特点。首先,它能够实现实时的人脸检测,即使在大规模的视频流中也能够保持较高的检测速度。其次,YOLOv7-Face具有较高的准确性,能够准确地检测出各种人脸表情和姿势,并且对于遮挡和光照变化等情况也具备一定的鲁棒性。另外,YOLOv7-Face还具有较强的可扩展性,可以适应不同尺寸和比例的人脸检测任务。 YOLOv7-Face的实现过程主要包括两个部分:模型训练和推理过程。在模型训练阶段,通过使用大量标注好的人脸图像数据,利用深度学习技术对YOLOv7-Face进行训练,使其能够准确地预测和识别人脸。在推理过程中,将输入的图像经过预处理后输入到YOLOv7-Face模型中,模型会输出所有检测到的人脸框和对应的置信度,从而完成人脸检测任务。 总的来说,YOLOv7-Face是一种高效、准确且可扩展的人脸检测模型,它在人脸识别、人脸表情分析、人脸活体检测等领域具有广泛的应用前景。 ### 回答2: YOLOv7-face是一种基于YOLOv7的人脸识别模型。YOLO(You Only Look Once)是一种实时目标检测算法,能够在一次前向传递中同时进行目标检测和定位。YOLOv7是YOLO系列的最新版本,相比前几个版本,它在检测精度和速度上都有了显著的提升。 YOLOv7-face专注于人脸识别任务。在该模型中,首先通过预训练的卷积神经网络提取图像的特征。然后,这些特征经过一系列的卷积和全连接层,最终得到人脸的位置和类别信息。与传统的人脸识别方法相比,YOLOv7-face具有更高的速度和更准确的检测结果。 YOLOv7-face的应用场景广泛,包括人脸识别门禁系统、人脸支付、人脸表情分析等。通过该模型,可以快速准确地检测和识别人脸,提高安全性和便利性。此外,YOLOv7-face还可以用于人脸数据的采集和处理,为人工智能的发展提供了重要的基础。 总之,YOLOv7-face是一种基于YOLOv7的人脸识别模型,通过先进的算法和网络结构,能够实现快速准确地人脸检测和识别。它在实际应用中具有很大的潜力,可以改善人脸识别的效率和精度,推动相关领域的发展。 ### 回答3: YOLOv7-Face 是一种用于人脸检测和人脸识别的算法模型。它是基于YOLO(You Only Look Once)系列算法的最新版本。YOLO是一种实时目标检测算法,其通过将目标检测任务转化为对均匀网格内的多个候选框进行分类和回归的问题来实现非常快速的目标检测。 YOLOv7-FaceYOLOv4-ACF(Anchor Call Frames)和YOLOv5-Face 的基础上进行了进一步改进和优化。相对于之前的版本,YOLOv7-Face 对人脸检测和识别任务更加有效和精确。 YOLOv7-Face 在训练阶段使用大量的人脸图像数据进行模型的训练,并将人脸检测和人脸识别任务合并在同一个模型中。通过深度神经网络的训练和优化,YOLOv7-Face 可以准确地检测和识别出输入图像中的人脸。 与传统的人脸检测和识别算法相比,YOLOv7-Face 的主要优点是速度快、精度高和实时性强。它可以在较短的时间内准确地检测和识别出大量的人脸,并且能够适用于各种不同的场景和应用需求。 总之,YOLOv7-Face 是一种强大的人脸检测和人脸识别算法模型,它结合了YOLO系列算法的快速性和准确性,可以高效地应用于各种人脸相关的实时应用领域。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值