A method and system for detecting impurities in wheat raw grain

CN122799433APending Publication Date: 2026-09-22HEZE MUDAN DISTRICT HUALU FLOUR CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611086353.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-21
Publication Date
2026-09-22

AI Technical Summary

Technical Problem

[0006]为解决杂质外观差异大、正常籽粒与杂质易混淆,且原粮图像存在密集堆积和稀疏分布差异,导致固定阈值检测易误检、漏检的技术问题,本申请在如下的多个方面中提供方案

Benefits of technology

提取连通区域外围轮廓的有序坐标点序列,根据轮廓点之间的相邻连线方向变化,确定连通区域的边界曲率参数;

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122799433A_ABST
    Figure CN122799433A_ABST
Patent Text Reader

Abstract

The application belongs to the technical field of impurity detection, and particularly relates to a wheat raw grain impurity detection method and system, which comprises the following steps: collecting a wheat raw grain image and performing multi-band decomposition to generate multiple frequency band component images and a preliminary impurity mask; extracting boundary curvature and morphological compactness of the mask connected region to form a combined geometric descriptor, removing a region meeting a wheat kernel morphology constraint and counting its geometric parameters, and reserving the remaining region to obtain a calibrated impurity mask; constructing a threshold adjustment function based on the geometric descriptor of the removed kernel; calculating an image gradient amplitude to obtain a spatial saliency weight map, and weightedly fusing the calibrated impurity mask to generate an impurity consistency score map; combining a raw grain foreground structure density to divide a dense accumulation area and a sparse distribution area, and generating a partition threshold according to global statistical moments and local spatial variables, and obtaining an impurity detection result through partition binarization and merging; and thus the accuracy and stability of wheat raw grain impurity detection are improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of impurity detection technology. More specifically, this application relates to a method and system for detecting impurities in raw wheat. Background Technology

[0002] Wheat is one of the most important food crops in my country and even globally. Its quality is related to national food security and the daily lives of the people. During the harvesting, threshing, and initial storage and transportation of wheat, various impurities such as straw, awns, weed seeds, gravel, mud, and shriveled wheat grains are often mixed in. These impurities can affect the grading and pricing of raw wheat and can also cause safety hazards such as overheating and mold during subsequent storage, reducing the quality and flour yield of processed flour. Therefore, the detection and removal of impurities in raw wheat is an important step in the grain storage and processing process.

[0003] Traditional wheat impurity detection mainly relies on manual sampling and visual observation. This method is time-consuming, labor-intensive, and inefficient. Moreover, it is easily affected by the experience and visual fatigue of the inspectors, and cannot guarantee the consistency of the test results. In recent years, with the rapid development of computer vision and image processing technology, optical image-based detection technology has gradually become an important development trend in the field of wheat impurity detection due to its non-destructive advantages.

[0004] However, in practical applications of wheat grain image processing, the impurities mixed in the grain are numerous and varied, with significant randomness and range in size, surface texture, and morphology. Furthermore, some organic impurities are similar in color and luster to normal wheat grains, making conventional image feature extraction methods often unable to completely separate various impurities from the varied background. Due to the influence of gravity and natural stacking, the spatial distribution of acquired wheat grain images is usually uneven, often containing densely packed areas where grains are obscured and compressed, as well as sparsely distributed areas with large areas of exposed background. This variation in spatial density distribution leads to significant differences in local image features. If a globally uniform judgment standard or a fixed image segmentation threshold is used, it cannot adapt to the morphological manifestations of normal wheat grains under different aggregation states. In densely packed areas, impurity response is weakened due to grain obscuration and texture superposition, leading to missed detections. In sparsely distributed areas, isolated noise or local background texture is misjudged as impurities, resulting in false detections.

[0005] Therefore, how to reduce the interference caused by the varied morphology of impurities and cope with the differences in density distribution in different regions of the image to achieve impurity detection is a key problem that urgently needs to be solved in this field. Summary of the Invention

[0006] To address the technical problems of large differences in the appearance of impurities, easy confusion between normal grains and impurities, and differences in dense accumulation and sparse distribution in raw grain images, which lead to false detection and missed detection by fixed threshold detection, this application provides solutions in the following aspects.

[0007] In a first aspect, this application provides a method for detecting impurities in raw wheat grains, comprising:

[0008] S1. Obtain the image of the wheat grain to be detected, perform multi-band decomposition on the wheat grain image to generate multiple frequency band component images, and generate a set of corresponding preliminary impurity masks based on each frequency band component image. S2. Perform geometric screening on the preliminary impurity mask. For the connected regions within each preliminary impurity mask, calculate the combined geometric descriptor of the boundary curvature and morphological compactness of the connected regions. Based on the preset wheat grain morphology constraints, screen out the connected regions that satisfy the constraints and statistically analyze their geometric descriptors. Retain the remaining connected regions to obtain a set of calibration impurity masks. Calculate the global statistical moments based on the geometric descriptors of all removed wheat grain regions and construct a threshold adjustment function accordingly. S3. Calculate the gradient magnitude of the wheat grain image, generate a spatial saliency weight map, perform scale registration on a set of calibration impurity masks, and combine the spatial saliency weight map to perform pixel-by-pixel weighted fusion of the registered calibration impurity masks to generate a consistency score map. Calculate the local structure density based on the foreground region distribution of the wheat grain image, and divide the image into densely packed regions and sparsely distributed regions accordingly. Calculate the regional mean of the consistency score in the densely packed regions and sparsely distributed regions as the local spatial parameters of the corresponding regions. Input the global statistical moments and local spatial parameters into the threshold adjustment function to generate the segmentation threshold corresponding to each region. Based on the segmentation threshold, complete the region binarization and merge to obtain the impurity detection results.

[0009] This application generates multiple frequency band component images through multi-band decomposition and generates preliminary impurity masks for each, effectively capturing the texture differences between impurities and normal wheat grains in different frequency bands, overcoming the problem of insufficient response of single frequency band features to complex impurities. By calculating a combined geometric descriptor of the curvature and morphological compactness of connected region boundaries and filtering out normal wheat grain regions based on preset wheat grain morphology constraints, it can accurately remove interference from wheat grains with similar morphology. At the same time, it uses the geometric descriptor of the removed wheat grains to construct a global statistical moment and a threshold adjustment function, so that the segmentation threshold can adapt to the morphological distribution changes of the current batch of wheat grains. Furthermore, it generates spatial bursts through gradient magnitude. The system generates a consistency score map by combining a weighted image with a calibration impurity mask based on multi-scale registration and performing pixel-by-pixel weighted fusion. This enhances the reliability of strong edge regions and suppresses false positives in weak response regions. Simultaneously, based on local structure density, the image is divided into densely packed regions and sparsely distributed regions. The mean consistency score of each region is calculated and input into a threshold adjustment function to generate a region-specific segmentation threshold. This effectively addresses the problem of weakened impurity response caused by seed occlusion and mutual compression, as well as the problem of isolated noise interference in sparse regions. It improves the detection sensitivity of impurities in dense regions and the detection specificity in sparse regions, ultimately improving the overall image impurity detection accuracy and reducing the false positive and false negative rates.

