High-standard detection method and device for food water quality classification
Water sample images were acquired using an industrial camera and a ring-shaped shadowless light source. Combined with HSV transform and Retinex enhancement processing, a lightweight MobileSAM segmentation network was used for multi-channel feature extraction and Fisher discrimination criteria evaluation. This solved the problems of inconsistent and poor adaptability in food water quality detection results, and achieved stable detection and real-time monitoring under different lighting conditions.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- ZHENGZHOU ZHONGDAO BIOTECHNOLOGY CO LTD
- Filing Date
- 2026-03-27
- Publication Date
- 2026-06-26
AI Technical Summary
Existing food water quality testing methods rely on the subjective experience of inspectors, resulting in inconsistent results, difficulty in forming unified standards, inability to accurately identify various anomalies, poor adaptability, inability to be deployed in real time on the production site, and inability to meet the rigid demand for real-time monitoring of the entire food production chain.
Water sample images are acquired using an industrial camera and a ring-shaped shadowless light source. The images are then processed using HSV color space transformation and Retinex enhancement, combined with a lightweight MobileSAM segmentation network for pixel-level segmentation. Multi-channel features are extracted, and a comprehensive evaluation is performed based on the Fisher discrimination criterion and dynamic grading threshold to output the water quality anomaly level.
It achieves consistency and stability of detection results under different lighting conditions, can accurately distinguish various water quality anomalies, adapts to different water sample characteristics, provides early problem detection and comprehensive risk assessment, and supports real-time monitoring of food production.
Smart Images

