在这个数字化时代,图像识别技术已经深入到我们的日常生活。Yolo(You Only Look Once)人体检测算法因其速度快、准确率高而备受关注。本文将带你从零开始,通过实战案例学习如何使用Yolo进行人体检测,让你轻松识别生活中的每个人。
一、Yolo简介
Yolo是一种基于深度学习的实时物体检测算法,由Joseph Redmon等人在2015年提出。与传统的物体检测算法相比,Yolo在检测速度和准确率上都有显著优势。它将检测任务分解为三个步骤:预测边界框、预测类别和预测置信度。
二、环境搭建
2.1 安装Python环境
首先,确保你的计算机上已经安装了Python环境。你可以通过以下命令检查Python版本:
python --version
如果Python没有安装,你可以从Python官方网站下载并安装。
2.2 安装深度学习框架
接下来,安装深度学习框架,如TensorFlow或PyTorch。这里我们以TensorFlow为例:
pip install tensorflow
2.3 安装其他依赖库
pip install opencv-python
pip install numpy
三、数据集准备
Yolo人体检测需要使用标注好的数据集进行训练。这里我们以COCO数据集为例。COCO数据集包含了大量的图像和标注信息,非常适合进行物体检测任务。
3.1 下载COCO数据集
你可以从COCO官方网站下载COCO数据集:
wget https://images.cocodataset.org/zips/train2014.zip
wget https://images.cocodataset.org/zips/val2014.zip
3.2 解压数据集
unzip train2014.zip
unzip val2014.zip
3.3 数据集预处理
在Yolo训练之前,需要对数据集进行预处理,包括图像尺寸调整、归一化等操作。以下是一个简单的预处理脚本:
import os
import cv2
import numpy as np
def preprocess_data(data_path, output_path, img_size=(416, 416)):
img_names = os.listdir(data_path)
for img_name in img_names:
img_path = os.path.join(data_path, img_name)
img = cv2.imread(img_path)
img = cv2.resize(img, img_size)
img = img / 255.0
img = img.astype(np.float32)
img_path = img_path.split('/')[-1]
output_path = os.path.join(output_path, img_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
cv2.imwrite(output_path, img)
preprocess_data('train2014', 'train2014_preprocess')
preprocess_data('val2014', 'val2014_preprocess')
四、训练Yolo模型
4.1 准备模型配置文件
首先,需要准备一个模型配置文件,用于定义网络的架构和训练参数。以下是一个简单的模型配置文件示例:
# yolov3.cfg
[net]
backbone = darknet53
width = 416
height = 416
channels = 3
momentum = 0.9
decay = 0.0005
angle = 0
saturation = 1.5
exposure = 1.5
mean = 0, 0, 0
hue = 0.1
# yolo
mask = 0
anchors = 10,14,23,27,37,58,81,82,135,169,344,319
classes = 80
classes = 1
num = 5
jitter = 0.3
truth_thresh = 1
random = 1
iou_thresh = 0.5
score_thresh = 0.5
nms_thresh = 0.4
weight_decay = 5e-4
init_weight = normal
batch = 64
subdivs = 8
scales = 0.1
learning_rate = 0.01
max_batches = 500000
policy = step
steps = 40000,450000
scales = 0.1,0.1
decay = 0.1
end_epoch = 500
4.2 训练模型
接下来,使用训练脚本开始训练模型:
python train.py --cfg yolov3.cfg --data data/coco.data --weights weights/yolov3.weights --name yolov3 --epochs 100
五、实战案例
5.1 读取图片
import cv2
img_path = 'data/dog.jpg'
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
5.2 检测人体
import numpy as np
from PIL import Image
# 加载模型
model = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
# 转换图片格式
img = Image.fromarray(np.uint8(img))
img = img.resize((416, 416))
img = np.array(img)
# 检测人体
blob = cv2.dnn.blobFromImage(img, 1/255, (416, 416), swapRB=True, crop=False)
model.setInput(blob)
output_layers = model.getUnconnectedOutLayersNames()
outputs = model.forward(output_layers)
# 解析检测结果
boxes = []
confidences = []
class_ids = []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# 获取边界框信息
center_x = int(detection[0] * img.shape[1])
center_y = int(detection[1] * img.shape[0])
w = int(detection[2] * img.shape[1])
h = int(detection[3] * img.shape[0])
# 计算边界框坐标
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 非极大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边界框
for i in indices:
i = i[0]
x, y, w, h = boxes[i]
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
通过以上实战案例,你可以轻松地使用Yolo进行人体检测。在实际应用中,你可以根据自己的需求对模型进行优化和调整,以达到更好的检测效果。