[0010] Preferably, the step of performing multi-band decomposition on the wheat grain image to generate multiple frequency band component images includes: converting the wheat grain image to be detected from the RGB color space to a single-channel mode to generate a two-dimensional grayscale base image. The two-dimensional discrete wavelet parameter executor based on fixed decomposition bandwidth is invoked. Using a row and column calculation window, low-pass and high-pass filters are used to perform matrix convolution and downsampling filtering on the grayscale base image to extract matrix features of different frequency bands. The output wavelet transform generates a low-frequency component image representing the global approximate features, and the extracted horizontal high-frequency component image, vertical high-frequency component image, and diagonal high-frequency component image are aggregated to construct multiple frequency band component images by combining the independent component images in each direction.

[0011] This application converts RGB images into single-channel grayscale base images, utilizes a two-dimensional discrete wavelet parameter actuator with fixed decomposition bandwidth, and employs low-pass and high-pass filters for matrix convolution and downsampling filtering. This efficiently extracts low-frequency global approximate features as well as high-frequency detail components in the horizontal, vertical, and diagonal directions. The decomposition process involves low computational cost and clear frequency band separation, which facilitates the independent generation of impurity masks for each frequency band component image. This lays a stable data foundation for multi-frequency band fusion detection, while ensuring that the algorithm's processing speed meets the requirements of real-time detection.

[0012] Preferably, the step of generating a set of corresponding preliminary impurity masks based on each frequency band component image includes: loading an edge extraction template model on the image data coordinate plane; calculating the edge gradient for each frequency band component image to obtain the corresponding feature gradient magnitude; comparing the feature gradient magnitude of each pixel with a preset binarization threshold, and marking pixels that meet the threshold condition as foreground pixels and pixels that do not meet the threshold condition as background pixels, thereby generating an initial binary image matrix; identifying connected regions for the foreground pixels in the initial binary image matrix, and counting the number of pixels contained in each connected region to obtain the area of ​​each connected region; filtering each connected region according to a preset area filtering condition, removing connected regions with an area lower than a preset area threshold, and retaining connected regions with an area that meets the preset area threshold condition, thereby generating the corresponding preliminary impurity mask.

[0013] This application calculates edge gradients for each frequency band component by loading an edge extraction template model onto the image coordinate plane and classifying pixels using a preset binarization threshold. This enables rapid localization of potential impurity edge response regions in each frequency band. Furthermore, by identifying connected components and filtering by area, it effectively filters out false regions with excessively small areas caused by camera shot noise or minute texture disturbances, reducing the processing burden of subsequent geometric filtering and fusion calculations, and improving the signal-to-noise ratio and reliability of the initial impurity mask.

[0014] Preferably, the combined geometric descriptor for calculating the boundary curvature and shape compactness of the connected region includes: Extract the ordered coordinate point sequence of the outer contour of the connected region, and determine the boundary curvature parameter of the connected region based on the change in the direction of the adjacent connecting lines between the contour points; Based on the area and perimeter of the connected regions, calculate the morphological compactness parameter that characterizes the compactness of the region shape; The boundary curvature parameters and shape compactness parameters are combined in a preset order to generate a combined geometric descriptor for characterizing the comprehensive shape features of the connected region.

[0015] This application extracts an ordered sequence of coordinate points from the outer contour of a connected region, calculates boundary curvature parameters based on the change in direction of adjacent connecting lines of contour points, and calculates morphological compactness parameters based on the region area and contour perimeter. The two are then combined in a preset order to form a comprehensive shape feature vector, which can comprehensively characterize the contour curvature and shape compactness of the connected region. It can effectively distinguish the elliptical contour of normal wheat grains from the irregular shapes of impurities such as straw and gravel, providing a reliable basis for subsequent precise screening based on morphological constraints.

[0016] Preferably, the construction of the threshold adjustment function includes: extracting the combined geometric descriptors corresponding to all connected regions identified as wheat grains and removed, and statistically analyzing the central tendency and dispersion features of the boundary curvature parameters and morphological compactness parameters therein; combining the central tendency and dispersion features to generate global statistical moment feature parameters that characterize the overall morphological distribution of the current wheat grains; weighting and summing the global statistical moment feature parameters with preset weight coefficients to obtain the basic response value; performing nonlinear normalization mapping on the basic response value to generate a basic segmentation threshold; and when calling the threshold adjustment function, offsetting and correcting the basic segmentation threshold according to the local spatial parameters corresponding to each input partition to obtain the segmentation threshold of the corresponding partition, wherein the local spatial parameters include the regional mean of the consistency score within the corresponding partition.

[0017] This application generates global statistical moment feature parameters by statistically analyzing the central tendency and dispersion characteristics of the boundary curvature and morphological compactness parameters of the removed wheat grain regions. These parameters can dynamically characterize the overall morphological distribution of wheat grains in the current batch. The global statistical moments are weighted and summed with preset weight coefficients and then mapped using nonlinear normalization to obtain the basic segmentation threshold, making the threshold setting batch-adaptive. Furthermore, when calling the application, the basic segmentation threshold is offset and corrected according to the local spatial parameters of each partition, so that densely packed areas and sparsely distributed areas obtain segmentation thresholds suitable for their respective density states. This effectively solves the problem of poor adaptability of fixed global thresholds in images with uneven density, and takes into account the dual suppression requirements of missed detections and false detections.

[0018] Preferably, the step of performing nonlinear normalization mapping on the basic response values ​​to generate a basic segmentation threshold includes: inputting the basic response values ​​into a standard Sigmoid activation function, nonlinearly mapping the basic response values ​​to a probability range of 0 to 1, and generating a basic segmentation threshold.

[0019] Preferably, the step of calculating the gradient magnitude of the wheat grain image and generating a spatial salience weight map includes: By using the sliding operation of the edge detection feature window, the feature gradient components in the horizontal direction and the feature gradient components in the vertical direction of the wheat grain image are extracted respectively. Calculate the gradient magnitude of each pixel using the combined directional gradient characteristics; Extract the maximum gradient magnitude limit index within the entire image region, and perform a proportional division operation on the gradient magnitude at all pixel coordinates to obtain normalized weights; Output normalized weight data in global coordinates and construct a spatial saliency weight map.