Figure CN122289770A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of food safety testing technology, and more specifically, to a high-standard testing method and apparatus for food water quality grading. Background Technology
[0002] Current food water quality testing processes heavily rely on the subjective experience and judgment of inspectors. Different personnel often yield significantly different evaluations of the same water sample, making it difficult to establish unified standards. This is particularly pronounced in mass production environments, leading to frequent disputes between internal control standards and external regulatory requirements. Changes in ambient light significantly impact results; judgments obtained in bright laboratory environments differ from those obtained under dimly lit production conditions, resulting in large discrepancies between self-inspection and random sampling results. Existing methods lack the ability to differentiate complex water quality anomalies, failing to accurately identify and locate different types of problems such as turbidity, suspended solids, color abnormalities, and biofilms. Especially when multiple anomalies coexist, they easily overlook potentially high-risk but subtle anomalies. Traditional testing often focuses on single-dimensional indicators, such as color or turbidity alone, lacking a comprehensive analytical framework encompassing multi-dimensional characteristics, leading to frequent blind spots and missed detections. Fixed threshold grading methods lack adaptability to different water sample types and cannot be flexibly adjusted according to the water quality characteristics of different food categories, making it difficult to accurately assess certain special products such as functional beverages. Existing methods neglect the distribution and coverage of anomalous areas, failing to effectively distinguish the risk differences between localized severe pollution and large-scale minor anomalies, leading to biased risk assessments. The comprehensive evaluation mechanism for the synergistic effects of multiple anomalies is inadequate, failing to fully reflect the overall water quality status, particularly evident in seasonal water source changes or sudden pollution events. High-precision water quality analysis algorithms often require specialized equipment, making real-time deployment at the production line difficult, creating a technological gap between high laboratory standards and simple on-site testing. This fails to meet the rigid demand for real-time monitoring across the entire food production chain, ultimately impacting food safety assurance levels.
[0003] In view of this, the present invention proposes a high-standard detection method and apparatus for food water quality grading to solve the above problems. Summary of the Invention
[0004] To overcome the aforementioned deficiencies of the prior art and to achieve the above objectives, the present invention provides the following technical solution: a high-standard detection method for food water quality grading, comprising:
[0005] Macro images of the water sample to be tested are acquired using an industrial camera and a ring-shaped shadowless light source under preset exposure parameters and recorded as the original water sample image.
[0006] The original water sample image was transformed using the HSV color space to separate the hue channel, saturation channel and brightness channel, and multi-scale Retinex enhancement was applied to the brightness channel to generate an enhanced image after illumination correction.
[0007] The enhanced image is input into a pre-trained lightweight MobileSAM segmentation network, which outputs four types of pixel-level segmentation results: turbidity region mask, suspended matter region mask, color abnormality region mask, and biofilm region mask.
[0008] For each type of pixel-level segmentation result covering the image region, features are extracted along three parallel paths: color channel, texture channel, and frequency domain channel, to obtain the color feature vector, texture feature vector, and frequency domain feature vector of the region.
[0009] After standardization and decorrelation processing, the color feature vector, texture feature vector and frequency domain feature vector of each region are concatenated to construct an 18-dimensional anomaly feature vector for each region.
[0010] Based on the historical water sample feature dataset with labeled anomaly levels, the optimal projection direction and dynamic classification threshold group are calculated according to Fisher's discrimination criterion.
[0011] The 18-dimensional anomaly feature vectors of each region are projected along the optimal projection direction to obtain the one-dimensional discrimination score of each region. Based on the dynamic classification threshold group, the discrimination scores of each region are divided into level I, level II, level III or level IV anomaly levels.
[0012] The area-weighted comprehensive evaluation of the anomaly levels of the four segmented regions is performed to determine the final water quality anomaly level of the water sample and output the classification results.
[0013] A high-standard testing device for food water quality grading, which is used to achieve high-standard testing methods for food water quality grading, including:
[0014] The image acquisition unit is used to acquire macro images of the water sample to be tested using an industrial camera and a ring shadowless light source under preset exposure parameters, and these images are recorded as the original water sample images.
[0015] The image enhancement unit is used to perform HSV color space transformation on the original water sample image, separate the hue channel, saturation channel and brightness channel, and apply multi-scale Retinex enhancement processing to the brightness channel to generate an enhanced image after illumination correction.
[0016] The image segmentation unit is used to input the enhanced image into the pre-trained lightweight MobileSAM segmentation network and output four types of pixel-level segmentation results: turbidity region mask, suspended matter region mask, color abnormality region mask, and biofilm region mask.
[0017] The feature extraction unit is used to extract features along three parallel paths—color channel, texture channel, and frequency domain channel—for the image region covered by each type of pixel-level segmentation result, and obtain the color feature sub-vector, texture feature sub-vector, and frequency domain feature vector of the region.
[0018] The feature construction unit is used to concatenate the color feature vector, texture feature vector and frequency domain feature vector of each region after standardization and decorrelation processing to construct the 18-dimensional anomaly feature vector of each region.
[0019] The model training unit is used to calculate the optimal projection direction and dynamic grading threshold group based on the Fisher discrimination criterion and the historical water sample feature dataset with labeled anomaly levels.
[0020] The hierarchical discrimination unit is used to project the 18-dimensional abnormal feature vector of each region along the optimal projection direction to obtain the one-dimensional discrimination score of each region. According to the dynamic hierarchical threshold group, the discrimination score of each region is divided into level I, level II, level III or level IV abnormality level.
[0021] The comprehensive evaluation unit is used to perform area-weighted comprehensive evaluation of the anomaly levels of the four types of segmented areas, determine the final water quality anomaly level of the water sample, and output the classification results.
[0022] The various units are connected via wired and / or wireless means to enable data transmission between units.
[0023] The technical effects and advantages of the high-standard detection method and device for food water quality grading of this invention are as follows:
[0024] This invention maintains stable and reliable test results under various complex lighting conditions, obtaining consistent evaluation results in both brightly lit laboratories and production workshops with complex lighting, greatly improving the applicability and universality of the test. It can comprehensively capture various manifestations of water quality anomalies, accurately distinguish and locate multiple coexisting water quality problems, avoiding safety hazards easily overlooked by traditional methods, and providing multiple safeguards for food safety. The adaptive grading mechanism can intelligently respond to the differences in characteristics of various water samples, providing reasonable rating results for both ordinary drinking water and special functional beverages, significantly expanding its application scope. This invention's sensitive capture capability of minute anomalies enables early detection and warning of problems, allowing enterprises to take intervention measures at the initial stage of quality deterioration and avoid large-scale losses. By comprehensively considering the severity and scope of anomalies, this invention provides a more comprehensive risk assessment, providing a scientific basis for production decisions and reducing over- or under-treatment caused by subjective judgment. Attached Figure Description
[0025] Figure 1 This is a schematic diagram of the high-standard detection method for food water quality grading of the present invention;
[0026] Figure 2 This is a schematic diagram of the high-standard food water quality grading testing device of the present invention. Detailed Implementation
[0027] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0028] This application example provides a high-standard testing method and apparatus for water quality grading in food. Please refer to [link / reference]. Figure 1 In this embodiment of the invention, the specific implementation process of the high-standard detection method for food water quality grading includes:
[0029] Macro images of the water sample are acquired using an industrial camera and a ring-shaped shadowless light source under preset exposure parameters, and these images are recorded as the original water sample images. This step utilizes a combination of a high-precision industrial camera and a professional ring-shaped shadowless light source to ensure standardized and consistent image acquisition. The industrial camera is typically equipped with a high-resolution sensor (at least 8 megapixels) and a macro lens (5-10x magnification), capable of clearly capturing minute particles and color variations in the water sample. The ring-shaped shadowless light source provides 360-degree uniform illumination, eliminating shadow interference and ensuring image quality. Preset exposure parameters include exposure time (typically 10-50 milliseconds), aperture size (typically F8-F11), and ISO sensitivity (typically set to 100-400). These parameters are pre-calibrated according to the water sample type to ensure comparability between different batches of images. During acquisition, the water sample is placed in a standard cuvette and fixed on a precision positioning platform to ensure consistency in the acquisition angle and distance, thereby obtaining high-quality original water sample images.
[0030] The original water sample image underwent HSV color space transformation to separate the hue, saturation, and brightness channels. Multi-scale Retinex enhancement was then applied to the brightness channel to generate an enhanced image after illumination correction. Color space transformation is a fundamental step in extracting water quality characteristics from food samples. Compared to RGB space, HSV space is closer to human perception, facilitating the separation of color and brightness information. The transformation process employed a standard RGB-to-HSV conversion algorithm, mapping each pixel of the original image from an RGB 3D vector to an HSV 3D vector. The hue channel (H) reflects the basic color characteristics of the water sample, the saturation channel (S) reflects the purity or intensity of the color, and the brightness channel (V) reflects the overall lightness and darkness. Multi-scale Retinex enhancement of the brightness channel effectively eliminates the effects of uneven illumination, enhances subtle details, and improves the accuracy of subsequent analysis. The enhanced image retains the true color information of the original water sample while exhibiting a more balanced brightness distribution and clearer detail, providing a high-quality image foundation for subsequent region segmentation and feature extraction.
[0031] The enhanced image is input into a pre-trained lightweight MobileSAM segmentation network, which outputs pixel-level segmentation results for four categories: turbidity region masks, suspended matter region masks, color anomaly region masks, and biofilm region masks. Image segmentation is a crucial step in locating abnormal areas in food and water quality, and this network achieves pixel-level accurate classification through deep learning. The MobileSAM segmentation network is a lightweight variant of SAM (Segment Anything Model), retaining the powerful segmentation capabilities of the original SAM while significantly reducing computational resource requirements, making it suitable for embedded deployment. Trained on a dedicated dataset of abnormal food and water quality samples, the network accurately identifies four typical abnormal features: turbidity regions appear as generally hazy areas; suspended matter regions appear as discrete floating particles or flocculent matter; color anomaly regions appear as areas significantly deviating from normal water color; and biofilm regions appear as semi-transparent thin film structures attached to the surface. The network outputs four binary mask images, where pixels with a value of 1 represent the corresponding category of abnormal region, and pixels with a value of 0 represent the background region. These masks precisely define the spatial distribution of various anomalies, providing accurate region localization for subsequent feature extraction.
[0032] For each pixel-level segmentation result covering the image region, features are extracted along three parallel paths: color channel, texture channel, and frequency domain channel, obtaining the color feature vector, texture feature vector, and frequency domain feature vector for that region. Multi-channel feature extraction is a crucial step in comprehensively characterizing the abnormal characteristics of food water quality, capturing the complete features of the anomaly from three complementary perspectives. The color channel extracts the optical density, hue, and saturation features of the water sample, reflecting the degree of color deviation in the abnormal region; the texture channel analyzes the structural complexity and directionality of the abnormal region through wavelet decomposition, reflecting surface texture features; and the frequency domain channel analyzes the frequency distribution characteristics of the abnormal region through Fourier transform, reflecting edge sharpness and detail richness. Each of these three parallel paths extracts a six-dimensional feature vector, quantifying the abnormal features from different angles, and together constructing a comprehensive anomaly descriptor. The design of multi-channel feature extraction fully considers the diverse manifestations of food water quality anomalies, ensuring that the system can accurately identify various types of food water quality problems, whether it be color changes, structural anomalies, or deviations in edge features, all can be accurately captured and quantified.
[0033] The color feature vectors, texture feature vectors, and frequency domain feature vectors of each region are standardized and decorrelated before being concatenated to construct an 18-dimensional anomaly feature vector for each region. Feature integration is a key step in integrating multi-channel information. Standardization and decorrelation ensure the consistency and non-redundancy of the feature space. The standardization process is based on the statistical distribution of historical water sample datasets, mapping each dimension of features to a standard normal distribution with a mean of 0 and a standard deviation of 1, eliminating dimensional differences and scale effects. Decorrelation analysis identifies and processes highly correlated redundant dimensions by analyzing the correlation matrix between features, ensuring efficient representation of the feature space. The final 18-dimensional anomaly feature vector is a highly condensed mathematical representation, with each dimension capturing a unique aspect of food water quality anomalies, collectively forming the complete feature basis for anomaly discrimination. The design of this feature vector considers the balance between computational efficiency and expressive power, preserving the key features of anomalies while controlling the complexity of dimensions, providing ideal feature input for subsequent discriminant analysis.
[0034] Based on a historical water sample feature dataset with labeled anomaly levels, the optimal projection direction and dynamic grading threshold set are calculated according to the Fisher discriminant criterion. Fisher discriminant analysis is a classic method for achieving feature dimensionality reduction and optimized class separation. It maximizes inter-class distance and minimizes intra-class distance by finding the optimal projection direction. This step utilizes a large amount of labeled historical water sample data, including a complete sample set from Level I (minor anomaly) to Level IV (severe anomaly), to establish a discriminant model for anomaly levels. The calculation process first constructs the intra-class and inter-class scatter matrices, and then solves the generalized eigenvalue problem to obtain the projection direction vector that best distinguishes different levels. Based on this direction, the distribution of samples of each level in the projection space is calculated, and the optimal split point is determined as the dynamic grading threshold. This data-driven threshold determination method can adapt to different water sample types and detection environments, avoids the limitations of fixed thresholds, and improves the adaptability and accuracy of grading.
[0035] The 18-dimensional anomaly feature vectors of each region are projected along the optimal projection direction to obtain a one-dimensional discrimination score for each region. Based on a dynamic grading threshold group, the discrimination scores of each region are classified into anomaly levels I, II, III, or IV. Feature projection is a key step in mapping high-dimensional features to an easily discriminative one-dimensional space, achieving dimensionality reduction of complex features through inner product operations. The projection process calculates the inner product between the 18-dimensional anomaly feature vector and the optimal projection direction vector to obtain a one-dimensional score that comprehensively reflects the degree of anomaly. Higher scores generally indicate more severe anomalies, while lower scores indicate milder anomalies. The projection calculation formula is:
[0036] ;
[0037] in, The discriminant score after projection. It is an 18-dimensional anomaly feature vector. This is the optimal projection direction vector. This represents the vector dot product operation.
[0038] Based on the comparison between the score and the dynamic grading threshold group, the system classifies the anomaly level of each region into four levels: Level I indicates minor anomalies that have little impact on usability; Level II indicates moderate anomalies that require attention; Level III indicates significant anomalies that require action; and Level IV indicates severe anomalies that are not suitable for use. This grading method based on projected scores transforms complex multidimensional features into intuitive level judgments, facilitating final decision-making and processing.
[0039] An area-weighted comprehensive evaluation is performed on the anomaly levels of the four types of segmented regions to determine the final water quality anomaly level of the water sample and output the classification result. Area-weighted comprehensive evaluation is the final step in integrating anomaly information from multiple regions. By considering the spatial extent of the anomaly regions, a more reasonable overall assessment is achieved. The evaluation process first calculates the area proportion of the four types of anomaly regions in the entire image as weight coefficients; then, the anomaly level of each region is multiplied by its corresponding weight and summed to obtain a preliminary weighted score; finally, adjustments are made according to specific rules, considering the concentration and distribution characteristics of the anomalies, to output the final water quality anomaly level. This comprehensive evaluation method considers both the severity and coverage of the anomalies, providing a more comprehensive reflection of the actual state of food-grade water quality and avoiding the one-sided judgments that may result from a single indicator, thus providing reliable technical support for food-grade water quality safety decisions.
[0040] In this embodiment of the invention, multi-scale Retinex enhancement processing is applied to the luminance channel to generate an enhanced image after illumination correction, including:
[0041] Each at a small scale Mesoscale With large scale Three Gaussian kernels are convolved into the luminance channel to obtain illuminance estimates at three scales. Multi-scale processing is the core idea of Retinex theory, simulating the perceptual characteristics of the human visual system at different scales through Gaussian filtering at different scales. This step selects three typical scales: small scale... (Typically set to 5-15 pixels) to preserve fine details, medium scale (Typically set to 30-50 pixels) to preserve medium-sized structures at large scale. (Typically set to 80-120 pixels) is used to estimate overall illumination. Gaussian kernel convolution is a two-dimensional spatial filtering operation that smooths the image by weighted averaging of neighboring pixel values. The Gaussian convolution formula is:
[0042] ;
[0043] in, For the Gaussian kernel in position The weight value at that location, The standard deviation of the Gaussian kernel determines the degree of smoothing.
[0044] The convolution operation is achieved by sliding the filter kernel across the image and weighted summation. The resulting illuminance estimation map reflects the illumination distribution at different scales, providing a foundation for subsequent reflection component extraction. The multi-scale design can address both local detail and global illumination correction needs, improving the naturalness and visual quality of the enhancement effect.
[0045] The Retinex reflectance components at three scales are obtained by taking the logarithm of the luminance channel and subtracting it from the illuminance estimation map at each scale. Reflectance component extraction is a key step in Retinex theory, based on the physical model that image luminance is the product of reflectivity and illumination. According to the addition separation principle in the logarithmic domain, the difference operation after taking the logarithm can effectively separate the reflectance and illumination components. Specifically, the natural logarithm of the luminance channel and the illuminance estimation map are taken respectively, and then the difference is calculated to obtain the reflectance component. The formula for calculating the reflectance component is:
[0046] ;
[0047] in, For the first Reflection components at each scale, This is the original luminance channel. For the first Illuminance estimation map at each scale, This is the operation for the natural logarithm.
[0048] The reflection component represents the inherent reflective properties of an object's surface. Ideally, it is unaffected by lighting conditions and better reflects the true characteristics of the water sample. The three reflection components at different scales each retain the structural details at their specific scales, collectively forming the basis of multi-scale enhancement.
[0049] The Retinex reflectance components at three scales are weighted and fused according to preset weight coefficients to obtain the fused reflectance component. Multi-scale fusion is a key step in balancing the contributions of each scale, integrating the advantages of different scales through appropriate weight allocation. The fusion process employs a linear weighting strategy, assigning weight coefficients to the reflectance components at the three scales and then calculating the weighted sum. The weight coefficients are typically preset based on the application scenario and image characteristics, with smaller scales receiving higher weights. (Typically 0.3-0.4), mesoscale weights (Typically 0.4-0.5), large-scale weights (Usually 0.1-0.2), and satisfies The formula for calculating the fused reflection component is:
[0050] ;
[0051] in, To fuse the reflection components, , , These are reflection components at three different scales. , , These are the corresponding weighting coefficients.
[0052] The fused reflection component integrates structural information at various scales, preserving detail clarity while maintaining global brightness balance, thus providing a base image for subsequent dynamic range adjustment.
[0053] The fused reflection component is truncated at the upper and lower percentiles and linearly stretched to map pixel values to a preset dynamic range, thus obtaining the corrected luminance channel. Dynamic range adjustment is a crucial step in ensuring image visual quality, optimizing pixel value distribution through nonlinear transformation. The process first calculates the histogram of pixel value distribution of the fused reflection component, determining the upper and lower percentile points (usually 1% and 99%), truncating extreme values to reduce the impact of noise and outliers; then, through linear mapping, the truncated reflection component is stretched to a preset dynamic range (usually [0, 255]) to enhance contrast and visual effect. This percentile-based adaptive adjustment method can flexibly adjust the mapping range according to the characteristics of the specific image, avoiding detail loss or over-enhancement that may result from a fixed threshold, ensuring the visual naturalness and information integrity of the enhancement result.
[0054] The corrected luminance channel is merged with the original hue and saturation channels, and then an enhanced image is generated through an inverse HSV-to-RGB transformation. Color space reconstruction is the final step in image enhancement, achieving a natural visual effect by preserving the original color information and combining it with enhanced luminance. The reconstruction process first recombines the corrected luminance channel with the unchanged hue and saturation channels to form an enhanced HSV image; then, a standard HSV-to-RGB conversion algorithm maps the image back to the RGB color space, generating the final enhanced image. This strategy of enhancing only the luminance channel while preserving color information avoids the color cast problem that may occur in common enhancement algorithms, ensuring the color reproduction and visual naturalness of the enhanced image, while significantly improving detail visibility and contrast, providing a high-quality image foundation for subsequent region segmentation and feature extraction.
[0055] In this embodiment of the invention, a lightweight MobileSAM segmentation network pre-trained with enhanced image input is used to output four types of pixel-level segmentation results, including:
[0056] The enhanced image is scaled to the standard input size of the MobileSAM segmentation network, and multi-level feature maps are extracted using a lightweight image encoder. Image preprocessing and feature extraction are fundamental steps in deep learning segmentation. Standardized input and multi-level feature extraction ensure segmentation accuracy. The preprocessing process uses bilinear interpolation to scale the enhanced image to the network's standard input size (typically 1024×1024 pixels), maintaining the aspect ratio while ensuring the pixel count meets network requirements. The lightweight image encoder is based on the MobileViT architecture, employing a structure combining depthwise separable convolution and attention mechanisms, significantly reducing computational complexity while preserving feature representation capabilities. The encoder progressively extracts multi-level features from low-level texture to high-level semantics through multi-level convolution and downsampling operations, forming a feature pyramid structure. This multi-level feature representation can simultaneously capture both local details and global structure of the water sample, providing rich feature information for subsequent accurate segmentation, and is particularly suitable for handling complex targets such as food water quality anomalies that possess both fine texture and overall morphological features.
[0057] Based on the prior spatial distribution of water quality anomaly regions, a uniformly distributed set of gridded cue points is generated within the effective image area. Cue point generation is a crucial step in guiding segmentation, using prior knowledge to direct the network to focus on potential anomaly regions. The generation process is based on statistical analysis of the spatial distribution patterns of water quality anomalies, revealing specific locational preferences for different types of anomalies: turbidity is typically globally distributed, suspended matter is mostly found in the upper and middle regions, color anomalies are common in edge regions, and biofilms are mostly found on the surface. Based on these prior distribution characteristics, the system generates a gridded set of cue points within the effective image area (usually the interior of a cuvette). The grid density is dynamically adjusted according to the image resolution, typically a uniform grid of 20×20 or 32×32. This cue point design based on prior knowledge significantly improves the targeting and efficiency of segmentation, enabling the network to quickly locate potential anomaly regions and reducing computational resource waste, making it particularly suitable for real-time detection applications.
[0058] The gridded cue point set and multi-level feature maps are fed into the mask decoder, which outputs candidate segmentation masks and their confidence scores for each cue point. Mask generation is the core step in the segmentation task, converting feature maps and cue point information into accurate segmentation results through the decoder network. MobileSAM's mask decoder adopts a lightweight Transformer structure, integrating global contextual information and local detail features through an attention mechanism. The decoding process first locates the gridded cue points in the feature space and extracts the corresponding feature vectors; then, a self-attention mechanism is used to capture long-range dependencies between features; finally, a multi-level cross-attention module fuses the cue point information with the feature map to generate candidate segmentation masks for each cue point. Each candidate mask also outputs a confidence score, reflecting the reliability of the segmentation result. This Transformer-based decoding architecture has strong semantic understanding capabilities, effectively distinguishing different types of food and water quality anomalies, and can accurately segment even visually similar objects using contextual information.
[0059] Candidate segmentation masks are sorted in descending order of confidence score, and non-maximum suppression (NMS) is applied sequentially to remove redundant masks with an IoU exceeding a preset overlap threshold. Mask selection is a crucial step in eliminating redundant results, removing excess segmentation results by comparing the overlap between masks. The selection process first sorts all candidate masks in descending order of confidence score, prioritizing the retention of masks with high confidence. Then, the crossover ratio (IoU) between masks is compared sequentially using the non-maximum suppression (NMS) algorithm. When the IoU of two masks exceeds a preset overlap threshold (usually set to 0.5-0.7), the mask with higher confidence is retained, while the mask with lower confidence is suppressed. The crossover ratio calculation formula is:
[0060] ;
[0061] in, For mask and The intersection and union ratio, This represents the number of pixels in the overlapping area of the two masks. This represents the number of pixels in the merged region of the two masks.
[0062] This IoU-based redundancy elimination strategy effectively avoids the problem of multiple cue points producing similar segmentation results, ensuring the simplicity and non-redundancy of the final segmentation result, while retaining all meaningful anomalous regions.
[0063] For the retained candidate segmentation masks, the mean features of the covered area in the hue and saturation channels of each mask are extracted. Based on preset classification rules, each mask is categorized into turbidity, suspended matter, color anomaly, or biofilm regions. Mask classification is a crucial step in determining the anomaly type, distinguishing different categories of food water quality anomalies through color feature analysis. The classification process first extracts the mean features of the covered area in the HSV hue and saturation channels for each retained mask; then, based on preset classification rules, the mask is assigned to the corresponding anomaly category. The discrimination rules are constructed based on statistical analysis of a large amount of water sample data, typically combining multiple feature dimensions such as hue mean, hue standard deviation, and saturation mean to form the classification decision boundary. The four types of food water quality anomalies exhibit obvious clustering characteristics in the feature space: turbidity regions typically show low saturation and moderate hue difference; suspended matter regions show high local contrast and irregular edges; color anomaly regions show hue values that significantly deviate from the background; and biofilm regions show a semi-transparent structure and unique texture features. This classification strategy, based on color features and prior knowledge, can effectively distinguish visually similar but fundamentally different types of food water quality anomalies, providing accurate regional classification for subsequent feature analysis.
[0064] In this embodiment of the invention, features are extracted along the color channel to obtain the color feature sub-vector of the region, including:
[0065] In the enhanced image, a background region not covered by any segmentation mask is selected, and its average brightness value is calculated and recorded as the reference background brightness. Establishing a background baseline is the first step in color feature extraction, achieved by identifying normal water sample areas. The selection process employs a mask inversion operation: all abnormal masks are merged and inverted to obtain the background region mask. Then, multiple sampling regions (typically 100-200 small 10×10 pixel regions) are randomly selected within the background region, and the average brightness value of these regions is calculated to obtain the reference background brightness. To improve the reliability of the baseline, the system removes sampling regions with abnormal brightness values (usually using the 3σ principle) to ensure that the final reference brightness reflects the standard state of normal water samples. The selection of the background region considers the balance of spatial distribution, ensuring that sampling points cover different parts of the image and avoiding interference from local illumination variations or edge effects. Accurate reference background brightness provides a reliable comparison benchmark for subsequent optical density calculations and is a key prerequisite for quantitatively analyzing the degree of abnormality in food water quality.
[0066] The optical density value of each pixel within the segmented region is obtained by taking the negative logarithmic ratio of its brightness value to the reference background brightness value. Optical density calculation is a crucial step in converting visual features into physical quantities, based on the Beer-Lambert law of light absorption theory. The calculation process uses the negative logarithmic ratio formula to convert the ratio of pixel brightness value to reference brightness into an optical density value, which directly reflects the water sample's ability to absorb or scatter light. The optical density calculation formula is as follows:
[0067] ;
[0068] in, For position Optical density value at that location This represents the brightness value at that location. Used as a reference for background brightness.
[0069] Optical density values provide a scientific basis for quantitatively characterizing the transparency and turbidity of food-grade water. Higher values indicate stronger light absorption, typically corresponding to more severe food-grade water quality anomalies. This feature extraction method, based on physical principles, transforms visual observation into measurable physical quantities, improving the interpretability and accuracy of features and providing a reliable numerical foundation for subsequent anomaly rating.
[0070] The mean and standard deviation of optical density values within a given region are denoted as the mean characteristic and the dispersion characteristic of optical density, respectively. Optical density statistics are a crucial step in quantifying the degree and uniformity of anomalies, comprehensively describing regional characteristics through the mean and standard deviation. The statistical process first calculates the arithmetic mean of the optical density of all pixels within the region, serving as the mean characteristic, directly reflecting the overall severity of the anomaly. Then, the standard deviation is calculated as the dispersion characteristic, reflecting the spatial uniformity and degree of variation of the anomaly. A higher mean generally indicates a more severe anomaly, while a larger standard deviation indicates a more uneven distribution of the anomaly. These two characteristics complement each other, together forming a comprehensive description of the anomaly degree, considering both the overall level and internal variations, effectively distinguishing different types and degrees of food and water quality problems. For example, turbidity problems typically exhibit a high mean and low standard deviation, while suspended matter may exhibit a medium mean and high standard deviation; this difference provides an important basis for anomaly classification.
[0071] The mean and kurtosis of pixel values in the hue channel of this region are extracted and denoted as the hue mean feature and hue kurtosis feature, respectively. Hue feature extraction is a key step in analyzing the color characteristics of water samples, comprehensively capturing color distribution characteristics through mean and kurtosis. The extraction process first calculates the average value of all pixels in the HSV hue channel (H) within the region as the hue mean feature, reflecting the basic color characteristics of the water sample; then, the kurtosis is calculated as the hue kurtosis feature, reflecting the sharpness of the hue distribution and the occurrence of outliers. The hue mean is directly related to the color category of the water sample, such as yellowish, greenish, or bluish tints, and is an important clue for identifying chemical pollution or microbial growth; kurtosis reflects the concentration of color distribution and the presence of special values. High kurtosis usually indicates concentrated color distribution and the existence of areas with prominent anomalies, which is indicative in the detection of certain specific pollutants. These two features together construct a mathematical representation of the color characteristics of the water sample, providing important information in the color dimension for anomaly identification.
[0072] The mean and skewness of pixel values within the saturation channel of this region are extracted, denoted as the saturation mean feature and saturation skewness feature, respectively. Saturation feature extraction is a crucial step in analyzing color purity and intensity, comprehensively capturing color vividness characteristics through mean and skewness. The extraction process first calculates the average value of all pixels within the region in the HSV saturation channel (S), serving as the saturation mean feature, reflecting color purity and intensity; then, the skewness is calculated as the saturation skewness feature, reflecting the asymmetry of saturation distribution. The saturation mean is directly related to the vividness of the water sample color; pure water typically has low saturation, while water samples containing organic matter or chemical pollution often have high saturation. Skewness reflects the bias in the saturation distribution; positive skewness indicates a tendency for the distribution to tail towards higher saturation, which is particularly significant in the detection of certain mixed pollution. These two features together construct a mathematical representation of the water sample's color intensity characteristics, providing crucial information on the color purity dimension for anomaly detection.
[0073] The optical density mean, optical density dispersion, hue mean, hue kurtosis, saturation mean, and saturation skewness features are combined into a six-dimensional color feature sub-vector. Feature combination is the final step in integrating multi-dimensional color information, constructing a unified color feature descriptor through vectorization. The combination process arranges the six independent feature values in a fixed order to form a six-dimensional feature vector, which fully describes the color characteristics of the water sample area. These six dimensions describe the color characteristics of the water sample from three aspects: optical density, hue, and saturation, respectively, considering both physical characteristics (optical density) and perceptual characteristics (hue and saturation), forming a complementary and comprehensive description. The color feature sub-vector provides the first set of key features for subsequent anomaly detection, and is particularly suitable for identifying food water quality problems related to color changes, such as chemical contamination, microbial contamination, and organic contamination. It is an indispensable and important indicator in food water quality rating.
[0074] In this embodiment of the invention, features are extracted along the texture channel to obtain the texture feature sub-vector of the region, including:
[0075] A two-dimensional discrete wavelet transform is performed on the brightness image corresponding to the segmented region, decomposing it to a preset number of layers L to obtain the wavelet coefficient matrices of the horizontal, vertical, and diagonal detail subbands at each layer. Wavelet decomposition is a fundamental step in multi-scale texture analysis, capturing structural features at different scales through hierarchical decomposition. The decomposition process uses the two-dimensional discrete wavelet transform (DWT) algorithm, selecting the Daubechies wavelet basis (usually db4 or db6) as the transform basis function to perform multi-level decomposition of the brightness image. The preset number of layers L is usually set to 3-5 layers, dynamically adjusted according to the image size and texture complexity. Each decomposition layer generates a low-frequency approximate subband and three high-frequency detail subbands (horizontal, vertical, and diagonal directions), recording detailed texture information at the corresponding scale. The horizontal detail subband reflects the vertical edge information in the image, the vertical detail subband reflects the horizontal edge information, and the diagonal detail subband reflects the edge information in the diagonal direction. These three detail subbands together constitute a complete texture description, capable of capturing various structural features in the water sample, such as suspended particle edges, biofilm textures, and turbidity distribution patterns.
[0076] The sum of squared coefficients is calculated for the wavelet coefficient matrices of the three detail subbands in each layer to obtain the energy value of each subband. Subband energy calculation is a key step in quantifying texture intensity, using the sum of squared coefficients to measure the richness of texture at a specific direction and scale. The calculation process involves squaring all coefficients in the wavelet coefficient matrix of each detail subband and then summing them to obtain the energy value of that subband. The energy value calculation formula is:
[0077] ;
[0078] in, For the first layer Energy value of the directional subband For the corresponding wavelet coefficient matrix at position The coefficient value at that location, Indicates direction (horizontal, vertical, or diagonal).
[0079] Subband energy directly reflects the texture intensity at a specific scale and direction; a higher value indicates richer texture features at the corresponding scale and direction. This energy-based texture quantification method can effectively capture the texture features of different types of anomalies in water samples. For example, suspended matter usually has high energy in detail subbands at multiple scales, while uniform turbidity is mainly manifested in detail subbands at larger scales. This difference provides an important basis for anomaly classification.
[0080] The layer with the highest total energy in three sub-bands is selected, and the energy values of the horizontal, vertical, and diagonal sub-bands of that layer are extracted and denoted as the principal-scale horizontal texture energy, principal-scale vertical texture energy, and principal-scale diagonal texture energy, respectively. Principal-scale selection is a crucial step in determining the key texture scale, identifying the most representative decomposition layer based on the principle of maximum energy. The selection process first calculates the sum of the energies of the three detail sub-bands in each layer, then compares the total energies of each layer, and selects the layer with the highest energy as the principal scale. The principal scale typically corresponds to the main characteristic scale of the water sample texture and can most effectively capture anomalous features. Sub-band energies in the horizontal, vertical, and diagonal directions are extracted from the principal-scale layer, and the texture intensity in each direction is quantified. These three features together construct a directional description of the main texture of the water sample, effectively distinguishing different types of food water quality anomalies. For example, suspended matter typically exhibits high energy in all three directions, while certain types of biofilms may have higher energy in specific directions; this directional difference provides important clues for fine classification.
[0081] The decay rate sequence of the total energy of the three subbands between adjacent decomposition layers is calculated, and the maximum value in the decay rate sequence is extracted and denoted as the texture roughness feature. Attenuation rate analysis is a crucial step in evaluating texture scale characteristics, determining the roughness of the texture through energy decay patterns. The analysis process first calculates the ratio of the total energy between every two adjacent layers, forming a decay rate sequence; then, the maximum value is extracted from the sequence as the texture roughness feature. The texture roughness feature reflects the rate of change of texture from fine to coarse scales; a higher value indicates a more drastic change in texture scale, typically corresponding to a coarser texture structure. This feature can effectively distinguish between fine and coarse textures and is an important indicator for identifying different types of food water quality anomalies. For example, fine suspended matter typically exhibits a higher roughness value, while uniform turbidity exhibits a lower roughness value; this difference provides important information on the scale dimension for anomaly type identification.
[0082] The ratio of the energy of the horizontal detail subband to the energy of the vertical detail subband in the finest-scale layer is calculated and denoted as the texture directionality feature. Directional analysis is a key step in quantifying the dominant direction of texture, and the directional preference of texture is determined by the energy ratio. The calculation process selects the finest-scale layer (usually the first layer decomposition) and calculates the ratio of the energy of the horizontal detail subband to the energy of the vertical detail subband as the texture directionality feature. A ratio greater than 1 indicates that the vertical texture is more significant, a ratio less than 1 indicates that the horizontal texture is more significant, and a ratio close to 1 indicates a balanced directional distribution. The finest-scale layer typically retains the most detailed edge and texture information, and its directional distribution can most sensitively reflect the directional characteristics of the texture. This feature is of great value in identifying certain types of food and water quality anomalies; for example, some biofilm structures have obvious directionality, while uniformly distributed suspended matter exhibits a balanced directional characteristic.
[0083] The principal-scale horizontal texture energy, principal-scale vertical texture energy, principal-scale diagonal texture energy, texture roughness features, texture directionality features, and total energy value of the entire layer are combined into a six-dimensional texture feature sub-vector. Feature combination is the final step in integrating multi-dimensional texture information, constructing a unified texture feature descriptor through vectorization. The combination process arranges six independent feature values in a fixed order to form a six-dimensional feature vector, which fully describes the texture characteristics of the water sample region. These six dimensions describe the texture structure of the water sample from three aspects: directionality, scale characteristics, and overall intensity. They consider both the energy distribution of the main texture directions and the scale characteristics and overall intensity of the texture, forming a comprehensive and complementary description. The texture feature sub-vector provides a second set of key features for subsequent anomaly detection, and is particularly suitable for identifying food water quality problems related to structural changes, such as suspended solids, flocculent matter, and biofilms. It is an indispensable and important indicator in food water quality rating.
[0084] In this embodiment of the invention, features are extracted along the frequency domain channel to obtain the frequency domain feature sub-vector of the region, including:
[0085] A two-dimensional discrete Fourier transform (DFT) is performed on the brightness image corresponding to the segmented region to obtain the frequency domain amplitude spectrum, and the zero frequency is shifted to the center of the spectrum. Frequency domain transformation is a fundamental step in analyzing the frequency characteristics of an image, converting spatial information into a frequency distribution through Fourier transform. The transformation process employs the two-dimensional discrete Fourier transform (DFT) algorithm, typically implemented efficiently using the fast Fourier transform (FFT), transforming the brightness image from the spatial domain to the frequency domain. The complex result obtained after the transformation yields an amplitude spectrum by calculating its modulus, reflecting the intensity distribution of each frequency component. To facilitate analysis and visualization, the amplitude spectrum is shifted to zero frequency, moving the DC component (zero frequency point) to the center of the spectrum, while high-frequency components are distributed on the periphery. This spectral representation is more in line with human visual habits and facilitates subsequent annular region segmentation and analysis. Frequency domain analysis can reveal frequency patterns and periodic structures in images that are difficult to observe directly in the spatial domain, providing a new analytical perspective for detecting subtle textures and regular anomalies in water samples, and serving as an important supplement to spatial domain analysis.
[0086] Using the spectral center as the center, the frequency domain amplitude spectrum is divided into three concentric ring regions—a low-frequency ring, a mid-frequency ring, and a high-frequency ring—according to a preset radius ratio. Frequency band division is a crucial step in separating different frequency components, achieving hierarchical frequency analysis through concentric ring partitioning. The division process uses the zero-frequency point (spectral center) as the center, dividing concentric ring regions according to a preset radius ratio: the low-frequency ring typically covers 0-10% of the radius around the spectral center, corresponding to the overall structure and low-frequency variations in the image; the mid-frequency ring covers 10-40% of the radius, corresponding to medium-scale structures and textures; and the high-frequency ring covers 40-100% of the radius, corresponding to fine edges and detailed textures. These three frequency bands capture visual features at different scales in the water sample image: low-frequency components reflect the overall transparency and turbidity distribution of the water sample; mid-frequency components reflect medium-scale suspended matter and structural changes; and high-frequency components reflect the presence of fine particles and sharp edges. Through this hierarchical analysis, the system can comprehensively evaluate the visual characteristics of the water sample from a frequency perspective, providing a multi-scale frequency perspective for anomaly detection.
[0087] The sum of squares of amplitude values within the low-frequency, mid-frequency, and high-frequency bands is calculated separately and denoted as low-frequency energy, mid-frequency energy, and high-frequency energy, respectively. Band energy calculation is a crucial step in quantifying frequency distribution characteristics, using the sum of squares to statistically assess the energy contribution of each band. The calculation process involves squaring all amplitude values within each band and summing them to obtain the total energy value for that band. Band energy directly reflects the amount of information in an image within the corresponding frequency range, and its distribution characteristics are closely related to the visual characteristics of the water sample. Pure water samples typically exhibit a predominance of low-frequency energy and lower mid- and high-frequency energy; water samples containing suspended solids show a significant increase in mid-frequency energy; and water samples containing fine particles or sharp edges show a significant increase in high-frequency energy. These three band energy indicators collectively construct a basic description of the water sample's frequency characteristics, providing key information in the frequency dimension for subsequent anomaly assessment. This effectively distinguishes different types of food water quality problems, such as overall turbidity (dominated by low frequencies), suspended solids (significantly high in mid frequencies), and fine particles (abundant in high frequencies).
[0088] The weighted average of radial frequencies, weighted by the amplitude values of each frequency point, is denoted as the spectral centroid feature. Spectral centroid analysis is a crucial step in determining the center of frequency distribution, assessing the overall distribution trend of frequency components through weighted averaging. The calculation process multiplies the radial distance (distance relative to the spectral center) of each frequency point by its amplitude value, then sums these values and divides by the sum of all amplitude values to obtain the spectral centroid value. The formula for calculating the spectral centroid is:
[0089] ;
[0090] in, For the centroid of the spectrum, For frequency domain coordinates, The radial distance to the center of the spectrum. The frequency domain amplitude spectrum in coordinates The value at that location.
[0091] The spectral centroid feature directly reflects the central tendency of the image frequency distribution. The larger the value, the higher the proportion of high-frequency components in the spectrum, which usually corresponds to finer textures and sharper edges. This feature can effectively distinguish different types of water samples. For example, clear water samples have a lower spectral centroid, water samples containing suspended matter have a medium spectral centroid, and water samples contaminated with fine particles have a higher spectral centroid. It is an important indicator for judging the water quality type for food processing.
[0092] The weighted standard deviation of the amplitude value at each frequency point relative to the spectral centroid is calculated and denoted as the spectral spread characteristic. Spectral spread analysis is a crucial step in assessing the dispersion of frequency distribution, quantifying the concentration or dispersion characteristics of the frequency distribution through the weighted standard deviation. The calculation process involves squared the difference between the radial distance of each frequency point and the spectral centroid, multiplied by its amplitude value, summed and normalized, and finally taking the square root to obtain the spectral spread value. The spectral spread characteristic reflects the dispersion of the frequency distribution; a larger value indicates a more dispersed distribution of frequency components, typically corresponding to an uneven texture structure; a smaller value indicates that the frequency is concentrated within a specific range, typically corresponding to a more regular texture. This characteristic can effectively distinguish different types of food water quality anomalies. For example, the spectral distribution of uniform turbidity is relatively concentrated, while the spectral distribution of mixed pollution is more dispersed, making it an important indicator for assessing the complexity of food water quality anomalies.
[0093] After normalizing the frequency domain amplitude spectrum, the information entropy is calculated and denoted as the frequency domain entropy feature. Frequency domain entropy analysis is a key step in assessing the complexity of frequency distribution, quantifying the uncertainty and complexity of the spectrum through information entropy theory. The analysis process first normalizes the frequency domain amplitude spectrum, converting it into a probability distribution; then, the information entropy of the normalized amplitude spectrum is calculated, reflecting the uncertainty of the frequency distribution. The formula for calculating frequency domain entropy is:
[0094] ;
[0095] in, For frequency domain entropy, The normalized frequency domain amplitude spectrum in coordinates The value at that location satisfies .
[0096] Frequency domain entropy directly reflects the complexity and randomness of image frequency distribution. Higher values indicate a more uniform and random frequency distribution, typically corresponding to complex and irregular textures; lower values indicate a more concentrated and regular frequency distribution, typically corresponding to simple or periodic textures. This feature can effectively distinguish different types of food water quality anomalies. For example, pure water samples have lower entropy values, while complex polluted water samples have higher entropy values, making it an important indicator for assessing the complexity of food water quality anomalies.
[0097] Low-frequency energy, mid-frequency energy, high-frequency energy, spectral centroid features, spectral spread features, and frequency domain entropy features are combined into a six-dimensional frequency domain feature sub-vector. Feature combination is the final step in integrating multi-dimensional frequency domain information, constructing a unified frequency domain feature descriptor through vectorization. The combination process arranges six independent feature values in a fixed order to form a six-dimensional feature vector, which fully describes the frequency domain characteristics of the water sample region. These six dimensions describe the frequency characteristics of the water sample from three aspects: energy distribution, central tendency, and complexity. They consider both the energy ratio of different frequency bands and the overall shape and complexity of the frequency distribution, forming a comprehensive and complementary description. The frequency domain feature sub-vector provides a third set of key features for subsequent anomaly detection, and is particularly suitable for identifying food water quality problems related to fine structure and edge sharpness, making it an indispensable and important indicator in food water quality rating.
[0098] In this embodiment of the invention, the color feature vector, texture feature vector, and frequency domain feature vector of each region are standardized and decorrelated before being concatenated to construct an 18-dimensional anomaly feature vector for each region, including:
[0099] For each feature dimension in the color, texture, and frequency domain feature sub-vectors, z-score standardization is performed based on the mean and standard deviation of the corresponding dimension in the historical water sample feature dataset, yielding three standardized sub-vectors. Feature standardization is a crucial step in eliminating the influence of dimensions, achieving normalization of the feature space by setting the mean to zero and the variance to one. The standardization process is based on a statistical model constructed from a large-scale historical water sample dataset, calculating the mean and standard deviation of each feature dimension, and then performing z-score transformation on the corresponding features of the current sample.
[0100] Standardization unifies all feature dimensions to the same scale space, eliminating the impact of differences in units and inconsistent numerical ranges, and ensuring a balanced contribution of each dimension in subsequent feature fusion and analysis. Simultaneously, standardization based on historical data allows the feature values of the current sample to be evaluated relative to the distribution of historical samples, making it easier to identify outliers and special patterns, thus improving the sensitivity and accuracy of detection.
[0101] The Pearson correlation coefficients for each dimension of each pair of the three standardized sub-vectors are calculated to construct a cross-channel correlation coefficient matrix. Correlation analysis is a key step in discovering feature redundancy, quantifying the linear dependencies between features through the correlation coefficient matrix. The analysis process calculates the Pearson correlation coefficients for each dimension of each pair of the three sub-vectors (color, texture, and frequency domain) to form a cross-channel correlation matrix. Each element in the matrix represents the degree of correlation between a pair of feature dimensions, with values ranging from -1 to 1. The closer the absolute value is to 1, the stronger the correlation, and the sign indicates a positive or negative correlation. This correlation analysis can discover redundant information and dependencies between features from different channels, providing a basis for subsequent decorrelation processing. For example, the optical density features of the color channel and the low-frequency energy features of the frequency domain channel may be highly correlated. If this redundancy is not addressed, some characteristics may be over-expressed in the final feature vector, affecting classification accuracy.
[0102] Identify dimensional pairs in the cross-channel correlation coefficient matrix whose absolute values exceed a preset decorrelation threshold. High-correlation dimension identification is a crucial step in determining redundant features; threshold filtering identifies the feature pairs that need processing. The identification process compares each element in the correlation coefficient matrix with a preset decorrelation threshold (typically set to 0.7-0.8). When the absolute value of the correlation coefficient exceeds the threshold, the corresponding dimensional pair is marked as a high-correlation dimensional pair. These high-correlation dimensional pairs represent redundant information in the feature space; ignoring them would reduce the effective dimensionality and expressive efficiency of the feature space. The identification process considers a balance between computational efficiency and processing effectiveness, processing only significantly correlated dimensional pairs to avoid information loss that may result from excessive decorrelation, ensuring that the final feature vector is both concise and effective while retaining comprehensive feature information about food and water quality anomalies.
[0103] A Schmidt orthogonalization projection is applied to the subordinate dimensions of the identified dimension pairs to eliminate cross-channel redundant correlations. Orthogonalization is a key step in eliminating feature redundancy, making feature dimensions orthogonal and independent through projection transformation. The process involves determining the dominant and subordinate dimensions (usually based on the physical meaning and discriminative power of the features) for each highly correlated dimension pair, and then performing a Schmidt orthogonalization projection on the subordinate dimensions to make them orthogonal to the dominant dimension. This process preserves the original information of the dominant dimension while adjusting the subordinate dimensions to retain only their unique information components orthogonal to the dominant dimension. Orthogonalization effectively eliminates redundant correlations in the feature space, improving the efficiency and accuracy of feature representation, while avoiding the information loss that may result from simply deleting dimensions. In the feature vector after orthogonalization, each dimension carries relatively independent information, collectively forming a complete description of food water quality anomalies, providing high-quality feature input for subsequent discriminant analysis.
[0104] The three sub-vectors after orthogonal projection are concatenated in the order of color, texture, and frequency domain to generate an 18-dimensional anomaly feature vector. Feature concatenation is the final step in constructing a unified feature representation, forming a complete anomaly feature vector through ordered combination. The concatenation process connects the processed color feature sub-vector (6-dimensional), texture feature sub-vector (6-dimensional), and frequency domain feature sub-vector (6-dimensional) in a fixed order to form an 18-dimensional comprehensive feature vector. This ordered concatenation method preserves the semantic structure of the features, facilitating subsequent analysis and interpretation. The final 18-dimensional anomaly feature vector is a high-dimensional mathematical representation of food water quality anomalies. Each dimension captures a specific aspect of the anomaly, collectively forming a comprehensive description of the anomaly. This feature vector integrates information from three different perspectives, considering color characteristics, texture structure, and frequency domain features. It can effectively distinguish various types of food water quality problems, providing ideal feature input for subsequent Fisher discriminant analysis and serving as a key data foundation for accurate food water quality grading.
[0105] In this embodiment of the invention, calculating the optimal projection direction and dynamic hierarchical threshold group based on the Fisher discrimination criterion includes:
[0106] The 18-dimensional anomaly feature vectors in the historical water sample feature dataset were divided into four sample groups according to their labeling levels, from Level I to Level IV. Sample grouping is a fundamental step in building the discriminative model. By dividing the training data into labeled levels, a class structure is provided for subsequent analysis. The grouping process is based on a large-scale historical water sample database. Samples are divided into four levels according to the anomaly levels labeled by experts: Level I contains slightly anomalous samples, which have little impact on usability; Level II contains moderately anomalous samples, which require attention; Level III contains significantly anomalous samples, which need processing; and Level IV contains severely anomalous samples, which are not suitable for use. This level-based grouping method directly corresponds to the final food water quality grading target, ensuring consistency between model training and practical application. The number of samples in the dataset is usually kept relatively balanced across levels to avoid classification bias, while ensuring sufficient sample size in each level group (usually at least 200-500 samples per level) to guarantee statistical reliability. These grouped samples provide the basic data structure for subsequent divergence matrix calculation and discriminant analysis.
[0107] The mean vector and within-group covariance matrix of each sample group are calculated separately, and the within-group covariance matrices are summed to obtain the within-class scatter matrix. The scatter matrix calculation is a core step in Fisher's discriminant analysis, quantifying intra-class dispersion and inter-class variability through a statistical model. The calculation process first calculates the mean vector in the 18-dimensional feature space for each rank group, representing the center position of that rank; then, the within-group covariance matrix is calculated, representing the degree of dispersion of samples around the center point in that rank; finally, the covariance matrices of the four rank groups are summed to obtain the within-class scatter matrix Sw, representing the overall dispersion within all rank groups. The within-class scatter matrix is an 18×18 symmetric positive definite matrix, where the diagonal elements represent the variance of each feature dimension within the group, and the off-diagonal elements represent the covariance between pairs of feature dimensions. This matrix comprehensively describes the feature distribution characteristics within each rank group, providing crucial information for finding the optimal projection direction; that is, the ideal projection direction should minimize the within-class scatter, ensuring that samples of the same rank cluster tightly after projection.
[0108] The inter-class divergence matrix is obtained by calculating the outer product between the mean vectors of each group and the global mean vector, and then weighting and summing them according to the number of samples in each group. Inter-class divergence calculation is a crucial step in quantifying rank differences, assessing the degree of separation between rank groups through mean differences. The calculation process first obtains the global mean vector for all samples; then, it calculates the difference vector between the mean of each rank group and the global mean; next, it calculates the outer product matrix of the difference vectors and weights them according to the number of samples in that group; finally, it sums the weighted outer product matrices of all rank groups to obtain the inter-class divergence matrix Sb. The inter-class divergence matrix is also an 18×18 symmetric matrix, reflecting the degree of separation between rank groups in the feature space. This matrix describes the relative positional relationship of each rank group in the feature space, providing a second key piece of information for finding the optimal projection direction: the ideal projection direction should maximize the inter-class divergence, ensuring that samples of different ranks are sufficiently separated after projection.
[0109] The optimal projection direction is denoted as the eigenvector corresponding to the largest eigenvalue of the product matrix of the inverse of the intra-class scatter matrix and the inter-class scatter matrix. Eigenvalue decomposition is a key step in determining the optimal projection, finding the projection direction that best distinguishes classes through eigenvalue analysis. The decomposition process first calculates the intra-class scatter matrix. The inverse matrix, then combined with the between-class scatter matrix. Multiply to obtain a matrix Next, eigenvalue decomposition is performed on the matrix to obtain all eigenvalues and their corresponding eigenvectors. Finally, the eigenvector corresponding to the largest eigenvalue is selected as the optimal projection direction. This direction satisfies the optimization objective of Fisher's criterion, which is to maximize the ratio of between-class divergence to within-class divergence after projection.
[0110] The optimal projection direction is an 18-dimensional unit vector, with each component corresponding to a projection weight in one dimension of the original feature space. This vector defines a linear mapping from the 18-dimensional feature space to the 1-dimensional discriminant space, and is key to achieving dimensionality reduction of high-dimensional features and optimal classification. It can most effectively distinguish between different levels of food and water quality anomalies, providing a foundation for subsequent threshold determination and sample classification.
[0111] Projecting all samples from each sample group onto a one-dimensional space along the optimal projection direction yields the projection value distribution for each group. Sample projection is a crucial step in achieving dimensionality reduction classification, mapping high-dimensional features to the discriminant space through inner product operations. The projection process calculates the inner product of the 18-dimensional feature vectors of all samples in the historical dataset with the optimal projection direction, obtaining one-dimensional projection values. Then, the projection values are grouped according to the original grade labels, resulting in four projection value distributions from grade I to grade IV. These distributions typically represent four overlapping intervals in one-dimensional space; ideally, the overlap is small, indicating effective differentiation between grades. The projection calculation process simplifies the subsequent classification task, transforming the complex 18-dimensional space discrimination into a simple one-dimensional threshold comparison, significantly reducing computational complexity while maintaining classification accuracy. The effectiveness of this dimensionality reduction mapping is directly based on the theoretical foundation of Fisher discriminant analysis, maximizing the preservation of class discriminant information during dimensionality reduction.
[0112] For the projected value distribution of adjacent class groups, the boundary point that minimizes the sum of the misclassification rates of the two groups is calculated and denoted as the classification threshold between adjacent classes. Threshold optimization is a key step in determining the classification boundary, finding the optimal split point through the principle of minimizing the misclassification rate. The optimization process analyzes the overlapping region of each pair of adjacent class groups (Ⅰ-Ⅱ, Ⅱ-Ⅲ, Ⅲ-Ⅳ) in the one-dimensional projected space, then calculates the total misclassification rate (the sum of misclassified samples from both classes) at each point within the overlapping region using that point as the threshold; finally, the point that minimizes the total misclassification rate is selected as the classification threshold between the two classes. This threshold determination method based on statistical optimization can find the optimal decision boundary under a given data distribution, balancing the classification accuracy of each class and avoiding classification bias. Compared with simple midpoint or mean thresholds, the misclassification rate minimization threshold usually achieves better classification performance, especially in cases of imbalanced or asymmetrical class distributions.
[0113] The three tiered thresholds—Levels I-II, II-III, and III-IV—are combined to form a dynamic tiered threshold group. Threshold aggregation is the final step in completing the classification rules, forming a complete multi-level threshold system through ordered combination. The aggregation process arranges the optimal thresholds among three adjacent levels in tiered order, forming the dynamic tiered threshold group. ,in This is the threshold separating Level I and Level II. This is the threshold separating Level II and Level III. This set of thresholds defines the boundary between Level III and Level IV. It defines four intervals in a one-dimensional discrimination space, corresponding to Levels I to IV from left to right. The "dynamic" nature of this dynamic grading threshold set is reflected in its automatic calculation and updating based on current historical data. It adapts to changes in data distribution and adjustments to testing standards, avoiding the limitations of fixed thresholds. This adaptive threshold system is a key component for achieving accurate food water quality grading, providing a flexible and reliable decision-making basis for subsequent sample classification.
[0114] In this embodiment of the invention, an area-weighted comprehensive evaluation is performed on the anomaly levels of the four types of segmented regions to determine the final water quality anomaly level of the water sample, including:
[0115] The ratio of the number of pixels in the turbidity mask, suspended matter mask, color anomaly mask, and biofilm mask to the total number of pixels in the enhanced image is calculated and recorded as the area weight of each segmented region. Area weight calculation is a crucial step in assessing the extent of anomalies, quantifying the coverage of each type of anomaly through pixel statistics. The calculation process involves counting the number of pixels in each of the four anomaly masks, then dividing by the total number of pixels in the image to obtain a normalized area ratio, which serves as the weight coefficient. These weights directly reflect the spatial distribution range of each type of anomaly in the water sample; larger values indicate a wider anomaly coverage, typically corresponding to more severe food safety water quality problems. The introduction of area weights ensures that the final rating considers not only the severity of the anomaly but also its coverage, providing a more comprehensive assessment of the food safety water quality status. This spatially distributed weight design is particularly important for balancing local and global anomalies, avoiding the risk of underestimating small-scale severe anomalies or overestimating large-scale minor anomalies.
[0116] The anomaly level values of each segmented region are weighted and summed based on their area weights to obtain a weighted anomaly score. Weighting is the core step in integrating information from multiple regions, and a comprehensive anomaly score is calculated through a weighted average. The calculation process multiplies the level values of each anomaly region (Level I = 1, Level II = 2, Level III = 3, Level IV = 4) by their corresponding area weights, and then sums the results to obtain a preliminary weighted anomaly score. The score calculation formula is:
[0117] ;
[0118] in, For weighted outlier scoring, For the first Area weights for anomalies For the first The numerical value of the exception level.
[0119] The weighted score is a continuous value, typically falling within the range of [1, 4], directly reflecting the overall degree of anomaly in the water sample. A higher value indicates a more severe food water quality problem. This weighted averaging method can reasonably balance the contributions of various anomalies, ensuring that the final rating considers both the type and degree of anomalies, as well as the spatial range of anomalies, providing an overall assessment of the food water quality status.
[0120] When the weighted anomaly score exceeds the preset comprehensive threshold and at least two anomaly categories reach Level III, the comprehensive level is increased by one level based on the weighted result. Level adjustment is a supplementary rule for handling special cases, improving rating accuracy by considering the combined effects of multiple anomalies. The adjustment rule is designed based on conservative principles of food and water quality safety; when multiple serious anomalies occur simultaneously, the overall food and water quality risk is usually higher than the simple sum of the individual effects of each anomaly. The preset comprehensive threshold is typically set at 2.5-3.0, indicating that the basic score has reached a relatively high level; the condition that two anomalies simultaneously reach Level III indicates the existence of multiple significant safety risks. When both conditions are met, the system increases the comprehensive level by one level based on the weighted result, but not exceeding the upper limit of Level IV. This adjustment rule, which considers the synergistic effects of multiple anomalies, enhances the rating system's sensitivity to complex food and water quality issues and improves its ability to identify potentially high-risk situations.
[0121] When only a single segmented region exhibits an anomaly and its area weight is below a preset minimum area threshold, the overall rating is downgraded by one level. This downgrade is a balancing rule to avoid oversensitivity, reducing the false alarm rate by considering the salience of the anomaly. The adjustment rule is designed based on the reliability principle of anomaly detection; when the anomaly range is extremely small and only a single type occurs, it may be a false positive caused by image noise or local interference. The preset minimum area threshold is typically set to 0.05-0.1, indicating that the anomaly coverage area is less than 5-10% of the image. When these conditions are met, the system downgrades the overall rating by one level based on the weighted result, but not below the lower limit of Level I. This adjustment rule, which considers the salience of the anomaly, enhances the robustness of the rating system, reduces sensitivity to minor noise and local interference, and improves reliability and practicality in real-world applications.
[0122] After the above adjustments, the adjusted comprehensive grade is quantified into corresponding grades from Level I to Level IV, which serve as the final water quality anomaly grade output. Grade quantization is the final step in generating the final result, outputting standardized grades through discretization. The quantization process converts the adjusted continuous score values (usually within the range of [1,4]) into discrete grade labels, typically using rounding or the nearest integer principle to map the score to the nearest integer level. The final output water quality anomaly grade is a clear classification result, ranging from Level I (minor anomaly) to Level IV (serious anomaly), intuitively reflecting the safety status of the water sample and usage recommendations. This discrete grade output facilitates subsequent decision-making and processing, making the test results easy to understand and implement, while maintaining consistency with the standard water quality rating system, and facilitating comparison and integration with other testing methods and historical data.
[0123] The above describes the high-standard detection method for food water quality grading in the embodiments of this application. The following describes the high-standard detection device for food water quality grading in the embodiments of this application. Please refer to [link / reference]. Figure 2 One embodiment of the high-standard food water quality grading testing device in this application includes:
[0124] The image acquisition unit is used to acquire macro images of the water sample to be tested using an industrial camera and a ring shadowless light source under preset exposure parameters, and these images are recorded as the original water sample images.
[0125] The image enhancement unit is used to perform HSV color space transformation on the original water sample image, separate the hue channel, saturation channel and brightness channel, and apply multi-scale Retinex enhancement processing to the brightness channel to generate an enhanced image after illumination correction.
[0126] The image segmentation unit is used to input the enhanced image into the pre-trained lightweight MobileSAM segmentation network and output four types of pixel-level segmentation results: turbidity region mask, suspended matter region mask, color abnormality region mask, and biofilm region mask.
[0127] The feature extraction unit is used to extract features along three parallel paths—color channel, texture channel, and frequency domain channel—for the image region covered by each type of pixel-level segmentation result, and obtain the color feature sub-vector, texture feature sub-vector, and frequency domain feature vector of the region.
[0128] The feature construction unit is used to concatenate the color feature vector, texture feature vector and frequency domain feature vector of each region after standardization and decorrelation processing to construct the 18-dimensional anomaly feature vector of each region.
[0129] The model training unit is used to calculate the optimal projection direction and dynamic grading threshold group based on the Fisher discrimination criterion and the historical water sample feature dataset with labeled anomaly levels.
[0130] The hierarchical discrimination unit is used to project the 18-dimensional abnormal feature vector of each region along the optimal projection direction to obtain the one-dimensional discrimination score of each region. According to the dynamic hierarchical threshold group, the discrimination score of each region is divided into level I, level II, level III or level IV abnormality level.
[0131] The comprehensive evaluation unit is used to perform area-weighted comprehensive evaluation of the anomaly levels of the four types of segmented areas, determine the final water quality anomaly level of the water sample, and output the classification results.
[0132] The various units are connected via wired and / or wireless means to enable data transmission between units.
[0133] This invention achieves high-standard graded detection of food water quality through high-precision image acquisition, multi-scale illumination enhancement, intelligent region segmentation, multi-channel feature extraction, Fisher discriminant analysis, and weighted comprehensive evaluation. The feature fusion grading method of this invention can accurately distinguish different types and degrees of food water quality anomalies, effectively identifying common problems such as turbidity, suspended solids, abnormal color, and biofilm, providing a systematic solution for food water quality safety assessment.
[0134] The above are merely preferred embodiments of the present invention and are not intended to limit the present invention. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art can still modify the technical solutions described in the foregoing embodiments or make equivalent substitutions for some of the technical features. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.
[0135] It should be noted that all formulas in this manual are calculated by removing dimensions and taking their numerical values. The formulas are derived from software simulations based on a large amount of collected data to obtain the most recent real-world results. The preset parameters and thresholds in the formulas are set by those skilled in the art according to the actual situation.
[0136] Although embodiments of the invention have been shown and described, those skilled in the art will understand that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the claims and their equivalents.
Claims
1. A high-standard testing method for water quality grading in food, characterized in that, include: Macro images of the water sample to be tested are acquired using an industrial camera and a ring-shaped shadowless light source under preset exposure parameters and recorded as the original water sample image. The original water sample image is transformed using the HSV color space to separate the hue channel, saturation channel and brightness channel, and multi-scale Retinex enhancement processing is applied to the brightness channel to generate an enhanced image after illumination correction. The enhanced image is input into a pre-trained lightweight MobileSAM segmentation network, which outputs four types of pixel-level segmentation results: turbidity region mask, suspended matter region mask, color abnormality region mask, and biofilm region mask. For each type of image region covered by the pixel-level segmentation result, features are extracted along three parallel paths: color channel, texture channel, and frequency domain channel, to obtain the color feature vector, texture feature vector, and frequency domain feature vector of the region. The color feature vector, texture feature vector and frequency domain feature vector of each region are standardized and decorrelated and then concatenated to construct an 18-dimensional anomaly feature vector of each region. Based on the historical water sample feature dataset with labeled anomaly levels, the optimal projection direction and dynamic classification threshold group are calculated according to Fisher's discrimination criterion. The 18-dimensional abnormal feature vectors of each region are projected along the optimal projection direction to obtain the one-dimensional discrimination score of each region. According to the dynamic classification threshold group, the discrimination scores of each region are divided into level I, level II, level III or level IV abnormality levels. The area-weighted comprehensive evaluation of the anomaly levels of the four segmented regions is performed to determine the final water quality anomaly level of the water sample and output the classification results.
2. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The step of applying multi-scale Retinex enhancement processing to the luminance channel to generate an enhanced image after illumination correction includes: Each at a small scale Mesoscale With large scale Three sets of Gaussian kernels are convolved on the brightness channel to obtain illuminance estimation maps at three scales; The Retinex reflectance components at three scales are obtained by taking the logarithm of the luminance channel and subtracting it from the illuminance estimation map at each scale. The Retinex reflection components at the three scales are weighted and fused according to a preset weighting coefficient to obtain the fused reflection components; Perform upper and lower percentile truncation and linear stretching on the fused reflection component to map the pixel value to a preset dynamic range and obtain the corrected brightness channel; The corrected luminance channel is merged with the original hue channel and saturation channel, and then the enhanced image is generated by HSV to RGB inverse transformation.
3. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The enhanced image is input into a pre-trained lightweight MobileSAM segmentation network, which outputs four types of pixel-level segmentation results, including: The enhanced image is scaled to the standard input size of the MobileSAM segmentation network, and multi-level feature maps are extracted using a lightweight image encoder. Based on the spatial prior distribution of water quality anomaly areas, a uniformly distributed set of gridded cue points is generated within the effective area of the image. The set of gridded cue points and the multi-level feature map are fed into the mask decoder, and the candidate segmentation mask and its confidence score corresponding to each cue point are output. The candidate segmentation masks are arranged in descending order of confidence scores, and non-maximum suppression is performed sequentially to remove redundant masks with cross-union ratios exceeding a preset overlap threshold. For the retained candidate segmentation masks, the mean features of the mask coverage area in the hue channel and the saturation channel are extracted, and each mask is classified into the turbidity region, suspended matter region, abnormal color region or biofilm region according to the preset classification rules.
4. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The step of extracting features along the color channel to obtain the color feature sub-vector of the region includes: In the enhanced image, a background region not covered by any segmentation mask is selected, and the average brightness value of the background region is calculated and recorded as the reference background brightness. The optical density value of each pixel is obtained by taking the negative logarithmic ratio of the brightness value of each pixel in the segmented region to the brightness of the reference background. The mean and standard deviation of the optical density values within this region are statistically analyzed and denoted as the optical density mean characteristic and the optical density dispersion characteristic, respectively. Extract the mean and kurtosis of the pixel values in the tone channel of the region, and denot them as tone mean feature and tone kurtosis feature, respectively. The mean and skewness of the pixel values in the saturation channel of this region are extracted and denoted as the saturation mean feature and the saturation skewness feature, respectively. The optical density mean feature, optical density dispersion feature, hue mean feature, hue kurtosis feature, saturation mean feature, and saturation skewness feature are combined into a six-dimensional color feature sub-vector.
5. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The step of extracting features along the texture channel to obtain the texture feature sub-vector of the region includes: Perform a two-dimensional discrete wavelet transform on the brightness image corresponding to the segmented region, decompose it to a preset number of layers L, and obtain the wavelet coefficient matrix of the horizontal detail sub-band, vertical detail sub-band and diagonal detail sub-band of each layer; The sum of squares of the wavelet coefficient matrices of the three detail sub-bands of each layer is calculated to obtain the energy value of each sub-band; Select the layer with the largest total energy of the three sub-bands, and extract the energy values of the horizontal, vertical and diagonal sub-bands of that layer, which are respectively denoted as the main scale horizontal texture energy, the main scale vertical texture energy and the main scale diagonal texture energy. Calculate the decay rate sequence of the total energy of the three subbands between adjacent decomposition layers, extract the maximum value in the decay rate sequence, and denote it as the texture roughness feature; The ratio of the energy of the horizontal detail subband to the energy of the vertical detail subband in the finest scale layer is calculated and denoted as the texture directionality feature. The principal scale horizontal texture energy, principal scale vertical texture energy, principal scale diagonal texture energy, texture roughness feature, texture directionality feature, and total energy value of the entire layer are combined into a six-dimensional texture feature sub-vector.
6. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The step of extracting features along the frequency domain channel to obtain the frequency domain feature sub-vector of the region includes: Perform a two-dimensional discrete Fourier transform on the brightness image corresponding to the segmented region to obtain the frequency domain amplitude spectrum and shift the zero frequency to the center of the spectrum; With the center of the spectrum as the center, the frequency domain amplitude spectrum is divided into three concentric ring regions: a low-frequency ring zone, a mid-frequency ring zone, and a high-frequency ring zone, according to a preset radius ratio. Calculate the sum of squares of the amplitude values in the low-frequency loop, mid-frequency loop, and high-frequency loop respectively, and denot them as low-frequency energy, mid-frequency energy, and high-frequency energy. The weighted mean of the radial frequencies is calculated using the amplitude values at each frequency point as weights, and is denoted as the centroid feature of the spectrum. Calculate the weighted standard deviation of the amplitude value at each frequency point relative to the centroid of the spectrum, and denot it as the spectral spread characteristic; After normalizing the frequency domain amplitude spectrum, the information entropy is calculated and denoted as the frequency domain entropy feature. The low-frequency energy, mid-frequency energy, high-frequency energy, spectral centroid feature, spectral spread feature, and frequency domain entropy feature are combined into a six-dimensional frequency domain feature sub-vector.
7. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The process involves standardizing and decorrelating the color feature vectors, texture feature vectors, and frequency domain feature vectors of each region, then concatenating them to construct an 18-dimensional anomaly feature vector for each region, including: For each feature dimension of the color feature sub-vector, texture feature sub-vector, and frequency domain feature sub-vector, z-score standardization is performed based on the mean and standard deviation of the corresponding dimension in the historical water sample feature dataset to obtain three standardized sub-vectors. Calculate the Pearson correlation coefficients of each dimension between each pair of the three standardized subvectors, and construct a cross-channel correlation coefficient matrix; Identify dimensional pairs in the cross-channel correlation coefficient matrix whose absolute values exceed a preset decorrelation threshold; Apply a Schmitt orthogonal projection to the subordinate dimensions in the identified dimension pairs; The three sub-vectors after orthogonal projection are concatenated in the order of color, texture, and frequency domain to generate the 18-dimensional anomaly feature vector.
8. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The calculation of the optimal projection direction and dynamic hierarchical threshold group based on the Fisher discrimination criterion includes: The 18-dimensional anomaly feature vectors in the historical water sample feature dataset are divided into four sample groups according to the labeling levels from Level I to Level IV. Calculate the mean vector and within-group covariance matrix for each sample group, and sum the within-group covariance matrices to obtain the within-class scatter matrix. Calculate the outer product between the mean vector of each group and the global mean vector, and then sum them up in weighted order according to the number of samples in each group to obtain the inter-class scatter matrix; The eigenvector corresponding to the largest eigenvalue of the product matrix of the inverse of the intra-class scatter matrix and the inter-class scatter matrix is denoted as the optimal projection direction. Project all samples of each sample group onto a one-dimensional space along the optimal projection direction to obtain the projection value distribution of each group; For the projection value distribution of adjacent grade groups, calculate the dividing point that minimizes the sum of the misclassification rates of the two groups, and denot it as the classification threshold between the adjacent grades. The three grading thresholds—Level I-II, Level II-III, and Level III-IV—are combined to form the dynamic grading threshold group.
9. The high-standard detection method for food water quality grading according to claim 1, characterized in that, The method of performing area-weighted comprehensive evaluation of the anomaly levels of the four types of segmented regions to determine the final water quality anomaly level of the water sample includes: The ratio of the number of pixels in the turbidity region mask, the suspended matter region mask, the color abnormality region mask, and the biofilm region mask to the total number of pixels in the enhanced image is calculated and recorded as the area weight of each segmented region. The anomaly level values of the corresponding regions are weighted and summed using the area weights of each segmented region to obtain a weighted anomaly score. When the weighted anomaly score exceeds the preset comprehensive threshold and there are at least two types of segmented regions with anomaly levels reaching Level III, the comprehensive level will be increased by one level based on the weighted result. When only a single segmented region has an anomaly and its area weight is lower than the preset minimum area threshold, the overall level will be downgraded by one level. After the above adjustments, the adjusted comprehensive level will be quantified into the corresponding level from Level I to Level IV, which will be used as the final water quality anomaly level output.
10. A high-standard testing device for food water quality grading, used to implement the high-standard testing method for food water quality grading as described in any one of claims 1 to 9, characterized in that, include: The image acquisition unit is used to acquire macro images of the water sample to be tested using an industrial camera and a ring shadowless light source under preset exposure parameters, and these images are recorded as the original water sample images. The image enhancement unit is used to perform HSV color space transformation on the original water sample image, separate the hue channel, saturation channel and luminance channel, and apply multi-scale Retinex enhancement processing to the luminance channel to generate an enhanced image after illumination correction. The image segmentation unit is used to input the enhanced image into a pre-trained lightweight MobileSAM segmentation network and output four types of pixel-level segmentation results: turbidity region mask, suspended matter region mask, color abnormality region mask, and biofilm region mask. The feature extraction unit is used to extract features from the image region covered by each type of pixel-level segmentation result along three parallel paths: color channel, texture channel, and frequency domain channel, to obtain the color feature sub-vector, texture feature sub-vector, and frequency domain feature vector of the region. The feature construction unit is used to concatenate the color feature sub-vectors, texture feature sub-vectors and frequency domain feature sub-vectors of each region after standardization and decorrelation processing to construct an 18-dimensional anomaly feature vector for each region. The model training unit is used to calculate the optimal projection direction and dynamic grading threshold group based on the Fisher discrimination criterion and the historical water sample feature dataset with labeled anomaly levels. The hierarchical discrimination unit is used to project the 18-dimensional abnormal feature vector of each region along the optimal projection direction to obtain the one-dimensional discrimination score of each region, and to classify the discrimination score of each region into level I, level II, level III or level IV abnormality levels according to the dynamic hierarchical threshold group. The comprehensive evaluation unit is used to perform area-weighted comprehensive evaluation of the anomaly levels of the four types of segmented areas, determine the final water quality anomaly level of the water sample, and output the classification results.