Helmet detection method based on YOLOv5 network
By introducing the attention mechanism and convolutional attention module CBAM into the YOLOv5 network, combined with the CIOU Loss loss function, the accuracy problem of helmet detection in dim conditions is solved, and efficient and accurate helmet detection is achieved.
Patent Information
- Application Number
- CN202210405929.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2022-04-18
- Publication Date
- 2024-08-23
- Estimated Expiration
- 2042-04-18
Smart Images

Figure CN114842503B
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of computer vision applications, and in particular relates to a helmet detection method based on a YOLOv5 network. Background Art
[0002] Electric vehicles have always been an important means of transportation for people's daily travel. In recent years, with the development of new energy technologies, electric vehicles have become more powerful and have longer driving ranges, but the number of traffic accidents they cause has also been increasing.
[0003] Scientific research shows that properly worn helmets can absorb a significant portion of the impact energy in the event of an accident, minimizing head injuries and reducing the risk of fatalities in traffic accidents by 60% to 70%. Traditional helmet wear detection methods rely on manual inspection of footage captured by cameras, which is inefficient and costly. Therefore, designing an automated helmet wear detection method is crucial for improving the accuracy and efficiency of helmet wear detection, assisting traffic law enforcement, and enabling intelligent traffic management.
[0004] Helmets are difficult to identify due to their small size and diversity, coupled with the diverse scenes and complex interactions between objects. Furthermore, helmet detection faces the following challenges: In dim conditions, low light intensity and visibility make it difficult to accurately locate electric vehicles, significantly increasing the difficulty of helmet detection.
[0005] Most published object detection methods have achieved good results for helmet detection, but their accuracy remains to be improved under dim conditions with low visibility and low illumination. In exploring deep learning-based helmet detection methods, Prajwal et al. first used YOLOv2 to detect people and scooters in video frames, then used YOLOv3 to detect whether a helmet was contained within a region of interest (ROI). This method used a redundant framework and was computationally intensive. Noel et al. first used traditional machine vision methods to classify motorcycles and scooters, then used the YOLOv3 object detection framework to detect helmets. This method has high requirements for shooting angle and image quality. Summary of the Invention
[0006] In order to solve the above technical defects in the prior art, the present invention proposes a helmet detection method based on the YOLOv5 network.
[0007] The technical solution for achieving the purpose of the present invention is: a helmet detection method based on the YOLOv5 network, comprising:
[0008] The original image is preprocessed using the Mosaic-8 image enhancement algorithm;
[0009] The pre-processed images are input into the YOLOv5 network with the attention mechanism for iterative training. The optimal weight model is obtained through repeated iterative training.
[0010] The image to be detected is preprocessed and then input into the optimal weight model for helmet detection.
[0011] Preferably, the original image dataset is produced by combining web crawling with self-photography, wherein 80% of the images come from the Internet and 20% come from actual photography.
[0012] Preferably, the original image is labeled with two labels, yes and no, where no indicates that the electric bike rider is not wearing a helmet and yes indicates that he is wearing a helmet. An image enhancement algorithm is used to translate, flip, rotate, and scale the image labeled yes, separate the three color channels, and add random noise.
[0013] Preferably, all C3-n modules in the target YOLOv5 algorithm model are added with a convolutional attention module CBAM.
[0014] Preferably, the C3-n module includes three standard convolutional layers and n Bottleneck modules. The C3-n module is used to learn residual features. Its structure is divided into two branches, one branch specifies n Bottleneck modules and 1 standard convolutional layer, and the other branch passes through 1 standard convolutional layer. Finally, the two branches are subjected to feature fusion operation and then pass through 1 standard convolutional layer. Among them, a convolutional attention module CBAM is added at the end of each Bottleneck module.
[0015] Preferably, the convolutional attention module CBAM channel attention module CAM and spatial attention module SAM, the channel attention module CAM is for the input feature F∈R C×H×W The maximum pooling operation based on width and height and the global average pooling are used to compress in the spatial dimension to obtain two feature maps and R C×H×W The two feature maps share a two-layer neural network MLP. The number of neurons in the first layer is C / r, r is the reduction rate, the activation function is ReLU, and the number of neurons in the second layer is C. The two feature maps output by MLP are summed based on the elements and then normalized by the Sigmoid activation function to obtain the final channel attention feature map M. c ∈R C ×1×1 ;
[0016] The spatial attention module SAM takes the output feature map of the channel attention module CAM as input, performs channel-based global maximum pooling and global average pooling on the input feature map, and obtains two feature maps and The two feature maps are connected in series, concatenated based on the channel, and then a 7×7 convolution operation is performed to generate the spatial attention feature M. s ∈R 1×H×W .
[0017] Preferably, the loss function of the target YOLOv5 algorithm model consists of classification loss, positioning loss and target confidence loss.
[0018] Preferably, the target YOLOv5 algorithm model uses CIOU Loss as the loss function for target box regression, specifically:
[0019]
[0020] in, d1 represents the Euclidean distance between the two center points of the prediction box and the target box, and d2 represents the diagonal distance of the minimum enclosing rectangle. and Represent the aspect ratios of the target frame and the predicted frame respectively,
[0021] Preferably, a binary cross entropy loss function is used to calculate the classification loss and target confidence loss, specifically:
[0022]
[0023]
[0024] In the formula, K represents the feature map output by the network, which is divided into K×K grids, and M represents the number of anchor boxes corresponding to each grid. Indicates the anchor box with target, represents the anchor box without target, λ no_obj Represents the confidence loss weight coefficient without the target anchor box, C i and Represent the predicted and actual confidence of the existence of an object in the i-th grid. i (c) and They represent the predicted and true probabilities of the object belonging to category c, respectively.
[0025] Compared with the prior art, the present invention has the following significant advantages:
[0026] The attention mechanism introduced in this paper acts on the feature map and can achieve better task results by obtaining the available attention information in the feature map;
[0027] This paper adopts CIOU Loss as the loss function for target box regression. Since CIOU Loss measures the overlapping area, center point distance and aspect ratio from three perspectives, the effect of prediction box regression is better.
[0028] This paper adds the CBAM module to the YOLOv5 network. Because the CBAM model incorporates a global maximum pooling operation within the channel attention module, it can, to a certain extent, compensate for the information lost by global average pooling. Secondly, the generated two-dimensional spatial attention map is encoded using a convolutional layer with a kernel size of 7. Larger kernels are particularly helpful in preserving important spatial regions. This enables the YOLOv5 network to not only more accurately classify and identify targets, but also more precisely locate their locations.
[0029] Other features and advantages of the present invention will be described in the following description, and in part will become apparent from the description or be understood by practicing the present invention. The purposes and other advantages of the present invention can be realized and obtained by the structures particularly pointed out in the written description, claims, and drawings. BRIEF DESCRIPTION OF THE DRAWINGS
[0030] The accompanying drawings are only for the purpose of illustrating particular embodiments and are not to be considered limiting of the present invention. Like reference symbols denote like parts throughout the drawings.
[0031] Figure 1 A flowchart of a helmet detection method based on a YOLOv5 network is provided in an embodiment of the present invention.
[0032] Figure 2 A YOLOv5 network structure diagram provided by an embodiment of the present invention.
[0033] Figure 3 A CBAM network structure diagram provided for an embodiment of the present invention.
[0034] Figure 4 A CAM structure diagram provided in an embodiment of the present invention.
[0035] Figure 5 A SAM structure diagram provided in an embodiment of the present invention.
[0036] Figure 6 Some pictures of the dataset.
[0037] Figure 7 This is a visualization analysis diagram of the dataset after image enhancement.
[0038] Figure 8 Schematic diagram of Focus slicing operation.
[0039] Figure 9 Schematic diagram of the Conv module structure.
[0040] Figure 10 This is a schematic diagram of the C3-n module structure.
[0041] Figure 11 Figure 2 is a schematic diagram of the Focus module structure.
[0042] Figure 12 Schematic diagram of the SPP module structure.
[0043] Figure 13 Schematic diagram of the Bottleneck module structure in the backbone network.
[0044] Figure 14 This is a structural diagram of the Bottleneck module in the Head module. DETAILED DESCRIPTION
[0045] It is easy to understand that, based on the technical solution of the present invention, a person of ordinary skill in the art can imagine various embodiments of the present invention without changing the essential spirit of the present invention. Therefore, the following specific embodiments and drawings are merely illustrative of the technical solution of the present invention and should not be regarded as the whole of the present invention or as a limitation or limitation of the technical solution of the present invention. On the contrary, the purpose of providing these embodiments is to enable those skilled in the art to understand the present invention more thoroughly. The preferred embodiments of the present invention are described in detail below in conjunction with the accompanying drawings, wherein the accompanying drawings constitute a part of this application and are used together with the embodiments of the present invention to illustrate the innovative concept of the present invention.
[0046] like Figure 1 As shown, the present invention is conceived as a helmet detection method based on the YOLOv5 network, comprising:
[0047] The original images were preprocessed using the Mosaic-8 image enhancement algorithm and then divided into training and test datasets. The images were then fed into a YOLOv5 network incorporating the Convolutional Block Attention Module (CBAM) attention mechanism for iterative training, effectively enhancing the extraction of key points such as faces and masks. The optimal weighted model was obtained through repeated iterative training. After training, the optimal weighted model was saved and tested on the test set.
[0048] As an example, a dataset of original images was created by combining web crawling and self-photography. 80% of the images were sourced from the internet, and 20% were captured in real-world photography. The actual photography primarily captured images of helmet wearers in dimly lit conditions. This example primarily captured images in low-visibility conditions, such as at night and early morning.
[0049] The original image dataset is preprocessed using image enhancement algorithms and the dataset is divided. Figure 6 As shown in the figure, in this example, 10,000 images in the dataset were labeled with two types of labels: yes and no, where no indicates that the e-bike rider was not wearing a helmet and yes indicates that he was wearing one. The dataset uses the YOLO format, and the images are labeled using LabelImg. The annotated files have a .txt extension and the file name matches the image name.
[0050] In order to solve the problem of slight inter-class imbalance in the dataset, the image enhancement algorithm is used to translate, flip, rotate, and scale the sample images labeled "yes", separate the three color channels and add random noise, so as to effectively alleviate the problem of inter-class imbalance. Figure 7 shown.
[0051] As an example, Figure 2 As shown, the preprocessed data is input into the target YOLOv5 algorithm model, where it is downsampled by a factor of 32 using one Focus module and four Conv modules. The Focus module slices the input data, taking a value for every other pixel in an image, similar to neighboring downsampling. This data is then divided into four parts, each equivalent to a 2x downsampling. The sampled data is concatenated along the channel dimension and convolved through the Conv module. After each convolution, the image information enters a C3-n module. This module, modeled after the CSPNet (CrossStage Partial Network) architecture, splits the feature map of the base layer within a stage into two parts. This split-and-merge strategy is applied across stages, integrating gradient changes into the feature map from beginning to end. The output of the final C3-n module is passed to the Head module. The Head module achieves top-down information flow by transferring and fusing high-level feature information with lower-level feature information using upsampling. Then, the convolution with a step size of 2 is used to process the bottom-level features and the high-level features, so that the bottom-level feature information is transmitted to the upper layer, thereby realizing the PANet operation. Figures 8 to 14 shown.
[0052] In a further embodiment, all C3-n modules in the target YOLOv5 algorithm model are added with a convolutional attention module CBAM, such as Figure 3 Specifically:
[0053] The C3-n module contains three standard convolutional layers (Conv modules) and n Bottleneck modules. The C3-n module is used to learn residual features. Its structure is divided into two branches. One branch specifies n Bottleneck modules and one standard convolutional layer, and the other branch only passes through one standard convolutional layer. Finally, the two branches are subjected to feature fusion operation and then passed through one standard convolutional layer.
[0054] Adding a convolutional attention module (CBAM) at the end of each Bottleneck module means that each C3-n performs an attention mechanism calculation, weighting the different dimensions of attention to the target in the feature image, improving the algorithm's extraction of the target's main features in the feature image. This improves the accuracy of the target detection algorithm.
[0055] Specifically, if Figure 4 、 5 As shown in the figure, the convolutional attention module CBAM includes two sub-modules, namely the channel attention module CAM and the spatial attention module SAM.
[0056] The channel attention module CAM is used to summarize the channel attention information. The channel attention module CAM is a given arbitrary intermediate feature F∈R C×H×W The feature map is compressed in the spatial dimension using global max pooling and global average pooling based on width and height. and Two feature maps share a two-layer neural network MLP. The number of neurons in the first layer is C / r (r is the reduction rate), the activation function is ReLU, and the number of neurons in the second layer is C. Then, the two feature maps output by MLP are summed based on the elements and normalized by the Sigmoid activation function to obtain the final channel attention feature map M. c ∈R C×1×1 .
[0057] The spatial attention module SAM is used to summarize the spatial attention information. The spatial attention module SAM mainly focuses on the position information of the target on the image. The spatial attention module SAM takes the output feature map of the channel attention module CAM as input, and performs channel-based global maximum pooling and global average pooling on the input feature map, respectively. and Two feature maps are then connected in series, concatenated based on the channel, and then a 7×7 convolution operation is performed to generate the spatial attention feature M.s ∈R 1×H×W .
[0058] The target YOLOv5 algorithm model loss function consists of classification loss, localization loss, and target confidence loss. The present invention uses a binary cross-entropy loss function to calculate the classification loss and target confidence loss. To reduce error, the localization loss is calculated using CIOU. By adjusting parameters and using gradient propagation to minimize this loss function, an optimized model is ultimately obtained, reducing overall error.
[0059] Furthermore, CIOU Loss is used as the positioning loss function in the network structure, specifically:
[0060]
[0061] in, d1 represents the Euclidean distance between the two center points of the prediction box and the target box, and d2 represents the diagonal distance of the minimum enclosing rectangle. and Represent the aspect ratios of the target frame and the prediction frame respectively. IoU is one of the commonly used performance evaluation indicators in target detection. The accuracy of the prediction frame is judged according to the degree of overlap between the target frame and the prediction frame, that is,
[0062] Furthermore, the binary cross entropy loss function is used to calculate the classification loss and target confidence loss, specifically:
[0063]
[0064]
[0065] Where K represents the feature map output by the network, which is divided into K×K grids, and M represents the number of anchor boxes corresponding to each grid. Indicates the anchor box with target, Indicates an anchor box without an object. no_obj Represents the confidence loss weight coefficient without target anchor box. C i and Represent the predicted and actual confidence of the existence of an object in the i-th grid. i (c) and They represent the predicted and true probabilities of the object belonging to category c, respectively.
[0066] To train the optimal weighted model, repeat the network training process and continuously adjust the parameters of the helmet detection network until the network learns to identify e-bike riders in images and correctly determines whether they are wearing helmets. Save the trained parameters. After training is complete, save the optimal weighted model and test it on the test set.
[0067] During the network model training phase, the iteration batch size was set to 32 and the total number of iterations was 600. The initial learning rate was set to 0.001, and the mini-batch gradient descent method was used. The Adam optimizer was used to calculate the adaptive learning rate of each parameter.
[0068] Example 1
[0069] This embodiment provides a helmet detection method based on a YOLOv5 network, including:
[0070] In the first step, a dataset of 9,000 images, which was created by combining web crawling and self-photography, was classified, formatted, and pre-processed manually.
[0071] Step 2: Input the preprocessed image into the YOLOv5 network with the attention mechanism for iterative training, and obtain the optimal weight model through repeated iterative training;
[0072] Step 3: Preprocess the image to be detected and input it into the optimal weight model for helmet detection.
[0073] In this example, a dataset was collected by combining web crawling and self-photography. 80% of the images were collected from the internet, and 20% were taken in real-world photography. The actual photography primarily captured images of helmet wearers in dim conditions. During the experiment, images were primarily taken in low-visibility conditions such as at night and early morning. The experimental parameters are shown in the table below:
[0074]
[0075] In this embodiment, the training effect is improved by optimizing the loss function.
[0076] Specifically, before explaining the YOLOv5 algorithm model, the loss function used in its structure is first explained. In the present invention, the binary cross entropy loss function is used to calculate the classification loss and target confidence loss. The loss function used in the present invention is as follows:
[0077]
[0078]
[0079] It should be noted that in the loss function formula, K represents the feature map output by the network, which is divided into K×K grids, and M represents the number of anchor boxes corresponding to each grid. Indicates the anchor box with target, represents the anchor box without target, λ no_obj Represents the confidence loss weight coefficient without target anchor box. C i and Represent the predicted and actual confidence of the existence of an object in the i-th grid. i (c) and They represent the predicted and true probabilities of the object belonging to category c, respectively.
[0080] Furthermore, the present invention adopts CIOU Loss as the loss function for target box regression, and CIOU Loss is as follows:
[0081]
[0082] in, d1 represents the Euclidean distance between the two center points of the prediction box and the target box, and d2 represents the diagonal distance of the minimum enclosing rectangle. and Represent the aspect ratios of the target box and the predicted box respectively.
[0083] Based on the original YOLOv5 network, this paper introduces the convolutional attention module CBAM. It should be noted that CBAM contains two submodules, the channel attention module CAM and the spatial attention module SAM. CAM summarizes the channel attention information. CAM is a given arbitrary intermediate feature F∈R C×H×W The feature map is compressed in the spatial dimension using global maxpooling and global average pooling based on width and height. and Two feature maps share a two-layer neural network MLP. The number of neurons in the first layer is C / r (r is the reduction rate), the activation function is ReLU, and the number of neurons in the second layer is C. Then, the two feature maps output by MLP are summed based on the elements and normalized by the Sigmoid activation function to obtain the final channel attention feature map M. c ∈R C×1×1 .
[0084] SAM aggregates spatial attention information. SAM focuses on the location of the target in the image. It uses the output feature map of CAM as the output feature map of this module. It first performs a global maximum pooling and a global average pooling based on the channel to obtain and Two feature maps are then connected in series, concatenated based on the channel, and then a 7×7 convolution operation is performed to generate the spatial attention feature M. s ∈R 1×H×W .
[0085] In this embodiment, the iteration batch size is set to 32, the total number of iterations is 600, the initial learning rate is set to 0.001, the small batch gradient descent method is adopted, and the Adam optimizer is used to update the network parameters.
[0086] In this embodiment, the model evaluation indicators mainly use mean average precision (mAP), recall rate (Recall), and precision (Precision). It should be noted that mean average precision (mAP) is the sum of the average precision of all categories divided by the average precision of all classes in the dataset, as shown in the following formula, where the AP value is the area of the PR curve.
[0087]
[0088] Recall, that is, the probability that the correct category in the sample is predicted correctly by the model, is shown below, where TP represents the number of positive categories predicted as positive categories, and FN represents the number of positive categories predicted as negative categories.
[0089]
[0090] Accuracy is the number of correctly predicted positive samples in the prediction dataset divided by the actual number of positive samples, as shown in the following formula, where FP represents the number of negative classes predicted as positive classes.
[0091]
[0092] In one implementation, after model training is complete, the trained parameters are saved, and the optimal weighted model is saved and tested on a test set. This paper utilizes the Mosaic-8 image enhancement algorithm to preprocess images, combining channel attention and spatial attention to fully exploit key feature points of electric vehicles and helmets, taking into account the impact of light intensity on detection accuracy during actual testing. This attention mechanism enables more accurate extraction of key features of helmets, enabling the original YOLOv5 network to achieve stronger feature expression capabilities, thereby improving detection accuracy.
[0093] This paper, powered by image enhancement and an attention mechanism, uses an improved YOLOv5 model to efficiently detect helmet wear and accurately determine whether a helmet is being worn correctly. In dim conditions with low visibility and illumination, the introduction of an attention mechanism enables more accurate extraction of key features of electric vehicle helmets, improving both detection accuracy and helmet detection efficiency. This paper also improves the YOLOv5 network's loss function, resulting in greater robustness and scalability, essentially meeting the real-time requirements of video images.
[0094] The above description is only a preferred embodiment of the present invention, but the protection scope of the present invention is not limited thereto.
[0095] Any changes or substitutions that can be easily conceived by those skilled in the art within the technical scope disclosed in the present invention should be included in the protection scope of the present invention.
[0096] It should be understood that in order to simplify the present invention and help those skilled in the art understand the various aspects of the present invention, in the above description of the exemplary embodiments of the present invention, various features of the present invention are sometimes described in a single embodiment or described with reference to a single figure. However, the present invention should not be interpreted as if all the features included in the exemplary embodiments are essential technical features of the claims of this patent.
[0097] It should be understood that the modules, units, components, etc. included in the device of one embodiment of the present invention can be adaptively changed to be installed in a device different from the embodiment. The different modules, units, or components included in the device of the embodiment can be combined into a single module, unit, or component, or they can be divided into multiple sub-modules, sub-units, or sub-components.
Claims
1. A helmet detection method based on YOLOv5 network, It is characterized in that include: The original image is preprocessed using the Mosaic-8 image enhancement algorithm; The preprocessed images are input into the YOLOv5 network with the attention mechanism for iterative training, and the optimal weight model is obtained through repeated iterative training; All C3-n modules in the target YOLOv5 algorithm model have added convolutional attention modules CBAM; The C3-n module includes three standard convolutional layers and n Bottleneck modules. The C3-n module is used to learn residual features. Its structure is divided into two branches. One branch specifies n Bottleneck modules and one standard convolutional layer, and the other branch passes through one standard convolutional layer. Finally, the two branches are subjected to feature fusion operation and then pass through one standard convolutional layer. A convolutional attention module CBAM is added at the end of each Bottleneck module. The convolutional attention module CBAM includes a channel attention module CAM and a spatial attention module SAM. The channel attention module CAM is used to input the feature F∈R C×H×W The maximum pooling operation based on width and height and the global average pooling are used to compress in the spatial dimension to obtain two feature maps. and R C×H×W The two feature maps share a two-layer neural network MLP. The number of neurons in the first layer is C / r, r is the reduction rate, the activation function is ReLU, and the number of neurons in the second layer is C. The two feature maps output by MLP are summed based on the elements, and then normalized by the Sigmoid activation function to obtain the final channel attention feature map M. c ∈R C×1×1 ; The spatial attention module SAM takes the output feature map of the channel attention module CAM as input, and performs channel-based global maximum pooling and global average pooling on the input feature map to obtain two feature maps and The two feature maps are connected in series, concatenated based on the channel, and then a 7×7 convolution operation is performed to generate the spatial attention feature M. s ∈R 1×H×W ; After preprocessing, the image to be detected is input into the optimal weight model for helmet detection.
2. The helmet detection method based on the YOLOv5 network according to claim 1, It is characterized in that The original image dataset is created by combining web crawling and self-photography, of which 80% of the images come from the Internet and 20% from actual photography.
3. The helmet detection method based on the YOLOv5 network according to claim 1, It is characterized in that The original images are labeled with two types of labels: yes and no. No means that the electric bike rider is not wearing a helmet, and yes means wearing a helmet. The image enhancement algorithm is used to translate, flip, rotate, and scale the images labeled yes, separate the three color channels, and add random noise.
4. The helmet detection method based on the YOLOv5 network according to claim 1, It is characterized in that The loss function of the target YOLOv5 algorithm model consists of classification loss, positioning loss and target confidence loss.
5. The helmet detection method based on the YOLOv5 network according to claim 4, It is characterized in that The target YOLOv5 algorithm model uses CIOU Loss as the loss function for target box regression, specifically: in, d 1 Represents the Euclidean distance between the two center points of the prediction box and the target box, d 2 represents the diagonal distance of the minimum enclosing rectangle, and Respectively represent the aspect ratios of the target box and the predicted box, 6. The helmet detection method based on the YOLOv5 network according to claim 4, It is characterized in that The binary cross entropy loss function is used to calculate the classification loss and target confidence loss, specifically: In the formula, K represents the feature map finally output by the network divided into K×K grids, M represents the number of anchor boxes corresponding to each grid, represents the anchor box with target, represents the anchor box without target, λ no_obj Represents the confidence loss weight coefficient without the target anchor box, C i and Represent the predicted confidence and true confidence of the existence of the object in the i-th grid, p i (c) and They represent the predicted probability and true probability that the object belongs to category c respectively.