[0020] Preferably, the generation of the consistency score map includes: obtaining all calibration impurity masks generated for the corresponding N frequency band components, and upsampling and mapping the coordinates of each calibration impurity mask to the spatial salience weights.Figure 1 In the consistent image coordinate space, feature pixel variables are extracted and retained at the same coordinate points in each mask layer; Combining the weights of the spatial saliency weight map at the corresponding pixel, the foreground determination result of the same pixel position in each calibration impurity mask is multiplied by the spatial saliency weight value corresponding to that pixel position, the resulting products are accumulated, and averaged according to the number of calibration impurity masks participating in the fusion to obtain the impurity consistency score of that pixel position. The consistency scores calculated for each coordinate point are arranged into a two-dimensional structure matrix to generate a consistency score map.

[0021] Preferably, dividing the image into densely packed regions and sparsely distributed regions includes: A foreground structure map of wheat grain is generated in the raw grain image, and a sliding window is set in the foreground structure map of the raw grain. The proportion of non-background pixels within the area covered by the sliding window is counted. When the proportion of non-background pixels meets the dense determination condition, the area corresponding to the center of the current window is determined as a densely packed area. When the proportion of non-background pixels does not meet the dense distribution criteria, the area corresponding to the center of the current window is determined as a sparse distribution area.

[0022] Secondly, this application provides a wheat grain impurity detection system, including a processor and a memory, wherein the memory stores computer program instructions, and when the computer program instructions are executed by the processor, the above-mentioned wheat grain impurity detection method is implemented.

[0023] By adopting the above technical solution, a computer program for detecting impurities in wheat raw materials is generated and stored in a memory so that it can be loaded and executed by a processor. A terminal device can then be made based on the memory and processor for convenient use.

[0024] This application improves the initial detection capability of minute and similar impurities in complex backgrounds by performing multi-band decomposition on wheat grain images and extracting texture features at different scales and directions. Furthermore, it utilizes a combined geometric descriptor constructed from boundary curvature and morphological compactness to geometrically screen suspected areas, eliminating false-detection regions that conform to wheat grain morphology constraints. Global statistical moments are calculated based on the geometric features of the screened grains to characterize the grain morphology distribution of the current batch. Subsequently, a weighted fusion of the calibration impurity mask is performed using a spatial salience weight map to generate an impurity consistency score map, which is then used to divide densely packed areas and sparsely distributed areas based on the foreground structure density of the grain. Partition segmentation thresholds are generated based on the global statistical moments and local spatial parameters of each partition, which can, to a certain extent, balance the risk of missed detection in dense areas and the risk of false detection in sparse areas, thereby improving the accuracy and stability of wheat grain impurity detection. Attached Figure Description

[0025] The above and other objects, features, and advantages of exemplary embodiments of this application will become readily understood by reading the following detailed description with reference to the accompanying drawings. In the drawings, several embodiments of this application are illustrated by way of example and not limitation, and the same or corresponding reference numerals denote the same or corresponding parts, wherein: Figure 1 This is a flowchart of a method for detecting impurities in raw wheat grains according to this application; Figure 2 A scatter plot showing the distribution of geometric characteristic parameters of wheat grains and impurities; Figure 3 This is a schematic diagram of the local structure density fluctuation curve under the sliding window. Detailed Implementation

[0026] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of this application. Based on the embodiments of this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.

[0027] The specific embodiments of this application will now be described in detail with reference to the accompanying drawings.

[0028] This application discloses a method for detecting impurities in raw wheat grains, referring to... Figure 1 This includes steps S1-S3: S1. Obtain the image to be detected, perform multi-band feature decomposition, and generate the corresponding impurity mask.

[0029] Specifically, the wheat grain image to be detected is acquired, the wheat grain image is decomposed into multiple frequency bands to generate multiple frequency band component images, and a set of corresponding preliminary impurity masks is generated based on each frequency band component image.

[0030] Color digital images of wheat samples to be tested are acquired using an industrial camera, and their brightness channels are extracted as the images to be processed. Single-layer two-dimensional discrete wavelet decomposition is performed on the brightness channels to obtain low-frequency components containing low-frequency approximation information, and three high-frequency detail component images containing high-frequency texture information in the horizontal, vertical, and diagonal directions, respectively. For each frequency band component image, a morphological top-hat transformation is first performed to enhance local bright details, resulting in a specular impurity response map. Then, adaptive threshold segmentation is performed on the specular impurity response map, marking pixels that meet the foreground determination criteria as foreground pixels and the remaining pixels as background pixels, generating a binary image of the corresponding frequency band component, and using the binary image as the preliminary impurity mask corresponding to that frequency band component.

[0031] In an optional embodiment, the wheat grain image is decomposed into multiple frequency band components to generate multiple frequency band component images, including: The image of the raw wheat grain to be detected is converted from the RGB color space to a single-channel mode to generate a two-dimensional grayscale base image. The two-dimensional discrete wavelet parameter executor based on fixed decomposition bandwidth is invoked. Using a row and column calculation window, low-pass and high-pass filters are used to perform matrix convolution and downsampling filtering on the grayscale base image to extract matrix features of different frequency bands. The output wavelet transform generates a low-frequency component image representing the global approximate features, and the extracted horizontal high-frequency component image, vertical high-frequency component image, and diagonal high-frequency component image are aggregated to construct multiple frequency band component images by combining the independent component images in each direction.

[0032] When performing color space conversion, use formulas The RGB three-channel image is dimensionality-reduced to obtain a two-dimensional grayscale base image with a pixel depth of 8 bits and a grayscale level ranging from 0 to 255. In the frequency band decomposition stage, the db2 wavelet basis from the Daubechies wavelet family is used as the core function of the two-dimensional discrete wavelet parameter executor, with a fixed decomposition bandwidth set to single-layer decomposition. The row and column calculation windows slide along the row and column directions of the image with a step size of 2, respectively. A low-pass filter with a length of 4 and parameters of -0.129, 0.224, 0.836, and 0.482, and the corresponding high-pass filter are used to perform one-dimensional discrete convolution operations on the image pixels, and downsampling filtering is performed at a ratio of 2:1.

