人群识别 python使用yolov5编写代码,从200张图片中随机选出20张图片,识别出图片中的虚拟人物,统计虚拟人物的数量和其中红色系、蓝色系上衣的人物数量,在终端中以文字形式输出相应的数量
时间: 2023-06-20 16:07:46 浏览: 77
以下是使用yolov5进行人群识别的Python代码,包括随机选取图片和统计虚拟人物数量及颜色系上衣的人物数量:
```python
import os
import random
import cv2
import torch
from pathlib import Path
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device
# 加载模型
model = attempt_load('yolov5s.pt', map_location=torch.device('cpu'))
# 选择设备
device = select_device('')
# 设置阈值
conf_thres = 0.25
iou_thres = 0.45
# 图片路径
img_dir = Path('image_dir')
# 从图片中随机选取20张
num_imgs = 20
img_paths = random.sample(list(img_dir.glob('*.jpg')), num_imgs)
# 统计虚拟人物数量
total_persons = 0
red_clothes_persons = 0
blue_clothes_persons = 0
for img_path in img_paths:
# 加载图片
img = cv2.imread(str(img_path))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 图片预处理
img_size = 640
img = cv2.resize(img, (img_size, img_size))
img = torch.from_numpy(img).to(device)
img = img.float() / 255.0
img = img.unsqueeze(0)
# 模型推理
pred = model(img)[0]
pred = non_max_suppression(pred, conf_thres, iou_thres)
# 统计虚拟人物数量及颜色系上衣的人物数量
for det in pred:
if det is not None and len(det):
for *xyxy, conf, cls in det:
xyxy = scale_coords(img.shape[2:], xyxy, img.shape[2:]).tolist()
if cls == 0:
total_persons += 1
x1, y1, x2, y2 = xyxy
crop = img[int(y1):int(y2), int(x1):int(x2)]
avg_color_per_row = np.average(crop, axis=0)
avg_color = np.average(avg_color_per_row, axis=0)
if avg_color[0] > avg_color[2]:
red_clothes_persons += 1
else:
blue_clothes_persons += 1
# 输出结果
print(f"在{num_imgs}张图片中,共识别出{total_persons}个虚拟人物,其中红色系上衣的人物数量为{red_clothes_persons},蓝色系上衣的人物数量为{blue_clothes_persons}")
```
其中,yolov5s.pt 是预训练模型的权重文件,需要下载并放置在当前目录下。img_dir 是存储图片的文件夹路径,需要根据实际情况进行修改。输出结果以文字形式在终端中显示。