YOLOv5如何进行区域目标检测(手把手教学)

基于yolov5的区域目标检测 基于yolov5的区域目标检测 先上图片 使用的是yolov5官方的yolov5s.pt权重,可以根据代码替换为自己的权重或者其他yolov5官方权重,代码的github链接: 首先是装环境,用的pycharm+conda的话在terminal里面输入: pip install -r requirements.txt 装好环境以后可以将自己想要检测的图片放入data/images/文件里面:然后就可以直接运行detect.py python detect.py 如果想要运行自己的摄像头: python 阅读详情
AI摘要

本文详细介绍了如何利用YOLOv5进行区域目标检测,通过设置特定的检测范围,使得模型仅在指定区域内进行目标检测。首先,你需要确定检测区域的四个顶点像素坐标,并计算其相对于图片总像素的比例。然后,在detect.py文件中修改代码,插入计算好的比例值,创建一个遮罩mask覆盖非检测区域。最后,运行修改后的代码,模型将按设定的检测区域进行目标检测。这种方法适用于需要针对特定区域进行检测的场景,如监控视频或特定应用场景的图像处理。

YOLOv5如何进行区域目标检测(手把手教学)

提示:本项目的源码是基于yolov5 6.0版本修改



效果展示

在使用YOLOv5的有些时候,我们会遇到一些具体的目标检测要求,比如要求不检测全图,只在规定的区域内才检测。所以为了满足这个需求,可以用一个mask覆盖掉不想检测的区域,使得YOLOv5在检测的时候,该覆盖区域就不纳入检测范围。

话不多说,直接上检测效果,可以很直观的看到目标在进入规定的检测区域才得到检测。
检测规定范围是否出现人


一、确定检测范围

快捷查询方法:

  1. 用windows自带画图打开图片
  2. 鼠标移到想要框选检测区域的四个顶点,查询点的像素坐标
  3. 分别计算点的像素坐标与图片总像素坐标的比例(后面要用)
    查询方法如下图所示:
    在这里插入图片描述
    提示:以下是计算的举例说明,仅供参考
    例如:图中所标注的点(1010,174)代表(x,y)坐标
    hl1 = 174 / 768 (可约分)监测区域纵坐标距离图片***顶部*** 比例
    wl1 = 1010 / 1614 (可约分)监测区域横坐标距离图片***左部*** 比例
    这里只举例了一个点,如检测范围是四边形,需要计算左上,右上,右下,左下四个顶点。

二、detect.py代码修改

1.确定区域检测范围

在下面代码位置填上计算好的比例:

 # mask for certain region
        #1,2,3,4 分别对应左上,右上,右下,左下四个点
        hl1 = 1.4 / 10 #监测区域高度距离图片顶部比例
        wl1 = 6.4 / 10 #监测区域高度距离图片左部比例
        hl2 = 1.4 / 10  # 监测区域高度距离图片顶部比例
        wl2 = 6.8 / 10  # 监测区域高度距离图片左部比例
        hl3 = 4.5 / 10  # 监测区域高度距离图片顶部比例
        wl3 = 7.6 / 10  # 监测区域高度距离图片左部比例
        hl4 = 4.5 / 10  # 监测区域高度距离图片顶部比例
        wl4 = 5.5 / 10  # 监测区域高度距离图片左部比例