[0033] After alternating row and column convolution and downsampling, the original image matrix is ​​proportionally decomposed into four sub-image matrices, which are output as follows: a low-frequency component image LL containing low-frequency row and column information, representing the main energy and global approximate contour of the image; a horizontal high-frequency component image LH containing low-frequency row and high-frequency column information, a vertical high-frequency component image HL containing high-frequency row and low-frequency column information, and a diagonal high-frequency component image HH containing high-frequency row and high-frequency column information, representing edge detail textures in different directions; the four independent component images, each with a pixel count one-quarter of the original image, are combined in multiple channels to construct a set of multiple frequency band component images containing global features and local high-frequency texture information.

[0034] In an optional embodiment, based on the image of each frequency band component, a set of corresponding preliminary impurity masks is generated, including: An edge extraction template model is loaded onto the image data coordinate plane, and edge gradients are calculated for each frequency band component image to obtain the corresponding feature gradient magnitudes. The feature gradient magnitude of each pixel is compared with the preset binarization threshold. Based on the comparison result, pixels that meet the threshold condition are marked as foreground pixels, and pixels that do not meet the threshold condition are marked as background pixels, thus generating an initial binary image matrix. Connected region identification is performed on the foreground pixels in the initial binary image matrix, and the number of pixels contained in each connected region is counted to obtain the area of ​​each connected region. Each connected region is filtered according to preset area filtering conditions. Connected regions with areas lower than the preset area threshold are removed, while connected regions with areas that meet the preset area threshold conditions are retained, and corresponding preliminary impurity masks are generated.

[0035] Furthermore, the calibration method for the preset area threshold specifically includes: using a physical calibration plate of fixed size to map the pixel resolution of the imaging system and obtain the physical size scale corresponding to each pixel; calculating the projected pixel area in the image space based on the physical outline size of the smallest target particle in the wheat impurity to be detected, and multiplying it by a correction factor of 0.8 as the preset area threshold, thereby filtering out system shot noise and fine dust interference.

[0036] For each generated frequency band component image, a 3×3 Sobel edge extraction template model is loaded. Horizontal convolution kernels with elements of -1, 0, 1, -2, 0, 2, -1, 0, 1 and vertical convolution kernels with elements of 1, 2, 1, 0, 0, 0, -1, -2, -1 are used to perform traversal convolution operations on the frequency band component images, yielding horizontal and vertical gradient values. The feature gradient magnitude corresponding to each coordinate point is then calculated using the Euclidean norm formula, with the data format being single-precision floating-point numbers. In the threshold segmentation step, a preset globally fixed judgment threshold is read. By performing pixel-by-pixel comparison operations on the entire image matrix, a binarized initial image matrix is ​​output. In this process, pixels that meet the threshold condition are marked as foreground pixels, and pixels that do not meet the threshold condition are marked as background pixels; foreground pixels are represented by non-zero values, and background pixels are represented by zero values.

[0037] Furthermore, the calibration method for the preset binarization threshold specifically includes: in the idle mode when the system is started, continuously acquiring N frames of environmental background images, performing time-series data analysis on each pixel, and extracting the time-series mean and standard deviation; calculating the time-series mean and the time-series standard deviation of the grayscale distribution of the entire image; using the time-series mean plus 3 times the time-series standard deviation as the preset binarization threshold to effectively suppress artifacts caused by ambient light fluctuations and sensor dark current noise.

[0038] After binarization, an 8-adjacent connected component labeling algorithm based on depth-first search is used to scan the initial binary image matrix. Each closed connected region consisting of non-zero foreground pixels is assigned an independent ID, and the area feature is obtained by accumulating the total number of pixels under each ID. .

[0039] For example, if the total number of pixels in a certain area is 45 after cumulative statistics, since 45 < 50, the pixel value of this area is reversed and assigned to 0, and then removed; if the total number of pixels in another area is 86, since 86 ≥ 50, this area is retained; artifacts caused by camera shot noise are filtered out by this area filtering rule, and the processed matrix containing the retained area is saved as the preliminary impurity mask layer corresponding to this frequency band component.

[0040] S2. Extract geometric descriptors of suspected regions to screen grains and construct a threshold adjustment model.

[0041] Specifically, geometric screening is performed on the preliminary impurity mask. For the connected regions within each preliminary impurity mask, a combined geometric descriptor of the boundary curvature and morphological compactness of the connected regions is calculated. Based on the preset wheat grain morphology constraints, connected regions that satisfy the constraints are screened out and their geometric descriptors are statistically analyzed. The remaining connected regions are retained to obtain a set of calibration impurity masks. Global statistical moments are calculated based on the geometric descriptors of all removed wheat grain regions, and a threshold adjustment function is constructed accordingly.

[0042] Eight-connected region identification is performed on the non-zero foreground pixels in each preliminary impurity mask to obtain multiple independent connected regions. For each connected region, its external contour point set is extracted, and the boundary curvature parameter, region area and contour perimeter are calculated. The morphological compactness parameter is calculated based on the region area and contour perimeter. The boundary curvature parameter and morphological compactness parameter are combined to obtain the combined geometric descriptor of the corresponding connected region.

[0043] Based on the preset wheat grain morphology constraints, connected regions that satisfy the constraints are screened out and their geometric descriptors are statistically analyzed. The remaining connected regions are retained to obtain a set of calibration impurity masks. Specifically, before determining the wheat grain morphology constraints, several normal wheat grain samples are pre-selected, and the dimensionless boundary curvature parameters are calculated. and shape tightness parameters And respectively, the mean curvature was calculated. Standard deviation of curvature Average firmness and the standard deviation of firmness Based on statistical results, set the constraint range for wheat grain morphology, for example, setting the curvature constraint range to... Set the tightness constraint range to , where a and b are preset tolerance coefficients.

[0044] When a combined geometric descriptor of a connected region Simultaneously satisfy Falling within the curvature constraint range and When the region falls within the compactness constraint range, it is determined that the connected region conforms to the wheat grain morphology constraint. All pixels within this region are assigned a value of 0 to remove it from the initial impurity mask, and the combined geometric descriptor corresponding to the connected region is stored in the statistical sample set. or If any parameter does not fall within the corresponding constraint range, the connected region is determined to not conform to the wheat grain morphology constraint, and its foreground label remains unchanged and is retained; after processing all connected regions, the preliminary impurity masks corresponding to each frequency band component are updated and together constitute a set of calibration impurity masks; the geometric feature parameter distributions of wheat grains and impurities are as follows: Figure 2 As shown.

