yolov5区域检测+计数

注意:我用的代码不是YOLO官方的源代码

如果你已经用了YOLO官方的源代码--就不用看了

如果你还没有Yolo代码可以参考一下

一、代码

借鉴的一位博主的代码(GitHub)

视频

二、修改的地方

具体如何使用、预测、训练等看博主的视频讲解

都有

位于 yolo.py里面

#---------------------------------------------------------#
        #   图像绘制
        #---------------------------------------------------------#
        number = 0
        for i, c in list(enumerate(top_label)):
            predicted_class = self.class_names[int(c)]
            box             = top_boxes[i]
            score           = top_conf[i]

            top, left, bottom, right = box

            top     = max(0, np.floor(top).astype('int32'))
            left    = max(0, np.floor(left).astype('int32'))
            bottom  = min(image.size[1], np.floor(bottom).astype('int32'))
            right   = min(image.size[0], np.floor(right).astype('int32'))

            label = '{} {:.2f}'.format(predicted_class, score)
            draw = ImageDraw.Draw(image)
            label_size = draw.textsize(label, font)
            label = label.encode('utf-8')
            #print("预测框数据:",label, top, left, bottom, right)

            if top - label_size[1] >= 0:
                text_origin = np.array([left, top - label_size[1]])
            else:
                text_origin = np.array([left, top + 1])

            for i in range(thickness):
                draw.rectangle([left + i, top + i, right - i, bottom - i], outline=self.colors[c])
            draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c])
            draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font)
            del draw
-------------------------------------以下是添加的----------------------------------------------
            # ---------------------------------------------------------#
            #   区域检测
            # ---------------------------------------------------------#
            # 预测框中心点
            x = (left + right) // 2
            y = (top + bottom) // 2
            centre = (x, y)
            #print("预测框中心点:", centre)
            b = ImageDraw.ImageDraw(image)  # 用b来表示
            b.point(centre, fill='blue')

            # 绘制区域---------检测区域自行修改
            h = image_shape[1]    # 图片的长
            k = image_shape[0]    # 图片的宽
            x1 = h // 10  # 左    # 左上角x值=长的1/10
            x2 = (9 * h) // 10  # 右    # 右上角x值=长的9/10
            y1 = k // 10  # 上    # 左上角y值=长的1/10
            y2 = (9 * k) // 10  # 下    # 右上角y值=长的9/10
            a = ImageDraw.ImageDraw(image)  # 用a来表示
            a.rectangle(((x1, y1), (x2, y2)), fill=None, outline='green', width=5)


            # 判断中心点是否在区域内
            '''
            判断x的值是否在范围内
            判断y值是否在范围内
            '''

            # 判断x值
            if x in range(x1, (x2 + 1)):
                if y in range(y1, (y2 + 1)):
                    number += 1
                else:
                    break
            else:
                break
        print("警告!有人入侵!!!")
        print('人数:', number)
        num = str(number)
        d = ImageDraw.ImageDraw(image)  # 用d来表示
        d.text((5, 10), "人数:" + num, fill=(255, 0, 0), font=font)    # 左上角显示人数
----------------------------------------以上-------------------------------------------------
        return image

修改后预测就行了(视频、图片都可以)

  • 2
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
你可以使用YOLOv8来进行行人检测,并计算检测到的行人数量。YOLOv8是一种基于深度学习的目标检测算法,它能够实时地对图像或视频的多个目标进行准确的检测和定位。 以下是一个示例代码片段,演示了如何使用YOLOv8来进行行人检测计数: ```python import cv2 import numpy as np # 加载YOLOv8模型 net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights') # 获取输出层信息 layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] # 加载图像 image = cv2.imread('image.jpg') height, width, channels = image.shape # 对图像进行预处理 blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) # 运行前向传播,获取输出层的结果 outs = net.forward(output_layers) # 解析输出结果,计算行人数量 class_ids = [] confidences = [] bounding_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 and class_id == 0: # 类别id为0表示行人 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) bounding_boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) # 进行非最大值抑制 indexes = cv2.dnn.NMSBoxes(bounding_boxes, confidences, 0.5, 0.4) # 绘制边界和标签 font = cv2.FONT_HERSHEY_PLAIN count = 0 for i in range(len(bounding_boxes)): if i in indexes: x, y, w, h = bounding_boxes[i] cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(image, 'Person', (x, y - 5), font, 1, (0, 255, 0), 1) count += 1 # 显示结果 cv2.imshow("Image", image) cv2.waitKey(0) cv2.destroyAllWindows() # 打印行人数量 print("Number of pedestrians detected:", count) ``` 请注意,上述代码是一个简化的示例,你需要根据自己的需求进行适当的修改和调整。此外,确保已经正确下载和配置了YOLOv8的配置文件和权重文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值