在135行:for path, img, im0s, vid_cap in dataset: 下插入代码:

        # mask for certain region
        #1,2,3,4 分别对应左上,右上,右下,左下四个点
        hl1 = 1.6 / 10 #监测区域高度距离图片顶部比例
        wl1 = 6.4 / 10 #监测区域高度距离图片左部比例
        hl2 = 1.6 / 10  # 监测区域高度距离图片顶部比例
        wl2 = 6.8 / 10  # 监测区域高度距离图片左部比例
        hl3 = 4.5 / 10  # 监测区域高度距离图片顶部比例
        wl3 = 7.6 / 10  # 监测区域高度距离图片左部比例
        hl4 = 4.5 / 10  # 监测区域高度距离图片顶部比例
        wl4 = 5.5 / 10  # 监测区域高度距离图片左部比例
        if webcam:
            for b in range(0,img.shape[0]):
                mask = np.zeros([img[b].shape[1], img[b].shape[2]], dtype=np.uint8)
                #mask[round(img[b].shape[1] * hl1):img[b].shape[1], round(img[b].shape[2] * wl1):img[b].shape[2]] = 255
                pts = np.array([[int(img[b].shape[2] * wl1), int(img[b].shape[1] * hl1)],  # pts1
                                [int(img[b].shape[2] * wl2), int(img[b].shape[1] * hl2)],  # pts2
                                [int(img[b].shape[2] * wl3), int(img[b].shape[1] * hl3)],  # pts3
                                [int(img[b].shape[2] * wl4), int(img[b].shape[1] * hl4)]], np.int32)
                mask = cv2.fillPoly(mask,[pts],(255,255,255))
                imgc = img[b].transpose((1, 2, 0))
                imgc = cv2.add(imgc, np.zeros(np.shape(imgc), dtype=np.uint8), mask=mask)
                #cv2.imshow('1',imgc)
                img[b] = imgc.transpose((2, 0, 1))

        else:
            mask = np.zeros([img.shape[1], img.shape[2]], dtype=np.uint8)
            #mask[round(img.shape[1] * hl1):img.shape[1], round(img.shape[2] * wl1):img.shape[2]] = 255
            pts = np.array([[int(img.shape[2] * wl1), int(img.shape[1] * hl1)],  # pts1
                            [int(img.shape[2] * wl2), int(img.shape[1] * hl2)],  # pts2
                            [int(img.shape[2] * wl3), int(img.shape[1] * hl3)],  # pts3
                            [int(img.shape[2] * wl4), int(img.shape[1] * hl4)]], np.int32)
            mask = cv2.fillPoly(mask, [pts], (255,255,255))
            img = img.transpose((1, 2, 0))
            img = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask)
            img = img.transpose((2, 0, 1))

2.画检测区域线(若不想像效果图一样显示出检测区域可不添加)

在196行: p, s, im0, frame = path, ‘’, im0s.copy(), getattr(dataset, ‘frame’, 0) 后添加

            if webcam:  # batch_size >= 1
                p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
                cv2.putText(im0, "Detection_Region", (int(im0.shape[1] * wl1 - 5), int(im0.shape[0] * hl1 - 5)),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1.0, (255, 255, 0), 2, cv2.LINE_AA)

                pts = np.array([[int(im0.shape[1] * wl1), int(im0.shape[0] * hl1)],  # pts1
                                [int(im0.shape[1] * wl2), int(im0.shape[0] * hl2)],  # pts2
                                [int(im0.shape[1] * wl3), int(im0.shape[0] * hl3)],  # pts3
                                [int(im0.shape[1] * wl4), int(im0.shape[0] * hl4)]], np.int32)  # pts4
                # pts = pts.reshape((-1, 1, 2))
                zeros = np.zeros((im0.shape), dtype=np.uint8)
                mask = cv2.fillPoly(zeros, [pts], color=(0, 165, 255))
                im0 = cv2.addWeighted(im0, 1, mask, 0.2, 0)
                cv2.polylines(im0, [pts], True, (255, 255, 0), 3)
                # plot_one_box(dr, im0, label='Detection_Region', color=(0, 255, 0), line_thickness=2)
            else:
                p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
                cv2.putText(im0, "Detection_Region", (int(im0.shape[1] * wl1 - 5), int(im0.shape[0] * hl1 - 5)),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1.0, (255, 255, 0), 2, cv2.LINE_AA)
                pts = np.array([[int(im0.shape[1] * wl1), int(im0.shape[0] * hl1)],  # pts1
                                [int(im0.shape[1] * wl2), int(im0.shape[0] * hl2)],  # pts2
                                [int(im0.shape[1] * wl3), int(im0.shape[0] * hl3)],  # pts3
                                [int(im0.shape[1] * wl4), int(im0.shape[0] * hl4)]], np.int32)  # pts4
                # pts = pts.reshape((-1, 1, 2))
                zeros = np.zeros((im0.shape), dtype=np.uint8)
                mask = cv2.fillPoly(zeros, [pts], color=(0, 165, 255))
                im0 = cv2.addWeighted(im0, 1, mask, 0.2, 0)

                cv2.polylines(im0, [pts], True, (255, 255, 0), 3)

总结