[0045] After all connected regions in the current image have been processed, the central tendency features and dispersion features are calculated for the boundary curvature parameters and morphological compactness parameters of all removed regions in the statistical sample set, respectively, to obtain global statistical moment feature parameters that characterize the overall morphological distribution of wheat grains. A threshold adjustment function model is then constructed based on the global statistical moment feature parameters.

[0046] In an optional embodiment, for connected regions within each preliminary impurity mask, a combined geometric descriptor of the boundary curvature and morphological compactness of the connected regions is calculated, including: Extract the ordered coordinate point sequence of the outer contour of the connected region, and determine the boundary curvature parameter of the connected region based on the change in the direction of the adjacent connecting lines between the contour points; Based on the area and perimeter of the connected regions, calculate the morphological compactness parameter that characterizes the compactness of the region shape; The boundary curvature parameters and shape compactness parameters are combined in a preset order to generate a combined geometric descriptor for characterizing the comprehensive shape features of the connected region.

[0047] For each independent preserved connected region in the initial impurity mask, the Moore neighbor tracing algorithm is used to extract the outer boundary of the connected region by traversing clockwise, resulting in a series of ordered two-dimensional coordinate digital vector sequences. and ,in The value range is from 1 to n, where n is the total number of contour points.

[0048] Set the step size parameter as follows Two vectors are formed by selecting the center point and contour points three positions before and after the center point. The local angle between the two vectors is obtained by using the dot product of the vectors and the inverse cosine function. ; will the first From the first contour point to the second... The arc length obtained by accumulating the distances between contour points along the contour direction is defined as... And through the formula Calculate the first The local average curvature at each contour point is calculated; the average local average curvature of all points on the contour is then used to obtain the overall boundary curvature parameter of the region; to reduce the influence of image scale and connected region size differences on the curvature parameter, the equivalent radius of the region is calculated based on the area of ​​the connected region, and the boundary curvature parameter is multiplied by the equivalent radius of the region to obtain the dimensionless boundary curvature parameter. .

[0049] By combining the pre-extracted boundary coordinates and using Green's formula to accumulate the number of pixels inside the polygon, the area parameter of the region can be calculated. The perimeter parameter is obtained by summing the Euclidean distances between adjacent contour points. Substitute into the firmness analysis formula The morphological compactness parameter was calculated. .

[0050] In the context of raw wheat grains, the density of healthy, intact, oval-shaped wheat kernels is... The value is usually between 1.2 and 1.5, while that for slender straw or irregular gravel... The value is usually greater than 1.8. The obtained boundary curvature parameter and the morphological compactness parameter are concatenated in a specific order to construct a structure as shown below. A 1×2 dimensional real-valued feature vector is used as a combined geometric descriptor to represent the comprehensive shape characteristics of the current region.

[0051] In an optional embodiment, global statistical moments are calculated based on the geometric descriptors of all removed wheat grain regions, and a threshold adjustment function is constructed accordingly, including: Extract the combined geometric descriptors corresponding to all connected regions that were identified as wheat grains and removed, and statistically analyze the central tendency and dispersion characteristics of the boundary curvature parameters and morphological compactness parameters respectively. The central tendency feature and the dispersion feature are combined to generate global statistical moment feature parameters that characterize the overall morphological distribution of wheat grains. The basic response value is obtained by weighting and summing the global statistical moment feature parameters with preset weight coefficients; The basic response values ​​are nonlinearly normalized to generate the basic segmentation threshold; When the threshold adjustment function is called, the basic segmentation threshold is offset and corrected according to the local spatial parameters corresponding to each input partition to obtain the segmentation threshold of the corresponding partition. The local spatial parameters include the regional mean of the consistency score within the corresponding partition.

[0052] Pre-maintain a size of A buffer queue is used to collect and store combined geometric descriptors of connected regions that have been identified as normal wheat grains and removed after a geometric screening step. This queue is used when the number of regions removed in a single image... Reaching the statistical lower limit, for example When =30, respectively at sequence sum By applying the unbiased estimation formula to the sequence, the expected value of the boundary curvature can be obtained. and sample standard deviation And the expected value of shape tightness. and sample standard deviation When the number of removed regions in a single image does not reach the statistical lower limit, the geometric descriptors of normal wheat grain combinations already stored in the historical buffer queue are used to supplement the data. If the historical buffer queue is still insufficient, the default global statistical moments pre-calculated from the normal wheat grain sample library are used as the input to the threshold adjustment function. A set of parameters calculated is, for example,... =0.52、 =0.08、 =1.35、 =0.12, concatenate this parameter to generate a 1×4 dimension global statistical moment feature vector. The transpose of .

[0053] During the threshold adjustment function construction stage, a preset weight coefficient vector is used. It is the optimal hyperplane weight vector obtained by offline machine learning algorithm using a single-layer neural network model trained on a large wheat grain sample set. The network structure of this single-layer neural network model is a single-layer perceptron structure, containing an input layer and an output layer. The input layer contains four neurons, the output layer contains one neuron, and there are no hidden layers. The input of the single-layer neural network model is an feature vector parameter representing the global statistical moments, which includes the expected value and sample standard deviation of the boundary curvature, and the expected value and sample standard deviation of the morphological compactness. The output of a single-layer neural network model is the basic response value obtained through network calculation.

[0054] Weight coefficient vector For example, -1.2, 0.5, -0.8, 0.6, using feature vector parameters with weight coefficient vector vector inner product The calculated scalar is input into the standard Sigmoid activation function, which nonlinearly maps the output base response value to a probability range of 0 to 1. To accommodate the apparent differences of impurities in different density distribution regions, the threshold adjustment function presets local spatial parameter input terms and offset correction rules. The local spatial parameters are determined in subsequent partitioning processing and are used to generate the offset correction amount when the threshold adjustment function is called. .

[0055] Specifically, let the mean of the consistency score within the corresponding partition be . The preset maximum offset is The offset coefficient corresponding to the densely packed area is The offset coefficient corresponding to the sparse distribution region is ;in, and These are positive coefficients preset and stored in the system parameter table based on experience; when the partition is a densely packed area, the offset correction amount... When the partition is a sparsely distributed region, the offset correction amount .

[0056] Densely packed areas are prone to missed impurities due to mutual occlusion of wheat grains. A negative offset correction is used to lower the segmentation threshold. Furthermore, when the mean consistency score of densely packed areas is low, the negative offset amplitude is increased accordingly to improve the detection sensitivity of weakly responding suspected impurities. Sparsely distributed areas have less background interference, but isolated noise can easily lead to false positives. A positive offset correction is used to increase the segmentation threshold. Furthermore, when the mean consistency score of sparsely distributed areas is high, the positive offset amplitude is increased accordingly to suppress the false alarm risk caused by high-response isolated noise. The generated threshold... Preferably, the threshold after offset correction serves as the discrimination boundary for performing binary classification in this local region. Amplitude limiting is applied to bring it within the range of values ​​in the consistency score map.

