*Article* **An Improved YOLOv5 Model: Application to Mixed Impurities Detection for Walnut Kernels**

**Lang Yu, Mengbo Qian \*, Qiang Chen, Fuxing Sun and Jiaxuan Pan**

College of Optical Mechanical and Electrical Engineering, ZhejiangA&F University, Hangzhou 311300, China **\*** Correspondence: qianmengbo@zafu.edu.cn; Tel.:+86-189-6802-0808

**Abstract:** Impurity detection is an important link in the chain of food processing. Taking walnut kernels as an example, it is difficult to accurately detect impurities mixed in walnut kernels before the packaging process. In order to accurately identify the small impurities mixed in walnut kernels, this paper established an improved impurities detection model based on the original YOLOv5 network model. Initially, a small target detection layer was added in the neck part, to improve the detection ability for small impurities, such as broken shells. Secondly, the Tansformer-Encoder

(Trans-E) module is proposed to replace some convolution blocks in the original network, which can better capture the global information of the image. Then, the Convolutional Block Attention Module (CBAM) was added to improve the sensitivity of the model to channel features, which make it easy to find the prediction region in dense objects. Finally, the GhostNet module is introduced to make the model lighter and improve the model detection rate. During the test stage, sample photos were randomly chosen to test the model's efficacy using the training and test set, derived from the walnut database that was previously created. The mean average precision can measure the multi-category recognition accuracy of the model. The test results demonstrate that the mean average precision (*mAP*) of the improved YOLOv5 model reaches 88.9%, which is 6.7% higher than the average accuracy of the original YOLOv5 network, and is also higher than other detection networks. Moreover, the improved YOLOv5 model is significantly better than the original YOLOv5 network in identifying small impurities, and the detection rate is only reduced by 3.9%, which meets the demand of real-time detection of food impurities and provides a technical reference for the detection of small impurities in food.

**Keywords:** YOLOv5; walnut kernels; impurities detection; small object detection