基于yolov5的区域目标检测实质上就是在图片选定检测区域做一个遮掩mask,检测区域不一定为四边形,也可是其他形状。该方法可检测图片/视频/摄像头。
提示:使用该方法要先确定数据集图像是否像监控图像一样,画面主体保持不变
原理展现如图所示:(图片参考http://t.csdn.cn/lgyO1)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

整体detect.py修改代码

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Run inference on images, videos, directories, streams, etc.

Usage:
    $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640
"""

import argparse
import os
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnn

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.experimental import attempt_load
from utils.datasets import LoadImages, LoadStreams
from utils.general import apply_classifier, check_img_size, check_imshow, check_requirements, check_suffix, colorstr, \
    increment_path, non_max_suppression, print_args, save_one_box, scale_coords, set_logging, \
    strip_optimizer, xyxy2xywh
from utils.plots import Annotator, colors
from utils.torch_utils import load_classifier, select_device, time_sync


@torch.no_grad()
def run(weights=ROOT / 'yolov5s.pt',  # model.pt path(s)
        source=ROOT / 'data/images',  # file/dir/URL/glob, 0 for webcam
        imgsz=640,  # inference size (pixels)
        conf_thres=0.25,  # confidence threshold
        iou_thres=0.45,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # show results
        save_txt=False,  # save results to *.txt
        save_conf=False,  # save confidences in --save-txt labels
        save_crop=False,  # save cropped prediction boxes
        nosave=False,  # do not save images/videos
        classes=None,  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms=False,  # class-agnostic NMS
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/detect',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        line_thickness=3,  # bounding box thickness (pixels)
        hide_labels=False,  # hide labels
        hide_conf=False,  # hide confidences
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        ):
    source = str(source)
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://', 'https://'))

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Initialize
    set_logging()
    device = select_device(device)
    half &= device.type != 'cpu'  # half precision only supported on CUDA

    # Load model
    w = str(weights[0] if isinstance(weights, list) else weights)
    classify, suffix, suffixes = False, Path(w).suffix.lower(), ['.pt', '.onnx', '.tflite', '.pb', '']
    check_suffix(w, suffixes)  # check weights have acceptable suffix
    pt, onnx, tflite, pb, saved_model = (suffix == x for x in suffixes)  # backend booleans
    stride, names = 64, [f'class{i}' for i in range(1000)]  # assign defaults
    if pt:
        model = torch.jit.load(w) if 'torchscript' in w else attempt_load(weights, map_location=device)
        stride = int(model.stride.max())  # model stride
        names = model.module.names if hasattr(model, 'module') else model.names  # get class names
        if half:
            model.half()  # to FP16
        if classify:  # second-stage classifier
            modelc = load_classifier(name='resnet50', n=2)  # initialize
            modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
    elif onnx:
        if dnn:
            # check_requirements(('opencv-python>=4.5.4',))
            net = cv2.dnn.readNetFromONNX(w)
        else:
            check_requirements(('onnx', 'onnxruntime'))
            import onnxruntime
            session = onnxruntime.InferenceSession(w, None)
    else:  # TensorFlow models
        check_requirements(('tensorflow>=2.4.1',))
        import tensorflow as tf
        if pb:  # https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
            def wrap_frozen_graph(gd, inputs, outputs):
                x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), [])  # wrapped import
                return x.prune(tf.nest.map_structure(x.graph.as_graph_element, inputs),
                               tf.nest.map_structure(x.graph.as_graph_element, outputs))

            graph_def = tf.Graph().as_graph_def()
            graph_def.ParseFromString(open(w, 'rb').read())
            frozen_func = wrap_frozen_graph(gd=graph_def, inputs="x:0", outputs="Identity:0")
        elif saved_model:
            model = tf.keras.models.load_model(w)
        elif tflite:
            interpreter = tf.lite.Interpreter(model_path=w)  # load TFLite model
            interpreter.allocate_tensors()  # allocate
            input_details = interpreter.get_input_details()  # inputs
            output_details = interpreter.get_output_details()  # outputs
            int8 = input_details[0]['dtype'] == np.uint8  # is TFLite quantized uint8 model
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # Dataloader
    if webcam:
        view_img = check_imshow()
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
        bs = len(dataset)  # batch_size
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
        bs = 1  # batch_size
    vid_path, vid_writer = [None] * bs, [None] * bs

    # Run inference
    if pt and device.type != 'cpu':
        model(torch.zeros(1, 3, *imgsz).to(device).type_as(next(model.parameters())))  # run once
    dt, seen = [0.0, 0.0, 0.0], 0
    for path, img, im0s, vid_cap in dataset:
        # mask for certain region
        #1,2,3,4 分别对应左上,右上,右下,左下四个点
        hl1 = 1.6 / 10 #监测区域高度距离图片顶部比例
        wl1 = 6.4 / 10 #监测区域高度距离图片左部比例
        hl2 = 1.6 / 10  # 监测区域高度距离图片顶部比例
        wl2 = 6.8 / 10  # 监测区域高度距离图片左部比例
        hl3 = 4.5 / 10  # 监测区域高度距离图片顶部比例
        wl3 = 7.6 / 10  # 监测区域高度距离图片左部比例
        hl4 = 4.5 / 10  # 监测区域高度距离图片顶部比例
        wl4 = 5.5 / 10  # 监测区域高度距离图片左部比例
        if webcam:
            for b in range(0,img.shape[0]):
                mask = np.zeros([img[b].shape[1], img[b].shape[2]], dtype=np.uint8)
                #mask[round(img[b].shape[1] * hl1):img[b].shape[1], round(img[b].shape[2] * wl1):img[b].shape[2]] = 255
                pts = np.array([[int(img[b].shape[2] * wl1), int(img[b].shape[1] * hl1)],  # pts1
                                [int(img[b].shape[2] * wl2), int(img[b].shape[1] * hl2)],  # pts2
                                [int(img[b].shape[2] * wl3), int(img[b].shape[1] * hl3)],  # pts3
                                [int(img[b].shape[2] * wl4), int(img[b].shape[1] * hl4)]], np.int32)
                mask = cv2.fillPoly(mask,[pts],(255,255,255))
                imgc = img[b].transpose((1, 2, 0))
                imgc = cv2.add(imgc, np.zeros(np.shape(imgc), dtype=np.uint8), mask=mask)
                #cv2.imshow('1',imgc)
                img[b] = imgc.transpose((2, 0, 1))

        else:
            mask = np.zeros([img.shape[1], img.shape[2]], dtype=np.uint8)
            #mask[round(img.shape[1] * hl1):img.shape[1], round(img.shape[2] * wl1):img.shape[2]] = 255
            pts = np.array([[int(img.shape[2] * wl1), int(img.shape[1] * hl1)],  # pts1
                            [int(img.shape[2] * wl2), int(img.shape[1] * hl2)],  # pts2
                            [int(img.shape[2] * wl3), int(img.shape[1] * hl3)],  # pts3
                            [int(img.shape[2] * wl4), int(img.shape[1] * hl4)]], np.int32)
            mask = cv2.fillPoly(mask, [pts], (255,255,255))
            img = img.transpose((1, 2, 0))
            img = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask)
            img = img.transpose((2, 0, 1))

        t1 = time_sync()
        if onnx:
            img = img.astype('float32')
        else:
            img = torch.from_numpy(img).to(device)
            img = img.half() if half else img.float()  # uint8 to fp16/32
        img = img / 255.0  # 0 - 255 to 0.0 - 1.0
        if len(img.shape) == 3:
            img = img[None]  # expand for batch dim
        t2 = time_sync()
        dt[0] += t2 - t1

        # Inference
        if pt:
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(img, augment=augment, visualize=visualize)[0]
        elif onnx:
            if dnn:
                net.setInput(img)
                pred = torch.tensor(net.forward())
            else:
                pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img}))
        else:  # tensorflow model (tflite, pb, saved_model)
            imn = img.permute(0, 2, 3, 1).cpu().numpy()  # image in numpy
            if pb:
                pred = frozen_func(x=tf.constant(imn)).numpy()
            elif saved_model:
                pred = model(imn, training=False).numpy()
            elif tflite:
                if int8:
                    scale, zero_point = input_details[0]['quantization']
                    imn = (imn / scale + zero_point).astype(np.uint8)  # de-scale
                interpreter.set_tensor(input_details[0]['index'], imn)
                interpreter.invoke()
                pred = interpreter.get_tensor(output_details[0]['index'])
                if int8:
                    scale, zero_point = output_details[0]['quantization']
                    pred = (pred.astype(np.float32) - zero_point) * scale  # re-scale
            pred[..., 0] *= imgsz[1]  # x
            pred[..., 1] *= imgsz[0]  # y
            pred[..., 2] *= imgsz[1]  # w
            pred[..., 3] *= imgsz[0]  # h
            pred = torch.tensor(pred)
        t3 = time_sync()
        dt[1] += t3 - t2

        # NMS
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
        dt[2] += time_sync() - t3

        # Second-stage classifier (optional)
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process predictions
        for i, det in enumerate(pred):  # per image
            seen += 1
            # if webcam:  # batch_size >= 1
            #     p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
            # else:
            #     p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
            if webcam:  # batch_size >= 1
                p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
                cv2.putText(im0, "Detection_Region", (int(im0.shape[1] * wl1 - 5), int(im0.shape[0] * hl1 - 5)),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1.0, (255, 255, 0), 2, cv2.LINE_AA)

                pts = np.array([[int(im0.shape[1] * wl1), int(im0.shape[0] * hl1)],  # pts1
                                [int(im0.shape[1] * wl2), int(im0.shape[0] * hl2)],  # pts2
                                [int(im0.shape[1] * wl3), int(im0.shape[0] * hl3)],  # pts3
                                [int(im0.shape[1] * wl4), int(im0.shape[0] * hl4)]], np.int32)  # pts4
                # pts = pts.reshape((-1, 1, 2))
                zeros = np.zeros((im0.shape), dtype=np.uint8)
                mask = cv2.fillPoly(zeros, [pts], color=(0, 165, 255))
                im0 = cv2.addWeighted(im0, 1, mask, 0.2, 0)
                cv2.polylines(im0, [pts], True, (255, 255, 0), 3)
                # plot_one_box(dr, im0, label='Detection_Region', color=(0, 255, 0), line_thickness=2)
            else:
                p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
                cv2.putText(im0, "Detection_Region", (int(im0.shape[1] * wl1 - 5), int(im0.shape[0] * hl1 - 5)),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1.0, (255, 255, 0), 2, cv2.LINE_AA)
                pts = np.array([[int(im0.shape[1] * wl1), int(im0.shape[0] * hl1)],  # pts1
                                [int(im0.shape[1] * wl2), int(im0.shape[0] * hl2)],  # pts2
                                [int(im0.shape[1] * wl3), int(im0.shape[0] * hl3)],  # pts3
                                [int(im0.shape[1] * wl4), int(im0.shape[0] * hl4)]], np.int32)  # pts4
                # pts = pts.reshape((-1, 1, 2))
                zeros = np.zeros((im0.shape), dtype=np.uint8)
                mask = cv2.fillPoly(zeros, [pts], color=(0, 165, 255))
                im0 = cv2.addWeighted(im0, 1, mask, 0.2, 0)

                cv2.polylines(im0, [pts], True, (255, 255, 0), 3)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # img.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # img.txt
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if save_crop else im0  # for save_crop
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
                        with open(txt_path + '.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                        annotator.box_label(xyxy, label, color=colors(c, True))
                        if save_crop:
                            save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

            # Print time (inference-only)
            print(f'{s}Done. ({t3 - t2:.3f}s)')

            # Stream results
            im0 = annotator.result()
            if view_img:
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video' or 'stream'
                    if vid_path[i] != save_path:  # new video
                        vid_path[i] = save_path
                        if isinstance(vid_writer[i], cv2.VideoWriter):
                            vid_writer[i].release()  # release previous video writer
                        if vid_cap:  # video
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        else:  # stream
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
                            save_path += '.mp4'
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
                    vid_writer[i].write(im0)

    # Print results
    t = tuple(x / seen * 1E3 for x in dt)  # speeds per image
    print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
        print(f"Results saved to {colorstr('bold', save_dir)}{s}")
    if update:
        strip_optimizer(weights)  # update model (to fix SourceChangeWarning)

def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / '权重文件', help='model path(s)')
    parser.add_argument('--source', type=str, default=ROOT / '检测图片', help='file/dir/URL/glob, 0 for webcam')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='show results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--line-thickness', default=1, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=True, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(FILE.stem, opt)
    return opt


def main(opt):
    check_requirements(exclude=('tensorboard', 'thop'))
    run(**vars(opt))


if __name__ == "__main__":
    opt = parse_opt()
    main(opt)


Yolov5基于目标区域(Region of Interest)的检测 Yolov5基于目标区域(Region of Interest)的检测前言引入mask图的制作yolo基于mask的检测 前言引入 想必大家在做yolo目标检测的时候很容易会遇上这样的问题,图片中的某个部分其实我并不想去检测里面的物品,它无关紧要… 正如这个转角,我的本意只想检测前方通道的目标,这个转角应该交给另外的摄像头去识别,所以我不希望因为这里出现了一小部分物体,导致整个检测结果受到影响,因此,想要让yolo不检测这一部分区域… 所以为了实现这个功能,我们可以用一个mask覆盖掉这个区域,让yolo 阅读详情

相关推荐

Python——一文详解使用yolov5进行目标检测全流程(无需gpu)

本文按步骤详细介绍了使用yolov5进行目标检测的全流程,包括:模型下载、环境配置、数据集准备和数据预处理、模型调整、模型训练、进行目标检测和检测结果分析。本文全部流程使用cpu完成(无需gpu),旨在跑通流程,模型训练过程较慢,且未能到达最优结果。需要 python版本>=3.8。

weixin_53848907的博客 7580

YOLOv5实战垃圾分类目标检测

垃圾分类是一项利国利民的民生工程,需要全社会的共同参与。YOLOv5是目前流行的强悍的目标检测技术。本项目采用YOLOv5实现垃圾分类目标检测。利用超万张已标注目标检测数据集进行训练,对居民生活垃圾图片进行检测,找出图片中属于哪个类别的垃圾,并指示出在图片中的位置。本课程的YOLOv5使用PyTorch版的ultralytics/yolov5,分别在Windows和Ubuntu系统上进行垃圾分类目标检测的项目演示。具体项目过程包括:数据集及格式转换、探索性数据分析(EDA)、安装软件环境、安装YOLOv5、修改YOLOv5代码(为支持中文标签)、训练集和测试集自动划分、修改配置文件、准备Weights&Biases训练可视化工具、训练网络模型、测试训练出的网络模型和性能统计。

Day6 目标检测实战:YOLOv5从训练到部署全流程

🚀:掌握本章技术可胜任80%的工业检测岗位需求!今日完整实现从数据标注到Edge端部署的全链路开发。

资深全栈架构师,乐于在 CSDN 分享技术见解,与大家携手共进,共攀技术巅峰! 1748

快(50%)两步实现yolov5只检测指定区域,屏蔽非检测区域(包含效果视频)

使用mask来实现yolo只检测指定区域

weixin_41826859的博客 3994

YOLOv5目标检测算法——通俗易懂的解析

YOLOv5目标检测算法——通俗易懂的解析

chase 1万+

基于RYU+Mininet的SDN校园网络实战:从零搭建虚拟化实验环境

本文详细介绍了如何利用RYU控制器和Mininet搭建SDN校园网络实验环境,从Ubuntu虚拟机准备到网络拓扑设计,再到关键网络功能实现。通过实战案例展示SDN在校园网络中的应用优势,包括简化配置、提升效率等,为网络工程师和学生提供了一套完整的虚拟化实验方案。

weixin_30872499的博客 460

调用yolov5模型基于opencv实现区域检测功能

调用yolov5模型基于opencv实现检测指定种类的物体是否在固定区域内,本方法适用于yolov5的预训练模型和自己训练的pt模型,既可检测图片视频,也可实现实时检测摄像头的功能。

qq_43601763的博客 1867

医学图像处理(一)使用U-Net进行MRI的肝脏分割

医学图像处理(一)使用U-Net进行MRI的肝脏分割数据集搜集训练集和测试集划分问题一: 测试集不包括GroundTruth问题二:T1和T2的数据能一起训练吗?问题三: T1的图像在文件夹中分成了InPhase和OutPhase,这个有什么区别?分离出肝脏将dicom文件转换为png格式数据增强U-net网络搭建自定义DatasetMain.py实验结果总结 图像分割小白一枚,之前接到一个MRI图像肝脏分割的任务。对于医学图像分割,第一想到的就是Unet. Unet在2015的MICCAI上首次提出,在医

qq_34003876的博客 2万+

使用PyQt5搭建yoloV5目标检测平台

使用PyQt5搭建YoLoV5目标检测平台

uuhhy的博客 2万+

图解基站机房:AAU、RRU与BBU之间的线缆连接与规格选择

本文以图解方式详解了5G基站机房中AAU、RRU与BBU三大核心设备之间的线缆连接方案与规格选择。重点阐述了电力线(如2×10 mm²直流电缆)、数据光缆(如野战光缆与波分复用)及射频馈线的功能、选型标准与实战布线法则,为通信工程部署与维护提供清晰指导。

weixin_29306011的博客 509

scRNA-seq | 吐血整理的单细胞入门教程(从原理到代码实操)(二)

scRNA-seq | 吐血整理的单细胞入门教程(从原理到代码实操)(二)

m0_72224305的博客 4307

YOLOv5区域入侵检测【附完整代码以及视频演示】

基于yolov5框架修改的。可以自己定义需要检测的区域,采用的权重文件是官方版本的yolov5s.pt。增加了本地摄像头检测、处理帧率的显示、以及检测的种类及其数量进行输出表示。

m0_58508552的博客 1万+

SAP LTMC实战指南:物料主数据高效导入全解析

本文详细解析了SAP LTMC工具在物料主数据高效导入中的实战应用,包括工具选择、项目搭建、模板定制、数据导入全流程及常见问题解决方案。重点介绍了LTMC的预置模板、LTMOM灵活配置、数据校验机制等核心功能,帮助用户快速掌握SAP数据迁移技巧,提升工作效率。

weixin_33738555的博客 436

yolov5 目标检测区域识别具体实现(摄像机识别区域加mask蒙版)

区域识别的具体实现可以通过以下步骤完成:1.数据预处理:首先,需要对输入的图像进行预处理,将其缩放到固定的尺寸大小,并将像素值归一化到0到1的范围内。此外,还需要进行数据增强的操作,包括随机裁剪、旋转、翻转等,以增加训练数据的多样性和鲁棒性。2.网络结构:YOLOv5采用了一种基于骨干网络的轻量级网络结构,即CSPDarknet。该网络结构由多个连续的CSP块组成,每个CSP块由一个卷积层和多个残差块组成,其中残差块内部也包含了CSP结构。这种设计可以使得模型在保证高精度的情况下,具有更高

zhuim99的博客 3391

33、AI赋能5G/6G通信:LDPC码解码与强化学习技术解析

本文探讨了基于AI和强化学习的LDPC码技术在5G/6G通信中的应用。包括LAMS解码器、神经MS解码器、盲识别方法、统一极性-LDPC解码器、NNMS和SNNMS解码器、N-2D-NMS解码器、神经分层MS解码器、MAB-NS方案以及强化学习与MCTS结合的技术。这些技术在提升解码性能、降低计算复杂度和增强系统适应性方面表现出色,为未来通信系统的发展提供了强有力的支持。

lambda的博客 247

数据科学助力大数据领域的航空安全分析

随着航空业的快速发展,航班数量不断增加,航空安全问题日益受到关注。大数据时代的到来,使得航空领域积累了大量的数据,包括飞行数据、维护数据、气象数据等。本文章的目的在于探讨如何运用数据科学的方法和技术,对这些大数据进行分析,以提高航空安全水平。范围涵盖了从数据收集、预处理到数据分析、模型构建和应用的整个流程。本文将按照以下结构进行组织:首先介绍数据科学和航空安全分析的核心概念以及它们之间的联系;接着阐述核心算法原理和具体操作步骤,并使用Python源代码进行详细说明;

软件工程实践的博客 1294

【目标检测】全网最全最详细YOLOv5训练自定义数据集教程

本教程专为刚入门 YOLOv5 并渴望训练自定义数据集的初学者设计,从零开始,详细介绍了项目的完整流程。通过使用 Conda 环境管理,在 PyCharm 中部署 YOLOv5,实现自定义数据集的目标检测任务。

小白一枚~ 1万+

【Unity终极奥义】Unity打包去掉启动画面Logo,无需破解,一学就会

大家都知道Unity打包的应用在启动的时候都会有一个默认的UnityLogo。 而且这个Logo使用升级版和破解版都是可以随意清除和更换的。 但是Unity个人版是无法通过Unity的打包设置去进行更换的。 那今天就教大家一个使用个人普通版更换Unity启动画面Logo的方法!一起来看一下吧!

努力前行,总会成为自己心中的那道光 8万+

【目标检测】TPH-YOLOv5:基于transformer的改进yolov5的无人机目标检测

最近在使用VisDrone作为目标检测任务的数据集,看到了这个TPH-YOLOv5这个模型在VisDrone2021testset-challenge数据集上的检测效果排到了第五,mAP达到39.18%。于是开始阅读它的论文,并跑一跑的它的代码。......

兴趣使然的创作者 1万+

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

【AI模型开发】如何使用YOLOv5进行目标检测?

YOLOv5是一个开源的目标检测模型。它是YOLO系列的升级版,由Ultralytics开发,并于2020年年中发布。YOLO的全称是you only look once,指只需要浏览一次就可以识别出图中的物体的类别和位置。对计算机而言,能够“看到”的是图像被编码之后的数字,所以它很难理解高层语义概念,比如图像或者视频帧中出现的目标是人还是物体,更无法定位目标出现在图像中哪个区域。目标检测的主要目的是让计算机可以自动识别图片或者视频帧中所有目标的类别,并在该目标周围绘制边界框,标示出每个目标的位置。

分享是一种境界,勤于分享,乐于分享! 1189

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

Pyqt搭建YOLOV5目标检测界面

Pyqt搭建YOLOV5目标检测界面

qq1309399183的博客 1603

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

【目标检测】Yolov5训练自己的数据集、设计危险区域判定算法及模型部署(持续更新)

简单说明一下在这篇文章中我要完成的任务:识别出图像中的窗户和儿童位置,并对儿童是否身处窗户内的危险区域进行算法判断,最终反馈给后端一个安全或危险的信号。将训练好的模型和设计好的算法部署在Jetson Nano设备上,以便深度学习的推理以及与后端的交互。 毕竟我是负责深度学习这部分的,所以本文我着重讲一下几个方面(当然一定是各位读者非常希望学习到的知识):如何配置yolov5所需环境、如何处理可能遇到的bug、如何收集自己需要的图片数据集、如何给图片标注标签、如何制作自己的配置文件、如何修改优化模型参数、如.

我的技术栈碎碎念空间 4309

突破边界:一文读懂YOLOv5如何精准划分目标区域

你是否曾困惑为什么AI能瞬间识别图像中的物体?当你在监控画面中看到行人被红色方框框出,汽车被蓝色圆圈标记时,背后隐藏着计算机视觉领域最核心的技术之一——决策边界(Decision Boundary)。作为Ultralytics YOLOv8的前身,YOLOv5凭借其独特的边界划分机制,在目标检测、图像分割和分类任务中实现了速度与精度的完美平衡。本文将用通俗语言拆解YOLOv5的决策边界原理,带你掌...

gitblog_00161的博客 799

从OpenCV到YOLOV5:目标检测从理论到实战

本文系统性地研究了目标检测技术从传统方法到深度学习的演进过程,重点对比分析了OpenCV级联分类器与YOLOv5的核心原理、技术特点及适用场景。通过深入研究Haar特征与卷积神经网络的特征提取机制,揭示了两种方法在检测精度、计算效率等方面的本质差异。在实践层面,详细探讨了使用Labelme进行数据标注的方法论,以及如何利用Roboflow等平台获取和优化训练数据集。基于上述理论研究,我们将YOLOv5模型部署至树莓派嵌入式平台,实现了垃圾分类目标检测系统的工程化应用。

2401_86849688的博客 1379

5.2 单阶段目标检测模型YOLOv3

其中跟真实框IoU最大的是锚框A_3,形状是(373,326),将它所对应的预测框的objectness标签设置为1,其所包括的物体类别就是真实框里面的物体所属类别。,每个锚框会有一个跟它对应的预测框,我们需要确定上面计算式中的t_x, t_y, t_w, t_h,从而计算出与锚框对应的预测框的位置和形状。,P_1, P_2,... , P_C则是锚框包含的物体属于每个类别的概率。为了回答问题,只需要将上面预测框坐标中的b_x, b_y, b_h, b_w设置为真实框的位置,即可求解出t的数值。

我亦无他,唯手熟尔 1578

视频目标检测 yolov

视频目标检测

jacke121的专栏 2031
上一篇: YOLOV5 6.0加入CA注意力机制(看了包会)
wiz_k
博客等级 码龄9年 1万+粉丝 3原创
评论 68
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wiz_k

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值