[0057] S3. Generate partition thresholds and output impurity detection results.

[0058] Specifically, the gradient magnitude of the wheat grain image is calculated to generate a spatial salience weight map. A set of calibration impurity masks is scale-registered, and the registered calibration impurity masks are then weighted and fused pixel-by-pixel using the spatial salience weight map to generate a consistency score map. Based on the distribution of the foreground region of the wheat grain image, the local structure density is calculated, and the image is divided into densely packed regions and sparsely distributed regions. The regional mean of the consistency score in the densely packed regions and sparsely distributed regions is statistically analyzed as the local spatial parameter of the corresponding region. The global statistical moments and the local spatial parameter are input into a threshold adjustment function to generate the segmentation threshold for each region. Based on the segmentation threshold, the regions are binarized and merged to obtain the impurity detection results.

[0059] The original color image of the grain was converted into a single-channel grayscale image. The Sobel edge operator with a kernel size of 3×3 was applied to obtain the partial derivative matrices of the image in the horizontal and vertical directions. The gradient matrices in the two directions were calculated and merged pixel by pixel using the Euclidean distance algorithm of square root of square, so as to obtain the total gradient magnitude matrix. The maximum and minimum values ​​of this matrix were linearly normalized to the floating-point range of 0 to 1, and used as the spatial salience weight map.

[0060] Before pixel-by-pixel fusion, each calibration impurity mask is upsampled and mapped to coordinates based on the scale relationship between the frequency band component image and the original image, so that it has the same image size and pixel coordinates as the spatial salience weight map. The registered calibration impurity masks are converted into binary matrices with values ​​of 0 or 1. The foreground determination results at the same pixel position are summed and divided by the number of calibration impurity masks to obtain the frequency band consistency ratio. This ratio is then multiplied by the weight value of the corresponding pixel in the spatial salience weight map to obtain a weighted impurity consistency score matrix. This matrix is ​​then converted into a single-channel consistency score map.

[0061] In the local density segmentation stage, the grayscale base image is segmented to obtain a foreground structure map representing the wheat grain and its visible object regions. The proportion of non-background pixels in the foreground structure map is statistically analyzed using a sliding window to obtain a local structure density matrix. The local structure density matrix is ​​compared with a preset density judgment threshold. The coordinate regions that meet the dense judgment conditions are labeled as densely packed area masks, and the coordinate regions that do not meet the dense judgment conditions are labeled as sparsely distributed area masks.

[0062] The mean values ​​of the corresponding consistency scores in the densely packed region and the sparsely distributed region are calculated respectively. These two mean values ​​are used as local spatial parameters of the dense region and the sparse region, respectively. They are substituted into the previously constructed threshold adjustment function to calculate and output the segmentation thresholds for the dense region and the sparse region. Then, based on these two thresholds, the pixels in the densely packed region and the sparsely distributed region are subjected to binarization processing with values ​​greater than the threshold set to 255 and values ​​less than the threshold set to 0. The processed binary images of the dense region and the sparse region are then combined and superimposed to output a complete binary image of the impurity detection result.

[0063] In an optional embodiment, the gradient magnitude of the wheat grain image is calculated to generate a spatial salience weight map, including: By using the sliding operation of the edge detection feature window, the feature gradient components in the horizontal direction and the feature gradient components in the vertical direction of the wheat grain image are extracted respectively. Calculate the gradient magnitude of each pixel using the combined directional gradient characteristics; Extract the maximum gradient magnitude limit index within the entire image region, and perform a proportional division operation on the gradient magnitude at all pixel coordinates to obtain normalized weights; Output normalized weight data in global coordinates and construct a spatial saliency weight map.

[0064] It should be noted that the Scharr operator is used as the sliding window for edge detection features. Horizontal convolutional kernels with parameters of -3, 0, 3, -10, 0, 10, -3, 0, 3 and vertical convolutional kernels with parameters of -3, -10, -3, 0, 0, 0, 3, 10, 3 are loaded into memory. Using a 1-pixel stride and zero-padding for boundary processing, dot-matrix multiplication and accumulation operations are performed row-by-row and column-by-column on the un-downsampled wheat grain base grayscale image to obtain the feature gradient component matrix at the same resolution. and ; Calculate the magnitude matrix containing continuous gradients pixel by pixel using the formula for the square root of the sum of squares. ,at this time The element values ​​in the array are located in the real number range from 0 to 1000.

[0065] In the weight mapping generation step, to avoid the distortion effect caused by isolated noise points on the overall distribution normalization, the entire image is... The values ​​within the matrix are arranged in descending order, with the 99th percentile used as the limiting criterion. For example, calculation It equals 680.5. When performing proportional division, for values ​​greater than... The gradient values ​​are all truncated and assigned values. Then, perform a uniform division on all coordinate points. The linear scaling operation is performed; the element value of each coordinate point in the processed matrix is ​​constrained to the interval between 0 and 1, resulting in a floating-point two-dimensional matrix with the same size as the original image, which is output as a spatial saliency weight map for subsequent weighted calculations.

[0066] In an optional embodiment, a set of calibration impurity masks is scale-registered, and the registered calibration impurity masks are then weighted pixel-wise using a spatial saliency weight map to generate a consistency score map, including: Obtain all calibration impurity masks generated for the corresponding N frequency band components, and upsample and map the coordinates of each calibration impurity mask to the spatial salience weights. Figure 1 In the consistent image coordinate space, feature pixel variables are extracted and retained at the same coordinate points in each mask layer; Combining the weights of the spatial saliency weight map at the corresponding pixel, the foreground determination result of the same pixel position in each calibration impurity mask is multiplied by the spatial saliency weight value corresponding to that pixel position, the resulting products are accumulated, and averaged according to the number of calibration impurity masks participating in the fusion to obtain the impurity consistency score of that pixel position. The consistency scores calculated for each coordinate point are arranged into a two-dimensional structure matrix to generate a consistency score map.

[0067] N identically sized binarized calibration impurity mask layers, generated from single-layer wavelet decomposition (e.g., N=4), are simultaneously loaded for low-frequency and high-frequency components in different directions. Each calibration impurity mask layer is then upsampled and mapped to obtain a registration mask layer with the same size as the spatial saliency weight map. For any coordinate position in the full-map spatial grid, a set of discrete state variables with values ​​of 0 or 1 at the same position across all mask layers is simultaneously extracted using array slicing operations. The real-valued weight factors for the corresponding pixel positions are obtained by looking up a table in the spatial saliency weight map matrix generated in the previous step. .

