数人 2
opencv自带的Haar特征分类器进行人脸检测 效果太差,尝试使用 yolo看看
从GitHub上下载了yolov3.cfg、yolov3.weights、coco.names,然后试着数人
import cv2 `
import numpy as np
# 加载YOLO网络配置和权重
net = cv2.dnn.readNet("d:\\yolov3.weights", "d:\\yolov3.cfg")
classes = []
with open("d:\\coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 加载图像
img = cv2.imread("d:\\202408212.jpg")
img = cv2.resize(img, None, fx=0.4, fy=0.4)
height, width, channels = img.shape
# 检测图像中的对象
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(net.getUnconnectedOutLayersNames())
# 显示信息在屏幕上
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# 对象检测
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# 矩形框
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)
# 使用NMS去除多余的框
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 计算人数
person_count = 0
color = (255, 0, 0)
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
if label == 'person': # 假设'person'是类名中表示人的标签
person_count += 1
cv2.rectangle(img, (x, y), (x + w, y + h), color, 1)
#cv2.putText(img, label, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
print(f"Detected {person_count} people in the image.")
# 显示图像
plt.figure(figsize=(20, 16))
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # 将BGR转换为RGB以正确显示颜色
plt.show()
效果好一些了,正面、没有被遮掩的都可以计算到了