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

本文介绍了如何在GitHub上使用`derronqi/yolov8-face`库进行人脸检测和关键点定位,包括初始化模型、图像预处理、YOLOv8算法实现以及结果绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习 使用 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)

<think>好的,我现在需要帮助用户解决如何下载YOLOv8s-pose模型文件的问题。首先,我需要回忆一下用户提供的引用内容,看看是否有相关的信息。在引用[2]中提到了加载模型的方式是使用YOLO(r'G:\Yolov8\yolov8-pose-pt\best.pt'),这说明用户可能已经知道如何通过代码加载模型,但不确定如何下载预训练模型。 接下来,引用[1]提到利用tensorRT_Pro-YOLOv8这个仓库进行推理,可能需要从源码下载,但用户的问题是关于模型文件的下载,所以可能需要更直接的途径。引用[3]和[4]讨论了YOLOv8-pose的预训练模型和不同尺寸的性能,但没有直接说明下载方法。 通常,Ultralytics的YOLO模型可以通过他们的官方库或者Hugging Face等平台获取。用户可能需要在官方文档中找到模型下载的链接。比如,使用命令行工具或者Python代码中的YOLO类来下载预训练模型。例如,YOLO('yolov8s-pose.pt')会自动下载模型,但用户可能需要访问权限或者正确的模型名称。 另外,用户可能需要确认模型的确切名称,比如是否有s(small)版本的pose模型。根据引用[3],存在yolov8m-pose.pt,但用户询问的是s版。需要检查Ultralytics的官方发布是否有对应的s版pose模型。假设存在的话,下载方式应该类似。 可能的步骤包括:通过官方GitHub仓库的说明,使用命令行或代码自动下载,或者手动从Hugging Face等平台下载。同时,用户可能需要安装ultralytics库,并确保网络连接正常,因为自动下载需要访问外部服务器。 还需要注意用户提到的不同输入尺寸和性能,但下载步骤可能不涉及这些,除非用户需要特定版本的模型。此外,引用[4]中的测试数据链接可能提供代码,但用户的问题主要是下载模型,因此重点应放在获取模型文件的方法上。 总结下来,正确的下载方法应该是通过Ultralytics提供的接口,或者直接访问他们的模型仓库手动下载。需要指导用户使用正确的模型名称和下载途径,确保他们能够获取到所需的yolov8s-pose.pt文件。</think>### 如何下载 YOLOv8s-pose 模型文件? YOLOv8s-pose 是 Ultralytics 官方发布的关键点检测模型,支持人体姿态估计任务。以下是两种常用的下载方式: --- #### **方法一:通过 `ultralytics` 库自动下载(推荐)** 1. **安装 `ultralytics` 库** 确保已安装最新版本的 `ultralytics`: ```bash pip install ultralytics --upgrade ``` 2. **通过代码自动下载** 在 Python 脚本中加载模型时,库会自动下载预训练权重文件(若本地不存在): ```python from ultralytics import YOLO model = YOLO('yolov8s-pose.pt') # 首次运行时会自动下载模型文件 ``` - 下载路径默认保存在用户目录的 `~/.cache/ultralytics` 中[^1] - 若需指定保存路径,可添加参数:`model = YOLO('yolov8s-pose.pt', download_dir='your/custom/path')` --- #### **方法二:手动下载** 1. **访问官方模型仓库** Ultralytics 官方模型通常托管在以下平台: - **GitHub Releases**: [https://github.com/ultralytics/ultralytics/releases](https://github.com/ultralytics/ultralytics/releases) - **Hugging Face Hub**: [https://huggingface.co/ultralytics](https://huggingface.co/ultralytics) 2. **搜索模型文件** 在仓库中查找 `yolov8s-pose.pt` 或类似命名的文件,直接下载即可。 --- #### **验证模型下载** 下载完成后,可通过以下代码验证模型是否可用: ```python from ultralytics import YOLO model = YOLO('yolov8s-pose.pt') # 加载本地模型文件 results = model.predict('example.jpg') # 测试推理 ``` --- ### 注意事项 1. **网络环境** 自动下载需确保网络能访问 `github.com` 或 `huggingface.co`,若受限可尝试手动下载后指定路径加载[^2]。 2. **模型性能** YOLOv8s-pose 的输入尺寸影响推理速度和精度,默认支持 $640 \times 640$ 分辨率,调整输入尺寸需同步修改代码中的预处理参数[^3][^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值