[0068] It should be noted that during the fusion operation, each mask layer is assigned the same confidence level for its decision state at this coordinate point, but the final contribution value is weighted and modulated by the spatial salience of that point, affecting the performance of the layer below the current location. The total number of impurity triggers is obtained by summing the values, and then multiplied by the spatial prominence weight at that point. The result is normalized by dividing by the total number of layers, N. For example, if all four mask images at a certain pixel are determined to be 1, and the spatial salience weight of that pixel is... If the score is 0.95, then the impurity consistency score S is 0.95; if only two layers are detected and If S equals 0.2, then S equals 0.1; the S values ​​calculated for all pixels are placed according to their original row and column indices to form a floating-point two-dimensional consistency score map matrix with values ​​between 0 and 1.

[0069] In an optional embodiment, local structure density is calculated based on the foreground region distribution of the wheat grain image, thereby dividing the image into densely packed regions and sparsely distributed regions, including: A foreground structure map of wheat grain is generated in the raw grain image, and a sliding window is set in the foreground structure map of the raw grain. The proportion of non-background pixels within the area covered by the sliding window is counted. When the proportion of non-background pixels meets the dense determination condition, the area corresponding to the center of the current window is determined as a densely packed area. When the proportion of non-background pixels does not meet the dense distribution criteria, the area corresponding to the center of the current window is determined as a sparse distribution area.

[0070] Furthermore, the calibration method for the density determination threshold specifically includes: constructing a random stacking filling model based on the average projected diameter of wheat grains and the physical area of ​​the sliding window; setting the physical limit value of the proportion of effective pixels within the window to 0.8; and verifying that when the proportion of effective pixels exceeds 0.8, wheat grains exhibit significant spatial overlap and occlusion effects by conducting imaging tests under different stacking densities in a simulated environment. This is then used as a physical benchmark to establish the density determination threshold.

[0071] Foreground segmentation is performed on the basic grayscale image of wheat grains to obtain a foreground structure map representing the wheat grains, impurities, and other visible grain entities. A square sliding window with a fixed side length of 15×15 pixels is initialized, and this calculation window traverses and scans along the horizontal and vertical dimensions with a step size of 1 pixel. To avoid information truncation at image edges, an auxiliary fill boundary of 7 pixels wide is pre-added around the foreground structure map using a mirror reflection mode. At any time when the sliding window is stationary, foreground determination is performed on the 225 pixels contained in this local area: all pixels marked as non-background within the current window are counted, and the sum of these pixel units is taken as the total number of effective pixels in this local area. .

[0072] After obtaining the total number of valid pixels, substitute this total number of valid pixels into the linear ratio function. The local structural density ratio was obtained. Use a classification threshold of 0.8 for state division: for example, the statistics at the current time are... Equal to 192 valid points, obtained If the value is greater than or equal to 0.8, then the spatial coordinates of the center anchor point of the window are marked as a densely packed area; otherwise, if the number of valid points is 105, If the score is less than 0.8, the center anchor point is classified as a sparse distribution region. The entire pixel space is mapped into a two-state distribution region mask map, which is used to subsequently calculate the regional mean of the consistency score for each region and match the corresponding segmentation threshold. When used, the local structure density fluctuation curve under the sliding window is as follows: Figure 3 As shown.

[0073] The experiment used a dataset containing 5000 images of raw wheat grains, covering various impurity types such as straw and gravel, and included expert-annotated segmentation masks. The experiment was conducted on a workstation equipped with a high-performance graphics card and 64GB of RAM. Three control groups were set up: the baseline group used a fixed global segmentation threshold and averaged the masks across frequency bands; variant group 1, based on the baseline group, utilized a threshold adjustment function based on geometric descriptor statistical moments; and the complete scheme group added a gradient-normalized spatial saliency weight map and a local structure density partitioning module based on the raw grain foreground structure map to variant group 1. The test metrics included impurity detection accuracy, false negative rate, and false positive rate.

[0074] After testing, the baseline group achieved an impurity detection accuracy of 82.5%, a false negative rate of 11.6%, and a false positive rate of 5.9%. Variant group 1, after applying a threshold adjustment mechanism, saw its impurity detection accuracy increase to 88.7%, its false negative rate decrease to 6.8%, and its false positive rate to 4.5%. The complete solution group, after overlaying all feature fusion modules, achieved an impurity detection accuracy of 96.4%, a false negative rate reduced to 2.1%, and a false positive rate of 1.5%.

[0075] The threshold adjustment mechanism utilizes a single-layer neural network to perform global statistical learning on wheat morphological features, which can adapt to changes in the morphological distribution of wheat grains in the current batch to a certain extent and reduce the risk of missed detection caused by a fixed single threshold. The complete scheme, by combining spatial salience weighted fusion with a partitioned threshold mechanism based on the foreground structure density of the raw grain, can improve the detection sensitivity of suspected impurity regions in densely packed areas and suppress some background interference in sparsely distributed areas. Under the experimental conditions, the accuracy of the complete scheme is 13.9% higher than that of the baseline group, indicating that multi-band decomposition, geometric screening, spatial salience weighting, and partitioned threshold mechanisms have a positive effect on improving the stability of raw grain impurity detection.

[0076] This application also discloses a wheat grain impurity detection system, including a processor and a memory. The memory stores computer program instructions, which, when executed by the processor, implement a wheat grain impurity detection method according to this application.

[0077] The system also includes other components well known to those skilled in the art, such as communication buses and communication interfaces, the settings and functions of which are known in the art and will not be described in detail here.

[0078] In the description of this specification, "multiple" or "several" means at least two, such as two, three or more, unless otherwise expressly and specifically defined.

[0079] While this specification has shown and described numerous embodiments of the present application, it will be apparent to those skilled in the art that such embodiments are provided by way of example only. Many modifications, alterations, and alternatives will arise for those skilled in the art without departing from the spirit and intent of the present application. It should be understood that various alternatives to the embodiments of the present application described herein may be employed in the practice of this application.

Claims

1. A method for detecting impurities in raw wheat grains, characterized in that, include: S1. Obtain the image of the wheat grain to be detected, perform multi-band decomposition on the wheat grain image to generate multiple frequency band component images, and generate a set of corresponding preliminary impurity masks based on each frequency band component image. S2. Perform geometric screening on the preliminary impurity mask. For the connected regions within each preliminary impurity mask, calculate the combined geometric descriptor of the boundary curvature and morphological compactness of the connected regions. Based on the preset wheat grain morphology constraints, screen out the connected regions that satisfy the constraints and statistically analyze their geometric descriptors. Retain the remaining connected regions to obtain a set of calibration impurity masks. Calculate the global statistical moments based on the geometric descriptors of all removed wheat grain regions and construct a threshold adjustment function accordingly. S3. Calculate the gradient magnitude of the wheat grain image, generate a spatial saliency weight map, perform scale registration on a set of calibration impurity masks, and combine the spatial saliency weight map to perform pixel-by-pixel weighted fusion of the registered calibration impurity masks to generate a consistency score map. Calculate the local structure density based on the foreground region distribution of the wheat grain image, and divide the image into densely packed regions and sparsely distributed regions accordingly. Calculate the regional mean of the consistency score in the densely packed regions and sparsely distributed regions as the local spatial parameters of the corresponding regions. Input the global statistical moments and local spatial parameters into the threshold adjustment function to generate the segmentation threshold corresponding to each region. Based on the segmentation threshold, complete the region binarization and merge to obtain the impurity detection results.

2. The method according to claim 1, characterized in that, The step of performing multi-band decomposition on the wheat grain image to generate multiple frequency band component images includes: converting the wheat grain image to be detected from the RGB color space to a single-channel mode to generate a two-dimensional grayscale base image. The two-dimensional discrete wavelet parameter executor based on fixed decomposition bandwidth is invoked. Using a row and column calculation window, low-pass and high-pass filters are used to perform matrix convolution and downsampling filtering on the grayscale base image to extract matrix features of different frequency bands. The output wavelet transform generates a low-frequency component image representing the global approximate features, and the extracted horizontal high-frequency component image, vertical high-frequency component image, and diagonal high-frequency component image are aggregated to construct multiple frequency band component images by combining the independent component images in each direction.

3. The method according to claim 2, characterized in that, The step of generating a set of corresponding preliminary impurity masks based on each frequency band component image includes: loading an edge extraction template model on the image data coordinate plane; calculating the edge gradient for each frequency band component image to obtain the corresponding feature gradient magnitude; comparing the feature gradient magnitude of each pixel with a preset binarization threshold, and marking pixels that meet the threshold as foreground pixels and pixels that do not meet the threshold as background pixels, thereby generating an initial binary image matrix; identifying connected regions for the foreground pixels in the initial binary image matrix and counting the number of pixels contained in each connected region to obtain the area of ​​each connected region; filtering each connected region according to a preset area filtering condition, removing connected regions with an area lower than a preset area threshold, and retaining connected regions with an area that meets the preset area threshold condition, thereby generating the corresponding preliminary impurity mask.

4. The method according to claim 1, characterized in that, The combined geometric descriptor for calculating the boundary curvature and shape compactness of connected regions includes: Extract the ordered coordinate point sequence of the outer contour of the connected region, and determine the boundary curvature parameter of the connected region based on the change in the direction of the adjacent connecting lines between the contour points; Based on the area and perimeter of the connected regions, calculate the morphological compactness parameter that characterizes the compactness of the region shape; The boundary curvature parameters and shape compactness parameters are combined in a preset order to generate a combined geometric descriptor for characterizing the comprehensive shape features of the connected region.

5. The method according to claim 1, characterized in that, The construction of the threshold adjustment function includes: extracting the combined geometric descriptors corresponding to all connected regions identified as wheat grains and removed, and statistically analyzing the central tendency and dispersion features of the boundary curvature parameters and morphological compactness parameters; combining the central tendency and dispersion features to generate global statistical moment feature parameters that characterize the overall morphological distribution of the current wheat grains; weighting and summing the global statistical moment feature parameters with preset weight coefficients to obtain the basic response value; performing nonlinear normalization mapping on the basic response value to generate the basic segmentation threshold; and when calling the threshold adjustment function, offsetting and correcting the basic segmentation threshold according to the local spatial parameters corresponding to each input partition to obtain the segmentation threshold of the corresponding partition, wherein the local spatial parameters include the regional mean of the consistency score within the corresponding partition.

6. The method according to claim 5, characterized in that, The step of performing nonlinear normalization mapping on the basic response values ​​to generate basic segmentation thresholds includes: inputting the basic response values ​​into a standard Sigmoid activation function, nonlinearly mapping the basic response values ​​to a probability range of 0 to 1, and generating basic segmentation thresholds.

7. The method according to claim 1, characterized in that, The calculation of the gradient magnitude of the wheat grain image and the generation of a spatial salience weight map include: By using the sliding operation of the edge detection feature window, the feature gradient components in the horizontal direction and the feature gradient components in the vertical direction of the wheat grain image are extracted respectively. Calculate the gradient magnitude of each pixel using the combined directional gradient characteristics; Extract the maximum gradient magnitude limit index within the entire image region, and perform a proportional division operation on the gradient magnitude at all pixel coordinates to obtain normalized weights; Output normalized weight data in global coordinates and construct a spatial saliency weight map.

8. The method according to claim 1, characterized in that, The generation of the consistency score map includes: obtaining all calibration impurity masks generated for the corresponding N frequency band components, upsampling and mapping the coordinates of each calibration impurity mask to the image coordinate space consistent with the spatial salience weight map, and extracting the retained feature pixel variables at the same coordinate points of each mask layer; Combining the weights of the spatial saliency weight map at the corresponding pixel, the foreground determination result of the same pixel position in each calibration impurity mask is multiplied by the spatial saliency weight value corresponding to that pixel position, the resulting products are accumulated, and averaged according to the number of calibration impurity masks participating in the fusion to obtain the impurity consistency score of that pixel position. The consistency scores calculated for each coordinate point are arranged into a two-dimensional structure matrix to generate a consistency score map.

9. The method according to claim 1, characterized in that, The process of dividing the image into densely packed regions and sparsely distributed regions includes: A foreground structure map of wheat grain is generated in the raw grain image, and a sliding window is set in the foreground structure map of the raw grain. The proportion of non-background pixels within the area covered by the sliding window is counted. When the proportion of non-background pixels meets the dense determination condition, the area corresponding to the center of the current window is determined as a densely packed area. When the proportion of non-background pixels does not meet the dense distribution criteria, the area corresponding to the center of the current window is determined as a sparse distribution area.

10. A wheat grain impurity detection system, characterized in that, include: A processor and a memory, the memory storing computer program instructions that, when executed by the processor, implement the method according to any one of claims 1-9.