A non-destructive detection method and system for corn seed vigor based on near-infrared spectroscopy
By combining generative adversarial networks and band grouping attention modules, the problems of insufficient generalization ability and poor physical interpretability of seed vigor detection models under small sample conditions in existing technologies are solved, and high-precision non-destructive detection of maize seed vigor is achieved.
Patent Information
- Application Number
- CN202611108052.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-24
- Publication Date
- 2026-11-20
AI Technical Summary
Existing seed vigor detection methods based on near-infrared spectroscopy have insufficient model generalization ability under small sample conditions, making it difficult to effectively utilize the global statistical characteristics and physical meaning of the spectrum. Furthermore, traditional preprocessing methods are inadequate for handling noise and baseline drift, resulting in poor detection accuracy and physical interpretability.
A generative adversarial network based on WGAN-GP is used to generate synthetic spectral data that conforms to the laws of spectroscopy. A deep convolutional neural network with band grouping attention module and statistical feature extraction branch is combined to improve the model’s discrimination ability through physical constraints and attention mechanism.
This improved the generalization ability and accuracy of the seed vigor discrimination model, enabling rapid, accurate, and non-destructive detection of maize seed vigor and enhancing the physical interpretability of the model.
Smart Images

Figure CN123126129A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of maize seed vigor detection technology, and in particular to a non-destructive detection method and system for maize seed vigor based on near-infrared spectroscopy. Background Technology
[0002] Seed vigor is a key indicator of seed quality, directly affecting crop emergence rate, seedling vigor, and final yield. High-vigor seeds exhibit rapid and uniform emergence, enabling them to adapt to complex field environments and laying the foundation for high and stable crop yields; conversely, low-vigor seeds can lead to missing seedlings and gaps in rows, severely impacting agricultural production efficiency. Therefore, rapid and accurate detection and grading of seed vigor during seed production, processing, storage, and sales are crucial for ensuring agricultural production safety and enhancing the competitiveness of the seed industry. Traditional seed vigor detection methods mainly include standard germination tests, TTC staining, and conductivity measurement. These methods are all destructive and cannot meet the practical needs of modern seed industry for high-throughput, non-destructive screening of single seeds. Near-infrared spectroscopy offers a new technical approach for seed vigor detection due to its advantages of speed, non-destructive nature, and lack of chemical reagent requirements. However, existing near-infrared spectroscopy-based seed vigor detection methods suffer from limitations in accuracy and generalization ability when faced with issues such as small sample modeling, insufficient utilization of spectral features, and insufficient physical interpretability of the model. A novel detection method that can simultaneously address these problems is urgently needed.
[0003] Near-infrared spectroscopy can reflect the vibrational information of hydrogen-containing groups in organic molecules such as water, starch, protein, and lipids within seeds. By establishing a correlation model between spectral features and seed vigor, seed vigor can be indirectly determined. In practical applications, data augmentation techniques are often used to expand limited labeled samples to meet the training needs of deep learning models. Among these, generative adversarial networks can generate new synthetic spectral data by learning the distribution of real spectral data. Regarding spectral feature extraction and modeling, spectra typically require preprocessing steps such as Savitzky-Golay smoothing to remove high-frequency noise, standard normal variable transformation to eliminate scattering interference, and first-order derivative processing to suppress baseline drift. Then, a classification model establishes a mapping from spectral features to vigor categories. In recent years, deep learning methods such as deep convolutional neural networks have been gradually applied in the field of spectral analysis due to their ability to automatically extract deep features. Inception structures and residual connections, in particular, improve model performance in terms of multi-scale feature capture and network training stability, respectively. Meanwhile, the introduction of attention mechanisms allows models to assign differentiated attention to different features, making it possible to integrate the physical meaning of spectral wavelength regions into the model. Furthermore, in spectral analysis, statistical measures such as mean, standard deviation, and skewness are often used to describe the global distribution characteristics of the spectrum. However, these statistical features are often ignored in existing deep learning methods and have not been effectively integrated into a unified model framework.
[0004] However, the aforementioned existing technologies still face the following three technical shortcomings in practical applications. First, obtaining high-quality labeled samples is difficult. Standard germination tests for seed vigor take more than 7 days, resulting in a limited number of labeled samples available for modeling. Commonly used data augmentation methods, such as adding noise to the original spectrum or interpolation, may produce synthetic spectra with curve shapes that do not conform to spectroscopic laws. The lack of data diversity and physical realism still restricts the improvement of model generalization ability under small sample conditions. Second, near-infrared spectral data has high dimensionality, complex noise, and problems such as baseline drift and scattering interference. Traditional preprocessing methods and shallow machine learning models are unable to fully explore the deep features contained in the spectrum. Although existing deep learning methods can automatically extract local waveform features, most of them only focus on the local waveform features of the spectrum and do not make sufficient use of the global statistical characteristics of the spectrum. However, changes in seed vigor often involve the synergistic changes of multiple chemical components, and single-dimensional local features are difficult to comprehensively represent vigor differences. Third, existing models lack consideration of the physical meaning of spectra and are difficult to consciously distinguish the band regions corresponding to different chemical components during feature extraction. This results in poor physical interpretability of the models, insufficient focus on key bands, and ineffective utilization of the characteristic absorption peak regions of chemical components closely related to seed vigor, such as starch and protein, in the near-infrared spectrum.
[0005] To overcome the aforementioned technical deficiencies, this invention provides a non-destructive detection method and system for maize seed vigor based on near-infrared spectroscopy. It expands the dataset by generating synthetic spectral data that conforms to spectroscopic laws through a physically constrained generative adversarial network. A band-grouping attention module introduces prior spectroscopic knowledge into a deep convolutional neural network to enhance the model's ability to focus on key chemical information regions. Furthermore, a statistical feature extraction branch supplements the global statistical distribution information of the spectrum and complements deep local features, thereby achieving high-precision, non-destructive, and rapid identification of maize seed vigor even under imbalanced sample conditions. Summary of the Invention
[0006] This invention aims to address the shortcomings of existing technologies by providing a non-destructive detection method and system for maize seed vigor based on near-infrared spectroscopy, as detailed below: 1) In a first aspect, the present invention provides a non-destructive detection method for maize seed vigor based on near-infrared spectroscopy, comprising the following steps: Raw near-infrared spectral data of naturally aged corn seeds were collected, and a standard germination test was performed on each naturally aged corn seed to obtain a viability label for each naturally aged corn seed. A constrained generative adversarial network (GAN) is constructed and trained using raw near-infrared spectral data. After training, the generator in the constrained GAN generates synthetic spectral data. The GAN is constructed based on the WGAN-GP framework, and the training loss function includes a spectral physical constraint loss term, which is a weighted sum of smoothness constraint loss term, continuity constraint loss term, curvature constraint loss term, baseline drift constraint loss term, and band correlation constraint loss term. The original near-infrared spectral data and the synthetic spectral data were merged to construct an enhanced spectral dataset. The enhanced spectral dataset was then preprocessed to obtain a preprocessed spectral dataset. A deep convolutional neural network (DNN) model comprising a band grouping attention module and a statistical feature extraction branch was constructed. The DNN model was trained and its performance validated using a preprocessed spectral dataset and the viability labels of each naturally aged corn seed, resulting in a trained seed viability discrimination model. The band grouping attention module divides the input spectrum into multiple physically meaningful subgroups based on the wavelength range of the near-infrared spectrum and assigns learnable attention weights to each subgroup to enhance the contribution of key chemical information regions to the discrimination results. The statistical feature extraction branch extracts statistical feature vectors from the input spectrum and adaptively weights and fuses them with deep features extracted from the backbone network of the DNN model through a gated fusion mechanism. Near-infrared spectral data of maize seeds to be tested are collected and preprocessed, then input into the trained seed vigor discrimination model to output the vigor discrimination results of the maize seeds to be tested.
[0007] The beneficial effects of the non-destructive detection method for maize seed vigor based on near-infrared spectroscopy provided by this invention are as follows: This invention imposes physical constraints on the generative adversarial network (GAN) through smoothness constraint loss terms, continuity constraint loss terms, curvature constraint loss terms, baseline drift constraint loss terms, and band correlation constraint loss terms. This ensures that the generated synthetic spectral data conforms to the physical laws of spectroscopy, expands the number of low-viability samples, alleviates overfitting under imbalanced conditions, and improves the generalization ability of the seed viability discrimination model. The band grouping attention module divides the input spectrum into multiple physically meaningful subgroups based on the wavelength range of the near-infrared spectrum and assigns learnable attention weights to each subgroup. This allows the deep convolutional neural network model to enhance the contribution of key chemical information regions to the discrimination results, overcoming the shortcomings of existing models such as poor physical interpretability and insufficient attention to key bands. The statistical feature extraction branch extracts statistical feature vectors from the input spectrum and adaptively weights and fuses them with the deep features extracted by the backbone network through a gated fusion mechanism. This supplements the macroscopic distribution characteristics of the spectrum from a global perspective, complementing local waveform features and improving the accuracy and robustness of viability discrimination. Near-infrared spectral data of maize seeds to be tested were collected and preprocessed, and then input into a trained seed vigor discrimination model to output vigor discrimination results, thus realizing rapid, accurate and non-destructive detection of maize seed vigor.
[0008] Furthermore, the smoothness constraint loss term is used to penalize the second derivative of the generated spectrum, and its mathematical expression is: in, Represents the smoothness constraint loss term. This represents the mathematical expectation of a batch of generated samples. To generate the spectrum in the first Reflectance values for each band, and The first The and the first Reflectance values for each band, Total number of bands; The continuity constraint loss term uses Huber loss to limit the reflectivity variation between adjacent bands, and its mathematical expression is as follows: in, This represents the loss term due to continuity constraints. The Huber loss function is defined as follows: in, The difference in reflectivity between adjacent bands, i.e. , express The absolute value; The curvature constraint loss term is used to limit the local curvature of the generated spectrum, and its mathematical expression is: in, This represents the curvature constraint loss term. This represents the absolute value operator; The baseline drift constraint loss term is used to suppress the overall baseline drift of the spectrum, and its mathematical expression is as follows: in, This represents the baseline drift constraint loss term. To generate spectral vectors, The baseline vector is obtained by linear interpolation of the two endpoints of the spectrum. The squared norm of a vector is denoted by 2. The band correlation constraint loss term is used to match the band correlation of the generated spectrum with the prior correlation matrix, and its mathematical expression is: in, This represents the band correlation constraint loss term. Let be the mean square error function. For operations on the Pearson correlation coefficient matrix, To generate a matrix of samples in batches, This is the Gaussian attenuation prior correlation matrix based on band distance.
[0009] The beneficial effects of adopting the above-mentioned further technical solutions are as follows: By introducing five physical constraints—smoothness, continuity, curvature, baseline drift, and band correlation—into the training loss function of the generative adversarial network, the generator not only strives for the statistical distribution of the synthesized spectrum to be consistent with the real spectrum during the optimization process, but also forces the synthesized spectrum to satisfy the inherent physical laws of near-infrared spectroscopy. The smoothness constraint ensures that the spectral curve is continuous and smooth, avoiding the jagged noise and abnormal fluctuations commonly found in traditional GAN generation results; the continuity constraint limits the reflectance jumps between adjacent bands through Huber loss, preventing physically impossible abrupt peaks; the curvature constraint controls the local curvature of the spectrum, making the generated peaks and troughs conform to the shape of real absorption characteristics; the baseline drift constraint effectively suppresses the overall baseline shift of the spectrum, maintaining the comparability of the generated spectrum with the real spectrum at the absolute value level; and the band correlation constraint maintains the necessary correlation structure between bands by matching the prior correlation matrix. The synergistic effect of the above constraints not only expands the training set in quantity but also ensures that the generated low-activity samples have physical rationality in quality, thereby significantly improving the generalization ability and robustness of the discrimination model under imbalanced sample conditions.
[0010] Furthermore, the training loss function of the generative adversarial network also includes a consistency loss term, which is composed of a weighted sum of additive noise robustness loss and wavelength shift robustness loss. The additive noise robustness loss is the expectation of the square of the L2 norm of the difference between the synthesized spectral data generated by the generator before and after adding Gaussian noise to the input latent variable. The wavelength shift robustness loss is the sum of the expectations of the square of the L2 norm of the difference between the synthesized spectral data after shifting the synthesized spectral data by one band in the long-wave direction and by one band in the short-wave direction, respectively, and the synthesized spectral data before the shift.
[0011] The beneficial effects of adopting the above-mentioned further technical solutions are as follows: The introduction of the consistency loss term enhances the robustness of the generator to input disturbances and measurement noise. In actual near-infrared spectral acquisition, electronic noise of the spectrometer, ambient temperature fluctuations, and slight changes in sample placement can all introduce uncertainties into the spectral data. The additive noise robustness loss constrains the consistency of the generator's output before and after adding Gaussian noise to the input latent variable, making the generator locally smooth in the latent variable space, avoiding drastic output fluctuations caused by small input changes, and ensuring the stability of the generated spectrum. The wavelength shift robustness loss addresses the wavelength registration deviation that may occur during spectral acquisition. By constraining the output consistency of the spectrum before and after shifting by one band, the generator becomes insensitive to small shifts in wavelength direction, enhancing the applicability of the generated spectrum in actual measurement environments. The combined effect of these two robustness constraints ensures that the synthesized spectral data generated by the generator can maintain a stable spectral shape when facing various disturbances in actual detection, further improving the reliability and generalization performance of the discrimination model in practical application scenarios.
[0012] Furthermore, the band grouping attention module divides the input spectrum into multiple physically meaningful subgroups based on the wavelength range of the near-infrared spectrum, and assigns learnable attention weights to each subgroup. These subgroups are: the first subgroup corresponds to the wavelength range of 940nm to 990nm, the second subgroup corresponds to the wavelength range of 1140nm to 1230nm, the third subgroup corresponds to the wavelength range of 1410nm to 1540nm, and the fourth subgroup corresponds to the remaining wavelength ranges. Average pooling is performed on each subgroup to obtain a group-level feature representation. A learnable attention weight scalar is assigned to each subgroup, which is then normalized by softmax and multiplied by the corresponding group-level feature representation to obtain a weighted fused feature vector.
[0013] The beneficial effects of adopting the above-mentioned further technical solution are as follows: The band grouping attention module, by dividing spectral wavelengths into subgroups with clear chemical meanings, directly embeds prior spectroscopic knowledge into the deep convolutional neural network model, overcoming the fundamental defect of poor physical interpretability in traditional deep learning methods. 940-990nm corresponds to the lipid region, 1140-1230nm to the CH bond vibration region, and 1410-1540nm to the combined absorption region of water, protein, and starch. The chemical information of these bands is closely related to seed vigor. By assigning learnable attention weights to each subgroup, the model can adaptively adjust the degree of attention to different chemical information regions during training, giving greater weight to bands highly correlated with seed vigor discrimination, while suppressing interference from irrelevant regions. Compared to the traditional global attention mechanism, this grouping method preserves the local continuity and chemical correlation between bands, not only improving discrimination accuracy but also making the model's decision-making process interpretable; that is, the chemical basis for the model's judgment of seed vigor can be understood by observing the distribution of attention weights.
[0014] Furthermore, the statistical feature vector extracted by the statistical feature extraction branch includes at least one of the following features: the mean, standard deviation, and skewness of the full-band spectral reflectance, as well as the low-frequency energy ratio or the amplitude of the main peak in the frequency domain extracted after fast Fourier transform; the gated fusion mechanism dynamically calculates the fusion weights of deep features and statistical feature vectors based on the input samples through a lightweight sub-network.
[0015] The beneficial effects of adopting the above-mentioned further technical solutions are as follows: the statistical feature extraction branch and the backbone network form a multi-perspective representation of spectral data. The backbone network extracts local waveform features and deep abstract semantic features of the spectrum through convolution operations, and is adept at capturing subtle waveform changes related to the absorption peaks of chemical components; while the statistical feature extraction branch calculates statistical quantities such as mean, standard deviation, and skewness from a global perspective, reflecting the overall absorption level, dispersion, and distribution symmetry of the spectrum. These macroscopic characteristics are closely related to the overall chemical composition and physical structure of the seeds. The frequency domain features extracted by the Fast Fourier Transform reveal the periodic information of the spectrum. The above two feature perspectives are naturally complementary: deep features focus on local details, while statistical features grasp the overall outline. Through the gating fusion mechanism, the model can dynamically calculate the fusion weights according to the specific characteristics of each input sample, realizing the adaptive combination of features. This ensures that the final fusion features used for discrimination retain both local discrimination information and global distribution information, thereby significantly improving the discrimination accuracy and adaptability to different types of samples.
[0016] Furthermore, the generator in the generative adversarial network includes a fully connected layer and multiple one-dimensional transposed convolutional layers to progressively upsample random latent variables into synthetic spectral data; the discriminator in the generative adversarial network includes multiple one-dimensional convolutional layers and a fully connected layer to output a authenticity score for the input spectrum.
[0017] The beneficial effects of adopting the above-mentioned further technical solution are as follows: The generator, with its structure design of fully connected layers combined with one-dimensional transposed convolutional layers, can efficiently upsample low-dimensional random latent variables into 128-dimensional synthetic spectral data consistent with the dimensions of the real spectrum. The fully connected layer first maps the 100-dimensional latent variables to a high-dimensional feature space, providing a rich feature representation foundation for subsequent upsampling; multiple one-dimensional transposed convolutional layers gradually increase the spatial dimension of the feature map, realizing the progressive refinement of generation from abstract features to specific spectral waveforms. Each transposed convolutional layer can adjust the local details of the spectrum at different scales, giving the generated spectrum a natural hierarchical structure. The discriminator uses multiple one-dimensional convolutional layers to progressively extract multi-level deep features from the input spectrum, with the number of channels increasing from 64 to 512, and the receptive field gradually expanding. This allows for progressive abstraction from local waveforms to global patterns, and finally, the fully connected layer outputs a realism score. This adversarial structural design allows the generator and discriminator to compete and evolve together during training, ultimately enabling the generator to produce high-quality synthetic spectral data that is indistinguishable from real ones.
[0018] 2) In a second aspect, the present invention also provides a non-destructive testing system for maize seed vigor based on near-infrared spectroscopy, including a hardware platform and a software system deployed in the hardware platform; The hardware platform includes a near-infrared spectroscopy acquisition module, a sample carrying and transport module, and an embedded control system; The spectral acquisition module includes a spectrometer, a fiber optic probe, and a light source. The light source includes at least two halogen lamps, symmetrically installed on both sides of the detection area at a 45° angle to the horizontal plane, used to provide uniform near-infrared incident light to the corn seeds to be tested. The spectrometer is used to receive the near-infrared light reflected by the corn seeds to be tested through the fiber optic probe and convert it into raw spectral data. The sample carrying and transport module is used to carry the corn seeds to be tested and transport them sequentially to the detection position; the embedded control system is electrically connected to the spectral acquisition module and the sample carrying and transport module, and is used to run the software system and control the coordinated work of each module according to the instructions of the software system; The software system includes a data acquisition and control module, a combined preprocessing module, a model dynamic loading and inference module, a data management module, and a batch detection and report generation module. The data acquisition and control module configures the spectrometer parameters and communicates with the lower-level machine via a serial port, executing spectral acquisition after receiving a photoelectric trigger signal. The combined preprocessing module preprocesses the raw spectral data. The model dynamic loading and inference module loads the trained seed vigor discrimination model, performs inference on the preprocessed spectral data, and outputs the vigor discrimination results for the maize seeds to be tested. The data management module automatically saves the acquired spectral data, preprocessing parameters, prediction results, and acquisition time to a local historical record library. The batch detection and report generation module loads spectral data files in batches with one click and automatically generates detection reports. The trained seed vigor discrimination model is obtained by training any of the non-destructive detection methods for maize seed vigor based on near-infrared spectroscopy in the first aspect.
[0019] The beneficial effects of the non-destructive detection method and system for maize seed vigor based on near-infrared spectroscopy provided by this invention are as follows: This invention utilizes a generative adversarial network with multiple physical constraints (smoothness, continuity, curvature, baseline drift, and band correlation) to ensure that the generated synthetic spectral data conforms to the physical laws of spectroscopy. This effectively expands the number of low-viability samples, alleviates overfitting under imbalanced conditions, and improves the generalization ability of the seed viability discrimination model. The band-grouping attention module divides the input spectrum into four physically meaningful subgroups (940-990nm lipid region, 1140-1230nm CH region, 1410-1540nm water / protein / starch region, and supplementary bands) based on the wavelength range of the near-infrared spectrum. Learnable attention weights are assigned to each subgroup, enabling the deep convolutional neural network model to adaptively enhance the contribution of key chemical information regions to the viability discrimination results. This overcomes the shortcomings of existing models, such as poor physical interpretability and insufficient attention to key bands. The statistical feature extraction branch extracts statistical feature vectors such as mean, standard deviation, skewness, and FFT frequency domain features from the input spectrum. These vectors are then adaptively weighted and fused with the deep features extracted by the backbone network through a gated fusion mechanism. This supplements the macroscopic distribution characteristics of the spectrum from a global perspective, complementing local waveform features and improving the accuracy and robustness of vigor determination. The system integrates a symmetrical 45° halogen lamp light source, a mechanical baffle photoelectric trigger positioning system, a programmable preprocessing chain, and an automated hardware platform for dynamic model loading. This achieves software and hardware decoupling and a high degree of automation in the detection process, significantly improving the accuracy, generalization ability, and system practicality of maize seed vigor determination even under imbalanced sample conditions.
[0020] Furthermore, the sample carrying and transport module includes a replaceable sample tray, a sliding platform, mechanical baffles, and a photoelectric sensor. The sample tray has multiple independent grooves, each for placing a single corn seed to be tested. The sample tray is fixed to the sliding platform by positioning pins and a magnetic suction device. A row of mechanical baffles is fixedly installed on the side of the sliding platform, the number of which is the same as the number of independent grooves, and their installation positions are aligned with the central axis of each independent groove. The photoelectric sensor is fixedly installed at the detection position. When the sliding platform moves the sample tray to the detection position, the corresponding mechanical baffle enters the U-shaped groove of the photoelectric sensor and blocks the light path. The photoelectric sensor outputs a hardware interrupt signal to the embedded control system. Upon receiving the hardware interrupt signal, the embedded control system immediately stops the movement of the sliding platform and sends a position command to the host computer via a serial port. After receiving the position command, the host computer calls the near-infrared spectral acquisition module to complete the spectral acquisition of a single seed, and sends a confirmation signal to the host computer after the acquisition is completed, causing the sliding platform to continue moving to the next detection position. The embedded control system uses the actual photoelectric trigger signal as the basis for each stop and acquisition.
[0021] The beneficial effects of adopting the above-mentioned further technical solution are as follows: Through a physical triggering method combining a mechanical baffle and a photoelectric sensor, when the sliding platform moves the sample tray, the mechanical baffle enters the U-shaped groove of the photoelectric sensor and blocks the light path. The photoelectric sensor outputs a hardware interrupt signal to the embedded control system. Using the actual photoelectric trigger signal as the basis for each stop and acquisition avoids the cumulative error caused by relying on preset steps or time, thus improving the positioning accuracy of a single seed reaching the detection position. Upon receiving the hardware interrupt signal, the embedded control system immediately stops the movement of the sliding platform and sends a positioning command to the host computer via serial port. After receiving the positioning command, the host computer calls the near-infrared spectral acquisition module to complete the spectral acquisition of a single seed. After acquisition, it sends a confirmation signal to the host computer, causing the sliding platform to continue moving to the next detection position, achieving fully automatic continuous detection. The sample tray is fixed to the sliding platform by positioning pins and a magnetic suction device, facilitating quick replacement of sample trays with different groove specifications to accommodate different varieties of corn seeds to be tested.
[0022] Furthermore, the combined preprocessing module provides a variety of preprocessing methods, including standard normal variable transformation, multivariate scattering correction, derivative transformation, and Savitzky-Golay smoothing. Users can select multiple methods and freely sort them to form a combined preprocessing chain to perform chained processing on the original spectral data. The combined preprocessing module also supports real-time preview of the comparison between the original spectral curve and the preprocessed spectral curve during the processing.
[0023] The beneficial effects of adopting the above-mentioned further technical solutions are as follows: The combined preprocessing module provides multiple preprocessing methods, including standard normal variable transformation, multivariate scattering correction, derivative transformation, and Savitzky-Golay smoothing. Users can select multiple methods and freely sort them to form a combined preprocessing chain, performing chain-like processing on the original spectral data. This allows for flexible configuration of the optimal preprocessing workflow for maize seed spectral data of different sources and qualities, adapting to the diversity of noise types, scattering levels, and baseline drift levels in the spectral data. Through multiple selections and free sorting, users can adjust the execution order of preprocessing methods according to the specific characteristics of the spectral data, maximizing the effectiveness of each preprocessing method at different stages. Real-time preview of the comparison between the original and preprocessed spectral curves allows users to intuitively evaluate the impact of different preprocessing combinations on spectral morphology. This facilitates users in selecting the optimal preprocessing combination based on the smoothness of the spectral curve, the retention of characteristic peaks, and the baseline correction effect, improving the transparency and controllability of the preprocessing process and providing high-quality input spectral data for subsequent seed vigor discrimination models.
[0024] Furthermore, the model dynamic loading and inference module has a unified model loading interface, which allows users to select and load the trained seed viability discrimination model file from external storage devices; The model dynamic loading and inference module automatically identifies the deep learning framework type corresponding to the model file by analyzing the file extension; the deep learning framework type includes at least one of the Scikit-learn framework, Keras framework, PyTorch framework and ONNX framework. Based on the identified framework type, the model dynamic loading and inference module dynamically loads the runtime environment that matches the framework and parses the model file into a discriminative model instance that can be called.
[0025] The beneficial effects of adopting the above-mentioned further technical solutions are as follows: The model dynamic loading and inference module has a unified model loading interface, supporting users to select and load trained seed viability discrimination model files from external storage devices. This eliminates the need for users to use different loading methods for different model formats, reducing operational complexity. By analyzing the model file extension, the system automatically identifies the deep learning framework type corresponding to the model file. Deep learning framework types include at least one of the following: Scikit-learn, Keras, PyTorch, and ONNX. This allows users to load models without manually specifying the framework type. This design enables users to flexibly select seed viability discrimination models trained under different deep learning frameworks according to their actual needs, without format conversion, reducing operational steps and lowering the barrier to entry. Attached Figure Description
[0026] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments of the present invention will be briefly introduced below: Figure 1 This is a schematic flowchart of a non-destructive detection method for maize seed vigor based on near-infrared spectroscopy according to an embodiment of the present invention. Figure 2 A schematic diagram of the structure of a Generative Adversarial Network (GAN) for physical constraints; Figure 3 This is a schematic diagram of the structure of a deep convolutional neural network model; Figure 4 This is one of the structural schematic diagrams of a non-destructive testing system for maize seed vigor based on near-infrared spectroscopy according to an embodiment of the present invention; Figure 5 This is a schematic diagram of the main interface of the software system. Figure 6 This is a schematic diagram of the main interface of the software system during runtime. Figure 7 This is one example of an exported test report; Figure 8 Example 2 of the exported test report; Figure 9This is a second schematic diagram of a non-destructive testing system for maize seed vigor based on near-infrared spectroscopy, according to an embodiment of the present invention. Figure 10 This is an enlarged view of the sample carrying and transport unit. Detailed Implementation
[0027] The principles and features of the present invention are described below. The examples given are only for explaining the present invention and are not intended to limit the scope of the present invention.
[0028] The technical solution of the present invention and how the technical solution of the present invention solves the above-mentioned technical problems are described in detail below with specific embodiments. These specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments. The embodiments of the present invention will now be described with reference to the accompanying drawings.
[0029] like Figure 1 As shown in the figure, an embodiment of the present invention provides a non-destructive detection method for maize seed vigor based on near-infrared spectroscopy, comprising: S1. Collect raw near-infrared spectral data of naturally aged corn seeds, and conduct a standard germination test on each naturally aged corn seed to obtain a viability label for each naturally aged corn seed. The specific implementation process is as follows: S10. Corn seeds from different origins and years, harvested and stored under warehouse conditions, undergoing a viability decline process, were selected as samples. Due to differences in storage time and environment, the viability levels of these naturally aged corn seeds exhibit natural differentiation. The reflectance spectra of each naturally aged corn seed were collected individually using a near-infrared spectrometer. The near-infrared spectrometer parameters were set as follows: the spectral acquisition range covered 939.3 nm to 1665.74 nm, and each scanned spectrum contained 128 bands. Multiple repeated acquisitions were performed on each naturally aged corn seed, and the arithmetic mean of the multiple acquisition results was taken to obtain the raw near-infrared spectral data of that naturally aged corn seed.
[0030] To eliminate the influence of ambient light variations and instrument dark current, and to improve the stability and comparability of spectral data, black-and-white calibration was performed on the raw data. The calibration calculation formula is as follows: in, The corrected reflectance spectrum, The raw spectral data acquired by the instrument. The whiteboard reference spectrum is used. This serves as the blackboard reference spectrum. This correction process eliminates the effects of light source inhomogeneity and background noise, normalizing the spectral data to a uniform scale range. The resulting reflectance spectrum is the original near-infrared spectral data, which retains all the original information generated by the interaction between near-infrared light and hydrogen-containing groups in the organic molecules inside the seed.
[0031] S11. After spectral acquisition, each naturally aged corn seed was transferred to a standard germination test environment. Following international seed testing procedures, the seeds were placed on moist germination paper and germinated in a germination chamber at a constant temperature of 25 degrees Celsius for 7 days. At the end of the 7th day, the germination status of each seed was checked individually. Seeds with shoot and root lengths greater than the seed length and normal embryo development without deformities were classified as normally germinating seeds and assigned a high-viability tag. Seeds that did not germinate, or those that showed signs of germination but whose shoot and root lengths did not reach the seed length, or whose embryos showed abnormal growth, were classified as abnormal seeds and assigned a low-viability tag. Thus, each naturally aged corn seed obtained a raw near-infrared spectral data and a uniquely corresponding viability tag, forming a complete sample unit.
[0032] S2. Construct a generative adversarial network with constraints. Train the generative adversarial network using raw near-infrared spectral data. After training, use the generator in the trained generative adversarial network with constraints to generate synthetic spectral data. The generative adversarial network is constructed based on the WGAN-GP framework. The training loss function includes a spectral physical constraint loss term, which is composed of a weighted sum of smoothness constraint loss term, continuity constraint loss term, curvature constraint loss term, baseline drift constraint loss term, and band correlation constraint loss term. The Generative Adversarial Network (GAN) is built on the WGAN-GP framework and consists of a generator and a discriminator. The generator includes fully connected layers and multiple one-dimensional transposed convolutional layers to progressively upsample random latent variables into synthetic spectral data. The random latent variables are sampled from their prior distribution. The generator maps these latent variables into high-dimensional feature vectors through fully connected layers, and then progressively increases the spatial dimension of the feature map through multiple one-dimensional transposed convolutional layers, ultimately outputting synthetic spectral data with dimensions consistent with the real spectra. The discriminator includes multiple one-dimensional convolutional layers and a fully connected layer, outputting a authenticity score for the input spectrum. The input spectrum can be real spectral data or synthetic spectral data output by the generator. The discriminator progressively extracts multi-level deep features from the input spectrum through multiple one-dimensional convolutional layers, and finally outputs a scalar value as the authenticity score through the fully connected layer. This score represents the discriminator's confidence level in classifying the input spectrum as real spectral data rather than synthetic spectral data.
[0033] The generative adversarial network (GAN) was trained using raw near-infrared spectral data. Training employed an alternating optimization approach: in each training iteration, the generator parameters were fixed while the discriminator parameters were updated, and then the discriminator parameters were fixed again while the generator parameters were updated. The discriminator's training loss function consisted of Wasserstein distance and a gradient penalty term, forcing the discriminator to satisfy the Lipschitz continuity condition in the interpolation region between real and generated samples, ensuring training stability. The generator's training loss function consisted of a weighted sum of three parts: an adversarial loss term, a spectral physical constraint loss term, and a consistency loss term. In each training iteration, the generator calculated its loss value based on the training loss function and updated all network parameters using backpropagation. Training continued for multiple iterations, and the GAN training was complete when the training loss function converged to a stable value.
[0034] Synthetic spectral data is generated using a generator in a trained generative adversarial network (GAN). After training, the generator's network parameters remain fixed. New latent variables are randomly sampled from the prior distribution of latent variables and fed into the trained generator. The generator then sequentially upsamples the data through a fully connected layer for high-dimensional mapping and multiple one-dimensional transposed convolutional layers, ultimately outputting synthetic spectral data. Each batch of newly sampled latent variables corresponds to a batch of synthetic spectral data, with the number of bands and wavelength range of the synthetic spectral data matching the original near-infrared spectral data.
[0035] During the training of a generative adversarial network, the spectral physical constraint loss term in the generator's training loss function is a weighted sum of smoothness constraint loss term, continuity constraint loss term, curvature constraint loss term, baseline drift constraint loss term, and band correlation constraint loss term, as detailed below: 1) The smoothness constraint loss term penalizes the second derivative of the generated spectrum, ensuring good smoothness. The formula for this loss term is: in, Represents the smoothness constraint loss term. This represents the mathematical expectation of a batch of generated samples. To generate the spectrum in the first Reflectance values for each band, and The first The and the first Reflectance values for each band, The formula takes the expected value after summing the squares of the second-order differences at each band of the generated spectrum. The larger the second-order difference value, the more drastically the spectral curve bends at that point. By minimizing this loss term, the reflectance values of the generated spectrum are forced to transition smoothly at each band.
[0036] 2) The continuity constraint loss term uses Huber loss to limit reflectance variations between adjacent bands, preventing anomalous jumps in the generated spectrum. The formula for this loss term is: in, This represents the loss term due to continuity constraints. The Huber loss function is defined as follows: in, The difference in reflectivity between adjacent bands, i.e. , express The absolute value of the Huber loss. When the difference in reflectivity between adjacent bands is small, the square loss is used for fine constraint. When the difference is large, it is converted to linear loss to suppress accidental large jumps.
[0037] 3) The curvature constraint loss term is used to limit the local curvature of the generated spectrum. The formula for calculating this loss term is: in, This represents the curvature constraint loss term. The absolute value operator is used. This formula measures the degree of local curvature by calculating the ratio of the absolute value of the second derivative of the spectrum to the first derivative correction term. The first derivative correction term in the denominator ensures that the measurement of curvature by the loss term remains stable under different slopes, avoiding excessive penalty for normal curvature transitions in high-slope regions.
[0038] 4) The baseline drift constraint loss term is used to suppress the overall baseline drift of the spectrum. The formula for calculating this loss term is: in, This represents the baseline drift constraint loss term. To generate spectral vectors, The baseline vector is obtained by linear interpolation of the two endpoints of the spectrum. Let L2 be the squared norm of the vector. This formula calculates the expectation of the squared L2 of the difference between the generated spectral vector and the linear interpolation baseline vector. By minimizing this loss term, the overall baseline level of the generated spectrum is forced to approximate the linear baseline determined by the two endpoints.
[0039] 5) The band correlation constraint loss term is used to match the band correlation of the generated spectrum with the prior correlation matrix. The formula for calculating this loss term is: in, This represents the band correlation constraint loss term. This is the mean squared error function, used to calculate the mean squared value of the difference between two matrices. This is a Pearson correlation coefficient matrix operation used to calculate the pairwise Pearson correlation coefficients between each band in the batch-generated sample matrix. This is a matrix containing batch-generated samples, where each row corresponds to a generated spectral sample and each column corresponds to a wavelength band. This is the Gaussian attenuation prior correlation matrix based on band distance. This formula calculates the mean square error between the band correlation coefficient matrix of the generated spectrum and the prior correlation matrix. By minimizing this loss term, the generated spectrum maintains the proper correlation structure between bands.
[0040] The discriminator, a component of the constrained generative adversarial network (GAN), is responsible for distinguishing whether the input spectrum is real spectral data or synthetic spectral data output by the generator. The discriminator consists of multiple one-dimensional convolutional layers and one fully connected layer. The convolutional layers progressively extract multi-level deep features from the input spectrum, while the fully connected layer compresses these features into a scalar value as a authenticity score. The magnitude of the authenticity score indicates the discriminator's confidence level in classifying the input spectrum as real spectral data rather than synthetic spectral data.
[0041] Among them, the WGAN-GP framework is a variant of the Wasserstein generative adversarial network with gradient penalty. The WGAN-GP framework uses the Wasserstein distance to measure the distance between the real distribution and the generated distribution, and forces the discriminator to satisfy the Lipschitz continuity condition through the gradient penalty term, avoiding the training instability problem introduced by weight pruning, and improving the convergence and generation quality of generative adversarial network training.
[0042] The prior distribution of latent variables is the sampling source distribution of the random latent variables input to the generator. The prior distribution of latent variables typically adopts a standard normal distribution or a uniform distribution. During training and generation, the input latent variables are randomly sampled from the prior distribution, and different sampled values correspond to different forms of synthetic spectral data.
[0043] The spectral physical constraint loss term is a component of the generator training loss function. It is a weighted sum of smoothness constraint loss terms, continuity constraint loss terms, curvature constraint loss terms, baseline drift constraint loss terms, and band correlation constraint loss terms. The spectral physical constraint loss term transforms prior knowledge of near-infrared spectral waveform characteristics in the field of spectroscopy into differentiable mathematical constraints, embedding them into the generator's optimization objective. This allows the generator to actively satisfy these physical constraints during the generation of synthetic spectral data.
[0044] The consistency loss term is a component of the generator training loss function, used to measure the generator's output consistency in response to input perturbations and spectral wavelength shifts. The consistency loss term consists of two parts: additive noise robustness loss and wavelength shift robustness loss. By simultaneously constraining the generator's stability in both the latent variable space and the spectral wavelength direction, it improves the quality and generalization ability of the synthesized spectral data.
[0045] The additive noise robustness loss is a sub-term of the consistency loss term, measuring the degree of difference between the synthesized spectral data output by the same generator before and after adding Gaussian noise to the input latent variables. The degree of difference is quantitatively described by the expectation of the squared L2 norm of the difference between the two output spectral vectors. The additive noise robustness loss constrains the local smoothness of the generator in the latent variable space.
[0046] The wavelength shift robustness loss is a sub-term of the consistency loss term, measuring the degree of difference between the synthesized spectral data output by the generator and the original synthesized spectral data after wavelength shift by one band. The degree of difference is quantitatively described by the sum of the expected sums of the squares of the L2 norms of the differences between the two spectral vectors before and after the shift. The wavelength shift robustness loss constrains the local translation robustness of the generated spectrum in the wavelength dimension.
[0047] Synthetic spectral data is artificially generated by a trained generator using randomly input latent variables. The synthetic spectral data has the same statistical distribution as the original near-infrared spectral data and satisfies physical constraints such as smoothness, continuity, and band correlation in near-infrared spectra. Synthetic spectral data is used to augment the original near-infrared spectral data, constructing an enhanced spectral dataset.
[0048] The training loss function of the generative adversarial network also includes a consistency loss term, which is a weighted sum of additive noise robustness loss and wavelength shift robustness loss. The additive noise robustness loss is the expectation of the square of the L2 norm of the difference between the synthesized spectral data generated by the generator before and after adding Gaussian noise to the input latent variable. The wavelength shift robustness loss is the sum of the expectations of the square of the L2 norm of the difference between the synthesized spectral data after shifting it one band in the long-wave direction and one band in the short-wave direction, respectively, and the synthesized spectral data before the shift.
[0049] In a training iteration, a batch of input latent variables is first sampled from the prior distribution of latent variables. These latent variables are then fed into a generator, which outputs synthesized spectral data. Gaussian noise is then added to the same input latent variables to obtain perturbed latent variables. These perturbed latent variables are then fed back into the same generator, which outputs perturbed synthesized spectral data. The difference between the synthesized spectral data and the perturbed synthesized spectral data is calculated, and the squared L2 norm of this difference is calculated. The expected value of this difference over all samples in the batch is then taken to obtain the additive noise robustness loss. The mathematical expression for the additive noise robustness loss is: in, This indicates the additive noise robustness loss. Indicates the prior distribution of the latent variable Input latent variables of medium sampling And from a mean of 0 and a standard deviation of Gaussian distribution Medium-sampled Gaussian noise Find the expected value. Represents a generator. This indicates that the generator takes latent variables as input. To input the generated synthetic spectral data, The generator represents the latent variables after adding Gaussian noise. The input is the perturbed synthetic spectral data. This represents the squared L2 norm of the vector. The smaller the value of the additive noise robustness loss, the less sensitive the generator is to small changes in the input latent variables, and the more stable its generation ability.
[0050] In a training iteration, the generator first generates synthetic spectral data using the input latent variables as input, and then performs two translation operations on the synthetic spectral data. The first translation operation shifts each band of the entire synthetic spectral data one band towards longer wavelengths, from the original band located at the [missing band]. The reflectance value of the band shifts to the band of... The first band, or the gap created at the beginning or end by the translation, is filled with the value of the adjacent band. The second translation operation shifts the entire synthesized spectral data one band towards shorter wavelengths. The reflectance value of the band shifts to the band of... Each wavelength band is analyzed. The L2 norm squared is calculated for the difference between the synthesized spectral data before and after translation. This L2 norm is calculated separately for each translation direction and then summed. The expected value is then taken for a batch of samples to obtain the wavelength shift robustness loss. The mathematical expression for the wavelength shift robustness loss is: in, This indicates the loss of robustness to wavelength shift. Indicates the prior distribution of the latent variable Input latent variables of medium sampling Find the expected value. Represents a generator. This indicates that the generator takes latent variables as input. To input the generated synthetic spectral data, This indicates that the synthesized spectral data will be used. The spectral data obtained by shifting one band towards longer wavelengths. This indicates that the synthesized spectral data will be used. The spectral data obtained by shifting one band towards the shortwave direction This represents the squared L2 norm of the vector. This formula calculates the expected value of the sum of the squared L2 norms of the differences between the synthesized spectral data before and after the two translation directions. A smaller wavelength shift robustness loss indicates better local translation consistency in the wavelength direction of the synthesized spectral data generated by the generator.
[0051] The consistency loss term is formed by weighted summation of the additive noise robustness loss and the wavelength shift robustness loss. The mathematical expression for the consistency loss term is: in, Represents the consistency loss term. This indicates the additive noise robustness loss. This indicates the loss of robustness to wavelength shift. and These are the weighting coefficients corresponding to the additive noise robustness loss and the wavelength shift robustness loss, respectively. The weighting coefficients are preset hyperparameters, set before training begins and remaining constant throughout the training process.
[0052] Construct the complete training loss function for the generator. The generator's training loss function consists of a weighted sum of three parts: an adversarial loss term, a spectral physical constraint loss term, and a consistency loss term. The mathematical expression for the complete generator training loss function is: in, This represents the generator training loss function. Indicates the counter-loss term. Represents the spectral physical constraint loss term. Represents the consistency loss term. , , These are the weight coefficients for the adversarial loss term, the spectral physical constraint loss term, and the consistency loss term, respectively. The weight coefficients are set before training begins and remain unchanged during training.
[0053] In each training iteration, the generator calculates its loss value based on the generator training loss function described above, and updates all network parameters of the generator using the backpropagation algorithm. Training continues for multiple iterations until the generator training loss function converges to a stable value.
[0054] S3. Merge the original near-infrared spectral data with the synthesized spectral data to construct an enhanced spectral dataset. Preprocess the enhanced spectral dataset to obtain a preprocessed spectral dataset. The specific implementation process is as follows: The raw near-infrared spectral data and synthetic spectral data were merged to construct an enhanced spectral dataset. Two parts of spectral data were obtained: the first part was the raw near-infrared spectral data, derived from spectral measurements of naturally aged corn seeds, with each raw near-infrared spectral data line having a corresponding vitality label; the second part was the synthetic spectral data, generated by a generator in a trained generative adversarial network with a constraint mechanism, with the same number of bands and wavelength range as the raw near-infrared spectral data. The merging operation used a direct merging method, placing all samples from the raw near-infrared spectral dataset and all samples from the synthetic spectral dataset into the same dataset. The synthetic spectral data did not carry vitality labels during generation; during merging, vitality labels were assigned to each synthetic spectral data line by assigning a value consistent with the low-vitality sample category in the raw near-infrared spectral dataset, thus supplementing the low-vitality sample category. After merging, each sample in the enhanced spectral dataset contained a 128-dimensional spectral data line and a corresponding vitality label. The total number of samples in the enhanced spectral dataset was greater than the number of samples in the raw near-infrared spectral dataset, and the number of samples in the low-vitality sample category was expanded.
[0055] The enhanced spectral dataset is preprocessed to obtain the preprocessed spectral dataset. The preprocessing involves three operations in sequence: Savitzky-Golay smoothing, standard normal variable transformation, and first derivative processing.
[0056] Savitzky-Golay smoothing performs point-by-point local polynomial fitting along the wavelength dimension for each spectral data point in the enhanced spectral dataset. At each band location, several adjacent bands to the left and right of that band are selected to form a local window. A polynomial of a preset order is used to perform least-squares fitting on the reflectance values within the window. The calculated value of the fitted polynomial at that band location replaces the original reflectance value. The smoothing window size is set to 11 bands, and the polynomial order is set to 2. After processing, high-frequency random noise introduced by the acquisition is suppressed in the spectral data, while the overall contour of the spectral curve is preserved.
[0057] The standard normal transformation (SNR) standardizes each spectral data point independently. For a given spectral data point, it calculates the arithmetic mean and standard deviation of the reflectance values across all 128 bands. This is done by subtracting the arithmetic mean from the reflectance value of each band and then dividing by the standard deviation. The mathematical expression for the standard normal transformation is: in, This represents the spectral data after standard normal transformation. This represents the input spectral data. This represents the arithmetic mean of the reflectance values across all bands of the spectrum. This represents the standard deviation of the reflectance values across all bands of the spectrum. After standard normalization, the overall baseline level of each spectral data point is normalized to zero mean, and the overall amplitude is standardized to unit variance. Baseline shifts and overall intensity differences caused by differences in scattered optical path lengths between samples are eliminated.
[0058] First-order derivative processing employs the Savitzky-Golay convolution method to calculate the first-order derivative of the spectral data after standard normal transformation along the wavelength dimension. The window size used for first-order derivative processing is 11 bands, and the polynomial order is 2. At each band location, the first-order derivative value is obtained by fitting a polynomial to the spectral data within the local window and calculating the first-order derivative of that polynomial. After first-order derivative processing, components related to baseline drift due to slow wavelength changes are filtered out, the slope information of reflectance changes in different bands is enhanced, and the subtle peaks and troughs related to absorption peaks of chemical components in the spectrum are more prominent. After completing the three steps of Savitzky-Golay smoothing, standard normal transformation, and first-order derivative processing, the preprocessed spectral dataset is obtained.
[0059] S4. Construct a deep convolutional neural network model that includes a band grouping attention module and a statistical feature extraction branch. Use the preprocessed spectral dataset and the viability label of each naturally aged corn seed to train and validate the deep convolutional neural network model, resulting in a trained seed viability discrimination model. The band grouping attention module is used to divide the input spectrum into multiple physically meaningful subgroups according to the wavelength range of the near-infrared spectrum, and assign learnable attention weights to each subgroup to enhance the contribution of key chemical information regions to the discrimination results. The statistical feature extraction branch is used to extract statistical feature vectors from the input spectrum and adaptively weightedly fuse them with the deep features extracted by the backbone network of the deep convolutional neural network model through a gating fusion mechanism. The statistical feature extraction branch extracts statistical feature vectors that include at least one of the following features: mean, standard deviation, and skewness of full-band spectral reflectance, as well as the proportion of low-frequency energy or the amplitude of the main peak in the frequency domain extracted after fast Fourier transform; the gated fusion mechanism dynamically calculates the fusion weights of deep features and statistical feature vectors based on the input samples through a lightweight sub-network.
[0060] A deep convolutional neural network model incorporating a band-grouping attention module was constructed. This module, located after the input layer, divides the input spectrum into physically meaningful subgroups based on the wavelength range of the near-infrared spectrum. The input spectrum consists of 128-dimensional preprocessed spectral data, corresponding to 128 bands within the near-infrared spectral acquisition range of 939.3 nm to 1665.74 nm. Based on the correspondence between the wavelength range of the near-infrared spectrum and the absorption peaks of the main chemical components in maize seeds, the 128 bands are divided into four subgroups. The first subgroup corresponds to the wavelength range of 940 nm to 990 nm, which corresponds to the lipid region. The second subgroup corresponds to the wavelength range of 1140 nm to 1230 nm, which corresponds to the carbon-hydrogen bond vibration region. The third subgroup corresponds to the wavelength range of 1410 nm to 1540 nm, which corresponds to the combined absorption region of water, protein, and starch. The fourth subgroup comprises the remaining wavelength ranges, i.e., all bands other than the three subgroups mentioned above.
[0061] Average pooling is performed on each subgroup to obtain the group-level feature representation. The average pooling operation calculates the arithmetic mean of the reflectance values across all bands within each subgroup vector, compressing the subgroup vector into a single scalar value. This scalar value represents the overall spectral response intensity of the wavelength range corresponding to that subgroup. The mathematical expression for average pooling is: in, Indicates the first Group-level feature representation of each subgroup The values are 0, 1, 2, and 3, corresponding to the first, second, third, and fourth subgroups, respectively. Indicates the first The number of bands contained in each subgroup Indicates the first The first subgroup vector The reflectance values of the i-th band, with the summation sign indicating the summation with respect to the i-th band. The reflectance values of all bands within each subgroup are summed. After the calculation is completed, each of the four subgroups generates a group-level feature scalar.
[0062] A learnable attention weight scalar is assigned to each subgroup, and the attention weight scalars of all subgroups are normalized using the softmax function. A learnable attention weight scalar is assigned to the first subgroup. Assign learnable attention weight scalars to the second subgroup Assign learnable attention weight scalars to the third subgroup Assign learnable attention weight scalars to the fourth subgroup These four attention weights are parameters of the deep convolutional neural network model, which are updated and optimized during model training using the backpropagation algorithm. The four attention weights are normalized using the softmax function, the mathematical expression of which is: in, Indicates the first The attention weight scalars of each subgroup after being normalized by the softmax function. Indicates the first The original learnable attention weight scalars for each subgroup The natural exponential function is represented by the sum of the exponential functions of the original learnable attention weight scalars for all four subgroups. The four normalized attention weight scalars satisfy the constraint that their sum is 1, representing the relative contribution of the four wavelength regions to the discrimination result.
[0063] Multiply the normalized attention weight scalar by the corresponding group-level feature representation to obtain the weighted fused feature vector. Then, multiply the normalized attention weight scalar of the first subgroup... Group-level feature representation of the first subgroup Multiply by the normalized attention weight scalar of the second subgroup. Group-level feature representation of the second subgroup Multiply by the normalized attention weight scalar of the third subgroup. Group-level feature representation of the third subgroup Multiply by the normalized attention weight scalar of the fourth subgroup. Group-level feature representation of the fourth subgroup Multiplying the four products and combining them into a single four-dimensional vector yields the weighted and fused feature vector. The mathematical expression for the weighted and fused feature vector is: in, This represents the weighted fused feature vector, with a dimension of 4, and the superscript... This indicates a transpose operation. In the weighted fused feature vector, dimensions with larger values contribute more to the wavelength region affecting the discrimination result, while dimensions with smaller values contribute less to the wavelength region affecting the result.
[0064] A deep convolutional neural network model incorporating a statistical feature extraction branch is constructed. This branch extracts statistical feature vectors from the input spectrum. The input spectrum is 128-dimensional spectral data before weighting by the band-grouping attention module. The statistical feature extraction branch calculates the mean, standard deviation, and skewness of the full-band spectral reflectance. The formula for calculating the mean is: in, This represents the average reflectance across the entire spectral band. This represents the total number of bands, with a value of 128. For the first The reflectance values for each band. The formula for calculating the standard deviation is: in, The standard deviation of reflectance across the entire spectral band. This represents the average reflectance across the entire spectral band. For the first Reflectance values for each band, This represents the total number of bands. The formula for calculating skewness is: in, The skewness of the reflectance across the entire spectral band. This represents the average reflectance across the entire spectral band. The standard deviation of reflectance across the entire spectral band. For the first Reflectance values for each band, This represents the total number of bands.
[0065] The statistical feature extraction branch further extracts the proportion of low-frequency energy after Fast Fourier Transform (FFT). FFT is performed on the spectral data to convert the time-domain spectral signal into a frequency-domain signal, and the proportion of low-frequency energy in the total energy is calculated to obtain the low-frequency energy proportion feature. The mean, standard deviation, skewness, and low-frequency energy proportion are combined to form a statistical feature vector.
[0066] The statistical feature extraction branch adaptively weights and fuses the deep features extracted by the backbone network of the deep convolutional neural network model through a gated fusion mechanism. The backbone network adopts an Inception-ResNet structure, extracting deep feature vectors from the input spectrum at multiple scales. The gated fusion mechanism dynamically calculates the fusion weights of the deep features and statistical feature vectors based on the input samples through a lightweight sub-network. This lightweight sub-network takes the statistical feature vectors as input, maps their dimension to 2D through a fully connected layer, and then normalizes them using a softmax function, resulting in two weight values corresponding to the fusion weights of the deep features and the statistical feature vectors, respectively. The mathematical expression for the gated fusion mechanism is: in, It is a 2-dimensional gated weight vector, containing deep feature fusion weights and statistical feature vector fusion weights. For the softmax function, This is the weight matrix of the fully connected layer in the lightweight subnetwork. For statistical feature vectors, This represents the bias vector of the fully connected layer in the lightweight subnetwork. Based on the calculated gate weight vector, the deep feature vector and the statistical feature vector are weighted and summed to obtain the fused feature.
[0067] A deep convolutional neural network model was trained using a preprocessed spectral dataset and the viability labels of each naturally aged corn seed. The preprocessed spectral dataset was randomly divided into training and validation sets in a 7:3 ratio. Stratified sampling was used during the partitioning process to maintain a consistent ratio of high-viability to low-viability samples in both sets. Cross-entropy loss was used as the training loss function, and an L1 regularization term was added to impose sparsity constraints on the attention weights in the band-grouping attention module. The Adam optimizer was used, with a learning rate of 0.001 and a weight decay coefficient of 10. -4 The batch size was set to 32. The number of training epochs was set to 200, and an early stopping strategy was adopted, stopping training when the validation set accuracy did not improve for 10 consecutive epochs. During training, the attention weight scalar of the band grouping attention module was optimized and updated together with other network parameters through the backpropagation algorithm.
[0068] The deep convolutional neural network model is validated to obtain a trained seed viability discrimination model. After each training epoch, the model's performance is evaluated using a validation set, and the accuracy on the validation set is calculated. After training, the model parameters that achieve the highest accuracy on the validation set are selected as the trained seed viability discrimination model.
[0069] Figure 3This paper demonstrates the overall structure of an attention network that integrates statistical features. This network is a deep convolutional neural network model used as a seed viability discrimination model. The network contains two parallel input paths. The input spectrum of the left spectral branch is preprocessed 128-dimensional spectral data. The input spectrum first enters a one-dimensional convolutional layer, Conv1D, with a kernel size of 7, a stride of 2, padding of 3, 1 input channel, and 32 output channels. This layer performs convolution operations along the wavelength dimension to extract shallow features. The convolution result is then passed through a batch normalization layer and the ReLU activation function BatchNorm+ReLU for normalization and non-linear activation. Finally, it is downsampled by a max pooling layer with a kernel size of 3, a stride of 2, and padding of 1. The downsampled feature map enters the Inception-1D module, which contains multiple parallel convolutional branches to extract spectral features at different scales. The output of the Inception-1D module enters the Residual-1D block, which contains two one-dimensional convolutions with kernel size 3 and skip connections. The skip connections directly add the input to the output of the second convolution to alleviate the gradient vanishing problem. The Inception-1D module and the Residual-1D block form a repeating unit, which is executed three times consecutively, enabling the network to progressively extract hierarchical details of the spectral data from coarse outlines to fine structures. The output of the last Residual-1D block enters the Adaptive Global Average Pooling layer, AdaptiveAvgPool, which performs average pooling on the feature map along the wavelength dimension, outputting a deep feature vector. This vector is then normalized by Layernorm before being passed to subsequent modules. The input spectrum of the statistical feature branch on the right is the original 128-dimensional spectral data. It first enters a fully connected Linear layer for linear transformation, then undergoes Layernorm normalization. Following this, it sequentially passes through a fully connected Linear layer, a ReLU activation function (ReLU), and a Dropout layer for non-linear activation and random deactivation. It then undergoes another fully connected Linear layer for linear transformation, and finally passes through a Sigmoid activation function to output a statistical feature vector. The deep feature vector output from the spectral branch and the statistical feature vector output from the statistical feature branch jointly enter the gated fusion module. The gated fusion module consists of a fully connected Linear layer, a ReLU activation function (ReLU), and a Dropout layer connected sequentially. A lightweight subnetwork dynamically calculates the fusion weights between the deep features and the statistical feature vector based on the input samples, achieving adaptive weighted fusion.The fused feature vector output by the gated fusion module enters the classifier, which consists of a fully connected Linear layer and an output layer. The fully connected Linear layer maps the fused features to 2D and outputs the original scores of the two categories, corresponding to high vitality and low vitality, respectively. Finally, the vitality discrimination result is output from the output layer.
[0070] S5. After collecting and preprocessing the near-infrared spectral data of the maize seeds to be tested, the data is input into the trained seed vigor discrimination model, and the vigor discrimination results of the maize seeds to be tested are output. The specific implementation process is as follows: Near-infrared spectral data of maize seeds of unknown viability were collected for viability assessment. The near-infrared spectral acquisition range, number of bands, and acquisition parameters used were consistent with those used when acquiring the original near-infrared spectral data. The spectral acquisition range was 939.3 nm to 1665.74 nm, with 128 bands. The arithmetic mean of the data collected from multiple repeated acquisitions of the maize seeds was used as the near-infrared spectral data. The acquired near-infrared spectral data is a 128-dimensional vector, with each dimension representing the reflectance value of the corresponding band.
[0071] The near-infrared spectral data of the maize seeds to be tested were preprocessed. The preprocessing procedure was exactly the same as that for the enhanced spectral dataset, consisting of Savitzky-Golay smoothing, standard normal variable transformation, and first-order derivative processing. After these three preprocessing steps, the preprocessed spectral data was obtained, which was a 128-dimensional vector with the same input format as the trained seed vigor discrimination model.
[0072] The preprocessed spectral data to be tested is input into the trained seed vigor discrimination model. After forward inference, the model outputs the original scores for two categories: high vigor and low vigor. The category with the higher score is output as the vigor discrimination result of the maize seed to be tested.
[0073] In the above embodiments, although the steps are numbered S1, S2, etc., they are only specific embodiments given by the present invention. Those skilled in the art can adjust the execution order of S1, S2, etc. according to the actual situation. The scheme after adjusting the order is also within the protection scope of the present invention. It can be understood that in some embodiments, some or all of the above embodiments may be included.
[0074] like Figure 4 As shown, an embodiment of the present invention provides a non-destructive testing system for maize seed vigor based on near-infrared spectroscopy, comprising a hardware platform and a software system deployed on the hardware platform; The hardware platform includes a near-infrared spectroscopy acquisition module, a sample carrying and transport module, and an embedded control system; The spectral acquisition module includes a spectrometer, a fiber optic probe, and a light source. The light source includes at least two halogen lamps, symmetrically installed on both sides of the detection area at a 45° angle to the horizontal plane, used to provide uniform near-infrared incident light to the corn seeds to be tested. The spectrometer is used to receive the near-infrared light reflected by the corn seeds to be tested through the fiber optic probe and convert it into raw spectral data. The sample carrying and transport module is used to carry the corn seeds to be tested and transport them sequentially to the detection position; the embedded control system is electrically connected to the spectral acquisition module and the sample carrying and transport module, and is used to run the software system and control the coordinated work of each module according to the instructions of the software system; The software system includes a data acquisition and control module, a combined preprocessing module, a model dynamic loading and inference module, a data management module, and a batch detection and report generation module. The data acquisition and control module configures the spectrometer parameters and communicates with the lower-level machine via a serial port, executing spectral acquisition after receiving a photoelectric trigger signal. The combined preprocessing module preprocesses the raw spectral data. The model dynamic loading and inference module loads the trained seed vigor discrimination model, performs inference on the preprocessed spectral data, and outputs the vigor discrimination results for the maize seeds to be tested. The data management module automatically saves the acquired spectral data, preprocessing parameters, prediction results, and acquisition time to a local historical record library. The batch detection and report generation module loads spectral data files in batches with one click and automatically generates detection reports. The seed vigor discrimination model that has been trained is obtained by any of the above-mentioned non-destructive detection methods for maize seed vigor based on near-infrared spectroscopy.
[0075] The near-infrared spectroscopy acquisition module consists of three parts: a spectrometer, a fiber optic probe, and a light source. The light source includes two halogen lamps, symmetrically mounted on both sides of the detection area, each lamp arranged at a 45° angle to the horizontal plane. This symmetrical arrangement of the two halogen lamps at a 45° angle to the horizontal plane ensures that the near-infrared incident light illuminating the surface of the corn seed from both sides forms cross-illumination on the seed surface, eliminating shadows and uneven brightness caused by unilateral illumination. It also reduces specular reflection interference and improves the stability and consistency of the spectral data. When the halogen lamps are powered on, the filaments are heated to incandescence, emitting continuous spectral light covering the near-infrared band. When this near-infrared incident light illuminates the surface of the corn seed, it interacts with the chemical components inside the seed, such as water, starch, protein, and oil. Some light energy is absorbed, and some is reflected, forming reflected light carrying information about the chemical composition.
[0076] The fiber optic probe is fixed directly above the detection position, with its end aligned with the surface of the corn seed to be tested. The probe contains multiple fiber bundles; some fibers transmit light emitted from the light source to the sample surface, while others collect the near-infrared light reflected from the sample surface and transmit it to the spectrometer. The spectrometer receives the near-infrared light reflected from the corn seed through the fiber optic probe and converts it into raw spectral data. The spectrometer contains a dispersive element and a detector array. The dispersive element decomposes the incident composite reflected light into monochromatic light of different wavelengths, and the detector array converts the light intensity of each wavelength into electrical signals, which are then converted from analog to digital and output as digitized raw spectral data. The spectrometer's acquisition parameters are set as follows: spectral acquisition range covering 939.3 nm to 1665.74 nm, 128 bands, integration time set to 100 ms, and averaging times set to 3.
[0077] The raw data directly output by the spectrometer is not the reflectance value. To eliminate the influence of ambient light variations and instrument dark current, and to improve the stability and comparability of the spectral data, black and white board calibration is performed on the raw data. During calibration, a white board reference spectrum and a black board reference spectrum are first acquired. The white board reference spectrum is acquired as follows: a standard white board is placed at the detection position. The surface of the standard white board is a highly reflective diffuse reflective material. Near-infrared light emitted by the light source is reflected by the standard white board, collected by the fiber optic probe, and transmitted to the spectrometer. The spectrometer outputs the white board reference spectrum, denoted as [missing value]. The method for acquiring the blackboard reference spectrum is as follows: with the light source off, the dark current signal is acquired by the spectrometer under conditions of no incident light, denoted as... When collecting raw spectral data from the maize seeds to be tested, the spectrometer output is recorded as follows: The formula for calculating blackboard calibration is: in, The corrected reflectance spectrum, The raw spectral data of the maize seeds to be tested, collected by the spectrometer. The whiteboard reference spectrum is used. The blackboard reference spectrum is used. Through this correction calculation, the effects of light source inhomogeneity, ambient light variation, and instrument dark current are eliminated, normalizing the spectral data to a uniform reflectance scale range, and the original spectral data is obtained after correction.
[0078] The sample carrying and conveying module is used to carry the corn seeds to be tested and convey them sequentially to the detection position. The sample carrying and conveying module includes a replaceable sample tray, a sliding platform, a lead screw slide, a stepper motor, a mechanical baffle, and a photoelectric sensor.
[0079] The sample tray is detachable and secured to the sliding platform via positioning pins and a magnetic closure. The positioning pins provide a precise mechanical positioning reference, ensuring consistent and repeatable positioning of the sample tray on the sliding platform each time it is installed. The magnetic closure uses magnetic force to attract the metal parts of the sample tray, providing quick locking and releasing. The sample tray has multiple independent grooves, each designed for placing a single corn seed to be tested. The dimensions of the individual grooves are designed according to the shape and size of the corn seeds, with a diameter of 8 mm and a depth of 3 mm. This ensures that each corn seed has a defined physical position on the sample tray, and the single-seed placement method guarantees that each spectral acquisition is performed on only one seed, avoiding interference between spectral signals from multiple seeds. Sample trays with different groove diameters and depths can be used to accommodate different varieties of corn seeds.
[0080] The sliding platform is driven by a lead screw slide to perform linear reciprocating motion. The lead screw slide consists of a lead screw and a stepper motor. After receiving pulse commands, the stepper motor rotates, and the lead screw converts the rotational motion into linear displacement of the sliding platform. A row of mechanical baffles is fixedly installed on the side of the sliding platform. The number of mechanical baffles is the same as the number of independent grooves on the sample tray, and the installation position of each mechanical baffle is strictly aligned with the central axis of the corresponding independent groove.
[0081] The photoelectric sensor is fixedly mounted at the detection position. The photoelectric sensor employs a through-beam photoelectric switch, comprising a transmitter and a receiver, with a U-shaped groove formed between them. The transmitter continuously emits an infrared beam that passes through the U-shaped groove to reach the receiver, which converts the received beam into an electrical signal. The width of the U-shaped groove is slightly larger than the thickness of the mechanical baffle.
[0082] When the sliding platform moves the sample tray under the drive of the lead screw slide, each mechanical baffle moves synchronously with the sliding platform. When the sliding platform moves to the detection position where a corn seed to be tested is exactly below the fiber optic probe, the mechanical baffle corresponding to the independent groove where the seed is located enters the U-shaped groove of the photoelectric sensor, completely blocking the light path from the transmitter to the receiver. Due to the interruption of the optical signal, the receiver's output level changes, generating a hardware interrupt signal. The photoelectric sensor outputs this hardware interrupt signal to the embedded control system. This physical positioning method, which combines mechanical baffles and the photoelectric sensor, relies on the physical alignment of the mechanical position, eliminating positioning deviations caused by stepper motor step loss or accumulated errors during long-term operation.
[0083] The embedded control system is electrically connected to the near-infrared spectroscopy acquisition module and the sample carrying and transport module. It runs the software system and controls the collaborative operation of each module according to the software system's instructions. The embedded control system includes an embedded motherboard, a display screen, and a lower-level device. The embedded motherboard uses an Intel Core i5 processor, is equipped with 8GB of RAM and a 128GB solid-state drive, and comes pre-installed with Windows 10, responsible for running the software system. The display screen is a 10.1-inch touchscreen with a resolution of 1280×800, providing a human-machine interface. The lower-level device uses an STM32F407 microcontroller, responsible for low-level motor control and sensor signal processing. The embedded motherboard communicates with the lower-level device via a serial port, sending motion control commands to the lower-level device, which then drives the stepper motor to operate according to the commands. Simultaneously, the lower-level device acquires hardware interrupt signals from the photoelectric sensor and uploads them to the embedded motherboard via the serial port. The embedded motherboard also connects to the spectrometer via a Micro USB interface, sending spectral acquisition commands and reading spectral data.
[0084] The data acquisition and control module is used to configure spectrometer parameters and communicate with the lower-level machine via serial port. It executes spectral acquisition after receiving a photoelectric trigger signal. The module provides a graphical parameter configuration interface, allowing users to set parameters such as integration time, averaging counts, and smoothing window. The integration time is adjustable from 1 millisecond to 45 seconds in 1-millisecond increments, with a recommended value of 100 milliseconds; the averaging count ranges from 1 to 10, with a recommended value of 3; and the smoothing window ranges from 3 to 15 (odd numbers), with a recommended value of 11.
[0085] The data acquisition and control module has a built-in black and white reference calibration function. When acquiring a white reference, the data acquisition and control module prompts the user to place the standard white board in the detection position on the interface, and automatically triggers the spectrometer to acquire 10 samples, taking the average as the white board reference spectrum. And save it. When acquiring the black reference, prompt the user to turn off the light source, and automatically acquire the dark current spectrum as the blackboard reference spectrum. And save it.
[0086] In automatic detection mode, the data acquisition and control module sends motion commands to the lower-level computer via serial port, driving the stepper motor to move the sliding platform. When the lower-level computer detects a hardware interrupt signal from the photoelectric sensor, it sends a bit command to the data acquisition and control module via serial port. Upon receiving this command, the data acquisition and control module immediately sends an acquisition command to the spectrometer via the MicroUSB interface, triggering the spectrometer to complete a spectral acquisition and read the raw spectral data. The data acquisition and control module then calls the black-and-white board correction formula to calculate the reflectance spectrum. The raw spectral data is obtained. After acquisition, the data acquisition and control module sends a confirmation signal to the lower-level computer, causing the sliding platform to continue moving to the next detection position. The data acquisition and control module uses the actual photoelectric trigger signal as the basis for each stop and acquisition.
[0087] The combined preprocessing module is used to preprocess the raw spectral data. It offers a variety of preprocessing methods, including standard normal variable transformation, multivariate scattering correction, derivative transformation, and Savitzky-Golay smoothing. Users can select multiple methods from the above preprocessing methods through a graphical interface and freely arrange the execution order of the selected methods by dragging or sorting, forming a combined preprocessing chain. The combined preprocessing module executes each preprocessing method in the chain sequentially on the raw spectral data according to the user-defined order, completing the chained processing.
[0088] The combined preprocessing module also supports real-time previewing of the comparison between the original and preprocessed spectral curves during processing. After the user adjusts the preprocessing method or modifies the parameters, the combined preprocessing module immediately performs preprocessing on the current spectral data and updates the display, allowing the user to intuitively evaluate the impact of different preprocessing combinations on the spectral morphology.
[0089] The model dynamic loading and inference module is used to load the trained seed vigor discrimination model, perform inference on the preprocessed spectral data, and output the vigor discrimination results of the maize seeds to be tested. The model dynamic loading and inference module has a unified model loading interface, which allows users to select and load the trained seed vigor discrimination model file from external storage devices.
[0090] The model dynamic loading and inference module automatically identifies the deep learning framework type corresponding to a model file by analyzing its file extension. Deep learning framework types include at least one of the following: Scikit-learn, Keras, PyTorch, and ONNX. Files with the .pkl extension correspond to the Scikit-learn framework, files with the .h5 extension correspond to the Keras framework, files with the .pt or .pth extension correspond to the PyTorch framework, and files with the .onnx extension correspond to the ONNX framework.
[0091] Based on the identified framework type, the model dynamic loading and inference module dynamically loads the runtime environment matching that framework. For the Scikit-learn framework, it loads the pickle parser and the Scikit-learn runtime; for the Keras framework, it loads the TensorFlow backend and the Keras model parser; for the PyTorch framework, it loads the torch library and the model weight loader; and for the ONNX framework, it loads the ONNX Runtime inference engine. After loading, the model dynamic loading and inference module parses the model file into a callable discriminative model instance.
[0092] During inference, the model dynamic loading and inference module receives the preprocessed spectral data output from the combined preprocessing module, converts the data into the input tensor format required for discriminating model instances, calls the inference method for discriminating model instances, and the model outputs raw scores for two categories, corresponding to high vitality and low vitality, respectively. The model dynamic loading and inference module outputs the category with the higher score as the vitality discrimination result.
[0093] The data management module automatically saves the acquired spectral data, preprocessing parameters, prediction results, and acquisition time to a local historical record library. After each spectral acquisition, the data management module integrates the raw spectral data, preprocessed spectral data, the preprocessing method combination chain used, the prediction results output by the model dynamic loading and inference module, and the current acquisition time into a single record. This record is then appended to the local historical record library, which stores data in CSV format.
[0094] The batch testing and report generation module is used to load spectral data files in batches with a single click and automatically generate test reports. This module allows users to select a folder containing multiple spectral data files via a graphical interface and load all files within that folder with a single click. Once loading is complete, the module displays all loaded files in a list format on the interface.
[0095] After the user clicks the batch detection button, the batch detection and report generation module sequentially processes each spectral data file: first, it calls the combined preprocessing module to preprocess the spectral data according to the user-defined preprocessing chain; then, it calls the model dynamic loading and inference module to infer the preprocessed spectral data, obtaining the vitality determination result for each file. During processing, the batch detection and report generation module displays a progress bar on the interface, providing real-time feedback on the processing progress. After all files are processed, the batch detection and report generation module displays a result summary table, including the filename of each file and the corresponding vitality determination result.
[0096] The batch testing and report generation module allows users to set report titles and sample information notes. The generated test report includes a cover page, a sample list, a spectral curve for each sample, and a judgment result table. The original and preprocessed spectral curves are overlaid and displayed on the same coordinate system. The report format supports Excel export.
[0097] The seed vigor discrimination model was trained using a non-destructive detection method for maize seed vigor based on near-infrared spectroscopy, as described above.
[0098] The embedded control system consists of two parts: a lower-level computer and a higher-level computer. The lower-level computer is an STM32 microcontroller, and the higher-level computer is an embedded motherboard. The lower-level computer is electrically connected to the stepper motor driver, controlling the stepper motor's operation and stop by sending pulse signals. The lower-level computer is also electrically connected to a photoelectric sensor, detecting the sensor's output level in real time. The lower-level computer continuously monitors the photoelectric sensor's output level. When the light signal at the sensor's receiving end is blocked by a mechanical baffle, the output level changes. Upon detecting this change edge, the lower-level computer confirms that a hardware interrupt signal has been generated. After detecting the hardware interrupt signal, the lower-level computer immediately stops sending pulse signals to the stepper motor driver, causing the stepper motor to stop rotating, and the sliding platform to stop moving. Simultaneously, the lower-level computer sends a position command to the higher-level computer via serial port. This command contains the groove number information of the currently reached detection position.
[0099] The host computer is an embedded motherboard running the software system. It communicates with the slave computer via a serial port, continuously monitoring the serial port receive buffer. Upon receiving a arrival command from the slave computer, the host computer parses the groove number of the currently reached detection position. The host computer then sends an acquisition command to the spectrometer via a Micro USB interface, triggering the spectrometer to complete a spectral acquisition and read the raw spectral data. After spectral acquisition, the host computer processes the acquired raw spectral data, including calling the combined preprocessing module for preprocessing and the model dynamic loading and inference module for inference, outputting the vigor determination result of the tested corn seed. After completing spectral acquisition and inference processing, the host computer sends an acknowledgment signal to the slave computer via the serial port. Upon receiving the acknowledgment signal, the slave computer resumes sending pulse signals to the stepper motor driver, causing the stepper motor to resume rotation and driving the sliding platform to continue moving to the next detection position. The embedded control system uses real photoelectric trigger signals as the basis for each stop and acquisition, without relying on preset steps or time to control the stopping position of the sliding platform.
[0100] Optionally, in the above technical solution, the model dynamic loading and inference module has a unified model loading interface, which supports users to select and load the trained seed vitality discrimination model file from an external storage device; The model dynamic loading and inference module automatically identifies the deep learning framework type corresponding to the model file by analyzing the file extension; the deep learning framework type includes at least one of the Scikit-learn framework, Keras framework, PyTorch framework and ONNX framework. Based on the identified framework type, the model dynamic loading and inference module dynamically loads the runtime environment that matches the framework and parses the model file into a discriminative model instance that can be called.
[0101] The model dynamic loading and inference module features a unified model loading interface, allowing users to select and load trained seed viability discriminant model files from external storage devices. This unified interface is represented by a "Load" button and a file selection dialog box in the graphical interface. After clicking the "Load" button, the module invokes the operating system's file selection dialog box, which allows users to browse the folder directory structure on the external storage device. The user navigates to the external storage path containing the trained seed viability discriminant model file, selects the target model file, and clicks the "Confirm" button. The dialog box then returns the complete path of the selected model file to the module. Upon receiving the file path, the module opens the corresponding model file in binary mode, reading all bytes of data into a memory buffer for subsequent parsing and processing.
[0102] The model dynamic loading and inference module automatically identifies the deep learning framework type corresponding to a model file by analyzing its extension. The model file extension is the string following the last dot in the filename. The module extracts the extension string from the model file path already read into the memory buffer. Internally, the module maintains a mapping table between extensions and deep learning framework types. This table records the corresponding deep learning framework types for different extensions. The mapping relationships are as follows: model files with the .pkl extension correspond to the Scikit-learn framework, model files with the .h5 extension correspond to the Keras framework, model files with the .pt or .pth extension correspond to the PyTorch framework, and model files with the .onnx extension correspond to the ONNX framework. The module matches the extracted extension string with each extension in the mapping table. If a match is found, the deep learning framework type corresponding to the model file is determined; otherwise, a message indicating that the file format is not supported is returned to the user.
[0103] Based on the identified deep learning framework type, the model dynamic loading and inference module dynamically loads the runtime environment matching that framework and parses the model file into a callable discriminant model instance. When the identified deep learning framework is Scikit-learn, the module calls the `load` function from Python's pickle standard library to load the model file in binary mode. The `load` function deserializes the serialized data in the model file into a Python object, which is the discriminant model instance under the Scikit-learn framework. This discriminant model instance contains all the trained model parameters and network structure. When the identified deep learning framework is Keras, the module calls the `models.load_model` function from the Keras library. This function reads the model file, parses the network structure definition and weight data, and returns a Keras model object as the discriminant model instance. When the identified deep learning framework is PyTorch, the model dynamic loading and inference module first calls the `load` function in the `torch` library to load the model file as a state dictionary. Then, it calls the model class constructor in the `torch` library to create an empty PyTorch model instance. Finally, it calls the `load_state_dict` method of this model instance to load the weight parameters from the state dictionary into the model, obtaining a complete PyTorch discriminant model instance. When the identified deep learning framework is ONNX, the model dynamic loading and inference module calls the constructor of the `InferenceSession` class in the ONNX Runtime library, passing the model file path as a parameter to construct an ONNX Runtime inference session instance as the discriminant model instance. After loading, the model dynamic loading and inference module saves this discriminant model instance in memory for subsequent inference of the preprocessed spectral data.
[0104] like Figure 5 As shown, the main interface of the software system is developed using PyQt6. The layout is divided into a top menu bar, a left-side spectral display area (overlaying raw and preprocessed curves), a right-side operation panel (integrating parameter configuration, model selection, and acquisition control), and a bottom status bar. After the user configures the parameters, automatic detection is initiated. The system sequentially completes spectral acquisition, preprocessing, and model inference, displaying the results in real time and supporting the export of Excel reports (see interface running status). Figure 6 See the example report. Figure 7 , Figure 8 ).
[0105] The software system includes modules for data acquisition and control, spectral preprocessing, model loading and prediction, offline analysis, result display and report generation, etc. The functions of each module are the same as the corresponding modules in the system software described above, and will not be repeated here.
[0106] Figure 9 This is a schematic diagram of the overall structure of the benchtop testing system. Figure 10 This is an enlarged view of the sample carrying and transport unit. The spatial layout and connection relationship of the various modules of the hardware platform (near-infrared spectroscopy acquisition module, light source module, sample carrying and transport module, embedded control system) are shown in the figure. Their specific composition and working principle have been described in detail in the previous "System" section and will not be repeated here.
[0107] The technical solution of the present invention will be further described through the following embodiments: Example 1: Sample collection and database construction, specifically: This embodiment selected 3300 naturally aged corn seeds from 33 different corn varieties from different production areas. The reflectance spectrum of each seed was collected using a near-infrared spectrometer, with a spectral range of 939.3-1665.74 nm, 128 bands, and a resolution of 5.72 nm. The acquisition parameters were set as follows: integration time 100 ms, averaging times 3, and smoothing window 11. Each naturally aged corn seed was collected three times, and the arithmetic mean was taken as the raw near-infrared spectral data for that seed. After collection, a standard germination test was conducted on all naturally aged corn seeds. They were continuously cultured for 7 days at a constant temperature of 25 degrees Celsius using moist germination paper as a germination bed. Final statistics were performed on the 7th day. Seeds with shoot and root lengths greater than the seed length, and with normal embryo development and no deformities were marked as high vigor and assigned the vigor tag 1; seeds that did not germinate or germinated abnormally were marked as low vigor and assigned the vigor tag 0. Due to improper handling during collection or germination of some naturally aged maize seeds, no effective results were obtained. Ultimately, a total of 2971 naturally aged maize seeds were successfully germinated after obtaining valid raw near-infrared spectral data. Among them, 2319 samples were high-viability and 652 samples were low-viability. This dataset exhibits sample imbalance, with a relatively small number of low-viability samples, highlighting the necessity of subsequent data augmentation steps. All raw near-infrared spectral data and corresponding viability labels constitute the original database for subsequent model training.
[0108] Example 2: Construction and training of physically constrained generative adversarial networks, specifically: like Figure 2As shown, this embodiment constructs a physically constrained generative adversarial network (GAN) within the WGAN-GP framework for data augmentation. The physical perception generator structure is designed as follows: the input layer receives 100-dimensional latent variables, which are mapped to a 256-dimensional feature vector through a fully connected layer; three residual blocks are connected, each containing two fully connected layers and a skip connection; a dimensionality reduction layer reduces the 256-dimensional features to 128-dimensional; a reverse bottleneck layer first increases the dimensionality to 256-dimensional and then reduces it back to 128-dimensional to enhance feature representation; the output layer uses the Tanh activation function to generate 128-dimensional spectral data; finally, a lightweight smoothing correction is performed through a physical correction layer, which uses a 3-point moving average differentiable approximation with a mixing coefficient of 0.1.
[0109] The discriminator structure is designed as follows: 128-dimensional spectral data is input, which passes through four one-dimensional convolutional layers. The kernel size of each convolutional layer is 4, and the strides are 2, 2, 2, and 1, respectively. The number of output channels is 64, 128, 256, and 512, respectively. Each convolutional layer is followed by a LeakyReLU activation function with a negative slope of 0.2. Finally, a fully connected layer is passed to output a realism score. The output dimension is a one-dimensional scalar.
[0110] The training parameters are set as follows: input latent variable dimension 100, batch size 32, generator learning rate 0.0002, discriminator learning rate 0.0002, Adam optimizer first-order moment decay coefficient beta1 0.5, second-order moment decay coefficient beta2 0.999, gradient penalty coefficient λ_gp = 10, and the generator is updated once every 5 discriminator updates. The weight coefficients in the generator loss function are set as follows: α = 1.0, β = 0.1, γ = 0.5. In the training loss function, the physical guidance loss term is a weighted sum of smoothness constraint loss term, continuity constraint loss term, water absorption peak constraint loss term, and curvature constraint loss term to introduce spectral smoothness constraints, continuity constraints, and peak-valley constraints based on the near-infrared target absorption peak position; the consistency loss term is a weighted sum of additive noise robustness loss and wavelength shift robustness loss to enhance the robustness of the generated spectrum to measurement perturbations.
[0111] After training, a physical perception generator is used to generate synthetic spectral data, which is then fused with the original near-infrared spectral data to construct an enhanced spectral dataset.
[0112] Example 3: Construction of a discriminative model integrating band grouping attention and statistical features, specifically: This embodiment constructs an Inception-ResNet network that integrates a band grouping attention module and a statistical feature extraction branch as a seed viability discrimination model. Bands are grouped according to the wavelength range of the near-infrared spectrum. The starting wavelength is 939.3 nm, the step size is 5.72 nm, and there are a total of 128 bands. After calculating the center wavelength of each band, four subgroups are formed: the first subgroup is the other regions, with wavelengths less than 1400 nm, corresponding to indices 0 to 80, totaling 81 bands; the second subgroup is the starch absorption peak region, with wavelengths less than or equal to 1400 nm and wavelengths less than 1500 nm, corresponding to indices 81 to 97, totaling 17 bands; the third subgroup is the protein absorption peak region, with wavelengths greater than or equal to 1500 nm, corresponding to indices 98 to 127, totaling 30 bands. The attention weight scalar of the band grouping attention module is initialized to [0.1, 0.8, 0.6], indicating that initially, the focus is on the starch absorption peak region and the protein absorption peak region. The band grouping attention module is located after the network input layer and weights the input spectrum: x_weighted = softmax(w) @ x_group, where @ indicates weighted concatenation by group, the softmax function normalizes the three attention weight scalars, and the fourth subgroup is the remaining wavelength range.
[0113] The statistical feature extraction branch calculates a statistical feature vector from the raw near-infrared spectral data, including the mean, standard deviation, maximum, minimum, peak-to-peak value, energy, skewness, kurtosis, and the magnitudes of the first 16 Fast Fourier Transform coefficients, totaling 28 dimensions of raw statistical features. This statistical feature vector is input into a multilayer perceptron, with the following structure: the first fully connected layer maps the 28 dimensions to 64 dimensions, followed by a ReLU activation function and Dropout with a dropout rate of 0.7; a second fully connected layer maps the 64 dimensions back to 64 dimensions, outputting a 64-dimensional statistical feature vector.
[0114] The backbone network structure of the model includes: the input layer receives 128-dimensional spectral data, and the added channel dimension becomes (1, 128); the convolutional layer is Conv1d(1, 32, kernel_size=7, stride=2, padding=3) plus BatchNorm1d(32) plus ReLU plus MaxPool1d(kernel_size=3, stride=2, padding=1); the first Inception module has 32 input channels and 128 output channels, and contains four parallel convolutional branches, which are 1× The first Inception module consists of 1 convolution, 1×1 plus 3×3 convolution, 1×1 plus 5×5 convolution, 3×3 max pooling plus 1×1 convolution, with each branch having 32 output channels. After concatenation, the outputs are batch normalized and activated by ReLU. The first residual block has 128 input and 128 output channels, containing two 3×3 convolutions and skip connections. The second Inception module has 128 input channels and 256 output channels, with the same internal structure as the first Inception module. The second residual block also has 256 input and 256 output channels, containing two 3×3 convolutions and skip connections. Adaptive global average pooling outputs a 256-dimensional deep feature vector. This 256-dimensional deep feature vector, the 3-dimensional weighted fused feature vector from the band grouping attention module, and a 64-dimensional statistical feature vector are concatenated to obtain a 323-dimensional fused feature. The classification layer structure is as follows: the first fully connected layer maps 323 dimensions to 128 dimensions, followed by the ReLU activation function and Dropout with a dropout rate of 0.6. The second fully connected layer then maps the 128 dimensions to 2 dimensions, outputting the original scores of the two categories, corresponding to high vitality and low vitality, respectively.
[0115] The training parameters are set as follows: the enhanced spectral dataset is randomly divided into training and validation sets in a 7:3 ratio, and stratified sampling is used to maintain class balance. The batch size is 32, the optimizer is Adam, the learning rate is 0.001, and the weight decay is 10. -4 The training loss function is cross-entropy loss plus an L1 regularization term with a coefficient of 0.001, used to constrain the sparsity of the attention weight scalar. The training run consists of 200 epochs, employing an early stopping strategy: training stops if the validation set accuracy does not improve for 10 consecutive epochs. The learning rate is scheduled using ReduceLROnPlateau with a patience of 5 and a factor of 0.5. During training, the attention weight scalar of the band grouping attention module is optimized along with the network parameters through backpropagation. After training, the model with the highest validation set accuracy is saved as the seed viability discrimination model. Testing shows that the seed viability discrimination model achieves an accuracy of 89.73%, a recall of 89.73%, and an F1 score of 89.6% on the test set.
[0116] Example 4: Hardware integration of the detection system, specifically: The trained seed viability discrimination model is deployed to an integrated desktop detection system. The system hardware components are as follows: 1) Near-infrared spectroscopy acquisition module: Utilizing the Ocean Optics FLAME-NIR+ miniature near-infrared spectrometer, this spectrometer employs a high-performance, compact optical platform, equipped with an uncooled InGaAs linear array detector. It features a pre-configured wavelength range of 939.3-1665.74 nm, 128 pixels, an optical resolution of approximately 10 nm FWHM, a 25 μm slit, a signal-to-noise ratio of 6000:1, full signal coverage, a dynamic range of 6000:1, single-sampling capability, thermal stability of 0.08 nm / °C, an adjustable integration time range of 1 ms to 45 s, and a maximum scan frequency of approximately 400 Hz. The spectrometer connects to the embedded motherboard via a Micro USB interface.
[0117] 2) The fiber optic probe uses Ocean Optics QP600-1-VIS-NIR premium fiber with a core diameter of 600μm, a wavelength range of 400-2100nm, and a length of 1 meter. It connects to the spectrometer via an SMA 905 interface, and a collimating lens is installed at the end of the fiber optic probe to focus the beam. The fiber optic probe is fixed directly above the detection position, approximately 20mm from the sample surface, and is kept perpendicular to the incident light using a special clamp.
[0118] 3) Light source module: includes two sets of halogen lamps. The reflected light source consists of two 50W halogen lamps, symmetrically installed on both sides of the detection position at a 45° angle to the horizontal plane to ensure uniform light illumination of the seed surface; the projected light source consists of one 20W halogen lamp, installed below the loading platform, shining upwards through the light-transmitting hole for transmission spectrum acquisition.
[0119] 4) Sample Carrying and Transfer Module: The platform measures 400mm × 400mm and is made of aluminum alloy. The sample tray is detachable and has three independent grooves, each 8mm in diameter and 3mm deep, suitable for single-seed placement of corn. The lead screw slide consists of three sets: a sample feeding slide, a fiber optic moving slide, and a light source moving slide, each driven by a stepper motor. The photoelectric sensor uses a through-beam photoelectric switch, installed on both sides of the detection position, with a detection accuracy of 0.1mm.
[0120] To achieve modular design and precise positioning, this system adopts a tray-slider detachable structure. The sample tray is detachable, and trays with different groove specifications can be replaced according to different seed varieties. The groove diameter and depth are customized according to the seed size. The tray is fixed to the sliding platform below by positioning pins and magnetic devices to ensure consistent positioning during repeated installations.
[0121] The sliding platform is driven by a lead screw slide, and a row of precision mechanical baffles is mounted on its side. The baffles are made of thin stainless steel sheets, and their number matches the number of grooves in the tray. Each baffle is precisely aligned with the central axis of its corresponding groove. As the sliding platform moves, the baffles move back and forth accordingly. A through-beam photoelectric sensor is fixedly installed at the detection position, its U-shaped groove width slightly larger than the baffle thickness. When the sliding platform moves the tray, positioning a seed directly below the fiber optic probe, the baffle corresponding to that seed enters the U-shaped groove of the photoelectric sensor, completely blocking the light path. Upon detecting the change in light path continuity, the sensor immediately outputs a TTL level signal to the STM32 main control board. This physical triggering method eliminates positioning deviations caused by missed steps or accumulated errors from the stepper motor, ensuring that each spectral acquisition occurs in the same area on the seed surface. This interchangeable tray and baffle-in-slider design has the following advantages: users only need to replace the tray according to the object being detected, without needing to recalibrate the sensor position; the fixed connection between the baffle and the slider ensures positioning accuracy during long-term use; trays of different specifications can be used interchangeably as long as the groove spacing and baffle spacing are consistent, greatly improving the system's flexibility and applicability.
[0122] 5) Embedded Control System: The embedded motherboard uses an Intel Core i5 processor, 8GB of RAM, a 128GB solid-state drive, and comes pre-installed with Windows 10. The display is a 10.1-inch touchscreen with a resolution of 1280×800. The STM32 main control board, model STM32F407, is responsible for low-level motor control and sensor signal processing. It communicates with the embedded motherboard via serial port, receives motion commands, and provides position status feedback.
[0123] 6) Sheet metal casing: Made of 1.5mm thick cold-rolled steel sheet, bent and formed, with electrostatic powder coating treatment. A switch door is located on the front, and a reflective light source switch, a projector light source switch, and a one-button detection button are located on the right side. The internal structure has been optimized to ensure that each module is securely installed and easy to maintain.
[0124] Example 5: Detailed implementation of the software system's functional modules, specifically: The software system is developed using PyQt6 and deployed on an embedded motherboard. The detailed implementation of the functional modules is as follows: 1) Data Acquisition and Control Module: This module integrates spectrometer parameter configuration, motor motion control, and black-and-white reference calibration functions. Spectrometer parameter configuration supports setting the integration time (range 1ms-45s, 1ms increments, 100ms recommended); setting the averaging count (range 1-10, 3 recommended); and setting the smoothing window (range 3-15 odd numbers, 11 recommended). Motor control uses the UART protocol to communicate with the STM32 microcontroller, supporting setting the motion speed (range 100-1000 pulses / second, 500 pulses / second recommended); and the detection time (range 0.5-5 seconds). Spectral acquisition triggering supports both software triggering and photoelectric sensor hardware triggering modes. In automatic detection mode, hardware triggering is used for precise positioning.
[0125] Automatic detection mode and hardware triggering mechanism: When set to automatic detection mode, the main software thread enters a low-power listening state, waiting for a hardware interrupt signal sent by the STM32 via the serial port. This signal is generated by a photoelectric sensor fixed at the detection position, triggered by a mechanical stop on the slider, corresponding to the precise moment when the seed to be tested reaches the detection position. Upon receiving an interrupt signal, the software immediately pauses the output of motor motion commands and automatically executes the preset acquisition-preprocessing-prediction-display-recording process: It triggers the spectrometer to complete one spectral acquisition, obtaining the near-infrared spectral data of the seed to be tested; it calls the spectral preprocessing module to process the near-infrared spectral data of the seed in real time. The preprocessing process sequentially performs Savitzky-Golay smoothing, standard normal variable transformation, and first derivative processing to obtain preprocessed spectral data; it inputs the preprocessed spectral data into the loaded seed vigor discrimination model for inference, obtaining a vigor discrimination result of high or low vigor; it binds the vigor discrimination result to the current groove number, displays it in real time in the result column on the right side of the main interface, and automatically saves it to the log file; after the process is completed, the software sends a continue motion command to the STM32, driving the stepper motor to move to the next groove position, waiting for the next baffle trigger.
[0126] This hardware-triggered, software-response event-driven approach enables precise positioning and fully automated continuous detection of individual seeds, avoiding cumulative errors from stepper motors and improving detection efficiency and repeatability.
[0127] Black and white reference calibration, a necessary prerequisite step before data acquisition, is built into this module. When acquiring a white reference, the software prompts the user to place a standard white board, automatically acquiring 10 samples and averaging them as the white reference spectrum; when acquiring a black reference, the user is prompted to turn off the light source, and the software automatically acquires the dark current spectrum.
[0128] 2) Spectral preprocessing module: Provides the following algorithm options, supporting multiple algorithm combinations: Savitzky-Golay smoothing; standard normal variable transformation, the mathematical expression of which is: in, This represents the spectral data after standard normal transformation. This represents the input spectral data. This represents the arithmetic mean of the reflectance values across all bands of the spectrum. This represents the standard deviation of reflectance values across all bands of the spectrum; multivariate scattering correction calculates the average spectrum of all samples as a reference, and performs linear regression fitting on each sample; the first derivative is calculated using Savitzky-Golay convolution, window 11, order 2; the second derivative is also calculated using Savitzky-Golay convolution, window 11, order 2. After the user selects a preprocessing method, the left-hand spectral display area shows a real-time comparison of the spectral curves before and after processing, facilitating user evaluation of the results.
[0129] 3) Model Loading and Prediction Module: Supports loading model files in .pkl, .h5, and .pt formats. After loading, it automatically parses the model input requirements, such as whether preprocessing is needed and input dimensions, and displays information such as the model name and applicable crops on the interface. During prediction, the near-infrared spectral data of the seed to be tested is first preprocessed according to the user's selection, and then input into the seed vigor discrimination model for inference, outputting high or low vigor results. A built-in runtime log submodule records the following information for each prediction: timestamp, sample ID, original near-infrared spectral file path, preprocessing method, model version, and output results. The log file is saved in CSV format.
[0130] 4) Offline Analysis Module: Supports loading single files in CSV, TXT, and Excel formats. The first column must be wavelength, and the second column must be reflectance. Alternatively, it can load files in batches from folders. After batch loading, all files are displayed in a drop-down list for individual viewing. Clicking the batch detection button processes all files sequentially, with a progress bar indicating progress. Upon completion, a summary table is displayed, including filenames, original results, preprocessed results, and judgment results. Exporting to CSV is supported.
[0131] 5) Results Display and Report Generation Module: The spectral display area on the left side of the main interface supports zooming, panning, and saving images via the right-click menu. Test results are displayed in real-time in the right-hand results box, including the viability determination results. The report generator interface lists all samples tested, supports selection, and allows setting report titles, sample information notes, etc. The generated report includes a cover page, a sample list, spectral curves for each sample, overlay display of raw and preprocessed data, and a determination results table. Excel format is supported.
[0132] To address the limited number of high-quality labeled samples, a Physically Constrained Generative Adversarial Network (GAN) is constructed for data augmentation. The GAN employs the WGAN-GP framework and comprises a generator and a discriminator. The generator is a physics-aware generator, consisting of a fully connected layer, three sequentially connected residual blocks, a dimensionality reduction layer, a reverse bottleneck layer, an output layer, and a physics correction layer. The discriminator is a convolutional neural network, comprising four sequentially connected one-dimensional convolutional layers and a fully connected layer, with each one-dimensional convolutional layer followed by a LeakyReLU activation function. During training, in addition to the adversarial loss, a physics-guided loss term and a consistency loss term are introduced. The physics-guided loss term is a weighted sum of smoothness constraint loss terms, continuity constraint loss terms, water absorption peak constraint loss terms, and curvature constraint loss terms, used to introduce spectral smoothness constraints, continuity constraints, and peak-valley constraints based on the location of near-infrared target absorption peaks during training. Spectral smoothness constraints are implemented by penalizing the second derivative of the synthesized spectrum. Continuity constraints use Huber loss to limit reflectance variations between adjacent bands. A water absorption peak constraint loss term forces the generated spectrum to form a local valley at the 1450nm band. A curvature constraint loss term limits the local bending of the spectrum. The consistency loss term is a weighted sum of additive noise robustness loss and wavelength shift robustness loss, enhancing the robustness of the generated spectrum to measurement perturbations. These constraints ensure that the generated synthesized spectral data conforms to both a statistical distribution and strictly follows the physical laws of near-infrared spectroscopy. After training, a generator is used to generate synthesized spectral data consistent with the real spectral distribution, which is then fused with the original near-infrared spectral data to construct an enhanced spectral dataset.
[0133] A deep convolutional neural network model integrating a band-grouping attention module and a statistical feature extraction branch was constructed as the seed viability discrimination model. The band-grouping attention module, located after the network input layer, divides the 128 bands into three subgroups with clear chemical meanings based on the physical significance of the near-infrared spectrum. The first subgroup represents other regions, corresponding to a wavelength range of 939.3 nm to 1400 nm; the second subgroup represents the starch absorption peak region, corresponding to a wavelength range of 1400 nm to 1500 nm; and the third subgroup represents the protein absorption peak region, corresponding to a wavelength range of 1500 nm to 1665.74 nm. Average pooling was performed on each subgroup to obtain group-level feature representations. A learnable attention weight scalar was assigned to each subgroup, and after normalization using the softmax function, a normalized attention weight scalar was obtained. This normalized attention weight scalar was multiplied by the corresponding group-level feature representation to obtain a weighted fused feature vector. This structure incorporates prior spectroscopic knowledge into the deep convolutional neural network model, enabling the model to adaptively enhance the contribution of starch and protein absorption peak regions to the final discrimination result, while suppressing interference from other irrelevant regions. This improves the model's physical interpretability and ability to focus on key bands. The statistical feature extraction branch calculates multi-dimensional statistical features from the raw near-infrared spectral data, including mean, standard deviation, maximum, minimum, peak-to-peak value, energy, skewness, kurtosis, and the modulus of the first 16 fast Fourier transform coefficients, forming a 28-dimensional raw statistical feature vector. These statistics characterize the global distribution of the spectrum from different perspectives: mean and standard deviation reflect the overall absorption level and fluctuation; maximum, minimum, and peak-to-peak values indicate the intensity of specific absorption peaks; energy characterizes the total absorption capacity of the spectrum; skewness and kurtosis describe the symmetry and sharpness of the spectral distribution; and the fast Fourier transform coefficients extract the periodic features of the spectrum, helping to capture the combination frequency information of molecular vibrations. The original 28-dimensional statistical feature vector is input into a multilayer perceptron. The structure involves mapping a Linear 28-dimensional vector to 64-dimensional features, followed by a ReLU activation function, then Dropout, and finally mapping a Linear 64-dimensional vector back to 64-dimensional features. The output is a 64-dimensional statistical feature vector, which is then concatenated and fused with the deep features extracted by the backbone network. This branch fills the gap in deep convolutional neural network models' perception of global spectral statistical characteristics, complementing local waveform features and improving discrimination accuracy and robustness.
[0134] The backbone network of the model adopts the Inception-ResNet structure, which includes two Inception modules and two residual blocks, used to extract multi-scale deep features of the spectrum. The Inception modules capture multi-scale local waveform features through parallel convolutional branches with different kernel sizes, and the residual blocks directly add the input to the output through skip connections, which alleviates the gradient vanishing problem and enhances the stability of network training.
[0135] The deep features output from the backbone network, the weighted fused feature vector from the band grouping attention module, and the statistical feature vector from the statistical feature extraction branch are concatenated and fused to obtain the fused feature. This fused feature is then input into the fully connected classification layer, which outputs a judgment result indicating whether the seed belongs to high or low viability. During model training, the attention weight scalar and network parameters are optimized together through backpropagation, enabling the model to adaptively adjust the degree of attention given to different band regions.
[0136] This invention also integrates the trained seed viability discrimination model into an integrated benchtop detection system. The system's hardware includes a near-infrared spectral acquisition module, comprising a spectrometer and fiber optic probe; a light source module, comprising a halogen lamp reflective light source and a projected light source; a sample carrying and transport module, comprising a platform, sample tray, lead screw slide, stepper motor, and photoelectric sensor; an embedded control system, comprising an embedded motherboard and display screen; a heat dissipation module; and a sheet metal housing, achieving full automation from sample introduction to spectral acquisition. The software system is deployed on the embedded motherboard, using a graphical user interface developed with PyQt6. It integrates functional modules such as data acquisition and control, black-and-white reference calibration, spectral preprocessing, model loading and prediction, offline analysis, result display and report generation, and motor control. Users can complete operations such as serial port connection, parameter setting, model selection, automatic acquisition, data saving, and report generation with a single click through the graphical interface. The system displays spectral curves and discrimination results in real time and automatically records detailed information for each prediction. This invention combines physically constrained generative adversarial networks, multi-dimensional statistical feature fusion, and an automated hardware platform, offering advantages such as fast detection speed, high accuracy, and ease of operation. It is suitable for applications such as seed quality grading and scientific research testing.
[0137] This invention combines a physically interpretable band grouping attention module, multi-dimensional statistical feature fusion, and an automated hardware platform, resulting in the following advantages: First, the physically constrained generative adversarial network effectively solves the model training problem in small sample scenarios, and the generated synthetic spectral data conforms to spectroscopic laws, enhancing the diversity and representativeness of the data. Second, the band grouping attention module introduces prior spectroscopic knowledge into the deep convolutional neural network model, improving the model's physical interpretability and ability to focus on key bands. Third, the statistical feature extraction branch supplements the macroscopic characteristics of the spectrum from a global perspective, complementing the deep local features and improving the discrimination accuracy and robustness. Fourth, the integrated benchtop detection system achieves full automation from sample loading and spectral acquisition to result output, with fast detection speed and simple operation, suitable for applications such as seed quality grading and scientific research testing.
[0138] The above description is merely a preferred embodiment of the present invention and an explanation of the technical principles employed. Those skilled in the art should understand that the scope of disclosure in this invention is not limited to technical solutions formed by specific combinations of the above-described technical features, but should also cover other technical solutions formed by arbitrary combinations of the above-described technical features or their equivalents without departing from the above-disclosed concept. For example, technical solutions formed by substituting the above features with (but not limited to) technical features with similar functions disclosed in this invention.
[0139] Although embodiments of the present invention have been shown and described above, it is understood that the above embodiments are exemplary and should not be construed as limiting the present invention. Those skilled in the art can make changes, modifications, substitutions and variations to the above embodiments within the scope of the present invention.
Claims
1. A non-destructive method for detecting maize seed vigor based on near-infrared spectroscopy, characterized in that, include: Raw near-infrared spectral data of naturally aged corn seeds were collected, and a standard germination test was performed on each of the naturally aged corn seeds to obtain a viability label for each of the naturally aged corn seeds. A generative adversarial network (GAN) with a constraint mechanism is constructed. The GAN is trained using the original near-infrared spectral data. After training, the generator in the trained GAN with the constraint mechanism generates synthetic spectral data. The GAN is constructed based on the WGAN-GP framework, and the training loss function includes a spectral physical constraint loss term, which is a weighted sum of smoothness constraint loss term, continuity constraint loss term, curvature constraint loss term, baseline drift constraint loss term, and band correlation constraint loss term. The original near-infrared spectral data and the synthesized spectral data are merged to construct an enhanced spectral dataset. The enhanced spectral dataset is then preprocessed to obtain a preprocessed spectral dataset. A deep convolutional neural network model, comprising a band grouping attention module and a statistical feature extraction branch, is constructed. The model is then trained and its performance validated using the preprocessed spectral dataset and the viability label of each naturally aged corn seed, resulting in a trained seed viability discrimination model. The band grouping attention module divides the input spectrum into multiple physically meaningful subgroups based on the wavelength range of the near-infrared spectrum and assigns learnable attention weights to each subgroup to enhance the contribution of key chemical information regions to the discrimination results. The statistical feature extraction branch extracts statistical feature vectors from the input spectrum and adaptively weights and fuses them with deep features extracted from the backbone network of the deep convolutional neural network model using a gated fusion mechanism. Near-infrared spectral data of the maize seeds to be tested are collected and preprocessed, then input into the trained seed vigor discrimination model, and the vigor discrimination results of the maize seeds to be tested are output.
2. The non-destructive detection method for maize seed vigor based on near-infrared spectroscopy according to claim 1, characterized in that, The smoothness constraint loss term is used to penalize the second derivative of the generated spectrum, and its mathematical expression is: in, Represents the smoothness constraint loss term. This represents the mathematical expectation of a batch of generated samples. To generate the spectrum in the first Reflectance values for each band, and The first The and the first Reflectance values for each band, Total number of bands; The continuity constraint loss term uses Huber loss to limit the reflectivity variation between adjacent bands, and its mathematical expression is as follows: in, This represents the loss term due to continuity constraints. The Huber loss function is defined as follows: in, The difference in reflectivity between adjacent bands, i.e. , express The absolute value; The curvature constraint loss term is used to limit the local curvature of the generated spectrum, and its mathematical expression is as follows: in, This represents the curvature constraint loss term. This represents the absolute value operator; The baseline drift constraint loss term is used to suppress the overall baseline drift of the spectrum, and its mathematical expression is as follows: in, This represents the baseline drift constraint loss term. To generate spectral vectors, The baseline vector is obtained by linear interpolation of the two endpoints of the spectrum. The squared norm of a vector is denoted by 2. The band correlation constraint loss term is used to match the band correlation of the generated spectrum with the prior correlation matrix, and its mathematical expression is: in, This represents the band correlation constraint loss term. Let be the mean square error function. For operations on the Pearson correlation coefficient matrix, To generate a matrix of samples in batches, This is the Gaussian attenuation prior correlation matrix based on band distance.
3. The non-destructive detection method for maize seed vigor based on near-infrared spectroscopy according to claim 2, characterized in that, The training loss function of the generative adversarial network also includes a consistency loss term, which is composed of a weighted sum of additive noise robustness loss and wavelength shift robustness loss. The additive noise robustness loss is the expectation of the squared L2 of the difference between the synthesized spectral data generated by the generator before and after adding Gaussian noise to the input latent variable. The wavelength shift robustness loss is the sum of the expectations of the squared L2 of the difference between the synthesized spectral data after shifting it by one band in the long-wave direction and by one band in the short-wave direction, respectively, and the synthesized spectral data before the shift.
4. The non-destructive detection method for maize seed vigor based on near-infrared spectroscopy according to claim 1, characterized in that, The band grouping attention module divides the input spectrum into multiple physically meaningful subgroups based on the wavelength range of the near-infrared spectrum, and assigns learnable attention weights to each subgroup. These subgroups are: the first subgroup corresponds to the wavelength range of 940nm to 990nm, the second subgroup corresponds to the wavelength range of 1140nm to 1230nm, the third subgroup corresponds to the wavelength range of 1410nm to 1540nm, and the fourth subgroup corresponds to the remaining wavelength ranges. Average pooling is performed on each subgroup to obtain a group-level feature representation. A learnable attention weight scalar is assigned to each subgroup, which is then normalized by softmax and multiplied by the corresponding group-level feature representation to obtain a weighted fused feature vector.
5. The non-destructive detection method for maize seed vigor based on near-infrared spectroscopy according to claim 1, characterized in that, The statistical feature vector extracted by the statistical feature extraction branch includes at least one of the following features: mean, standard deviation, and skewness of full-band spectral reflectance, and the low-frequency energy ratio or frequency domain main peak amplitude extracted after fast Fourier transform; the gated fusion mechanism dynamically calculates the fusion weights of deep features and statistical feature vectors based on the input samples through a lightweight sub-network.
6. The non-destructive detection method for maize seed vigor based on near-infrared spectroscopy according to claim 1, characterized in that, The generator in the generative adversarial network includes a fully connected layer and multiple one-dimensional transposed convolutional layers, which are used to progressively upsample random latent variables into synthetic spectral data; the discriminator in the generative adversarial network includes multiple one-dimensional convolutional layers and a fully connected layer, which are used to output a authenticity score of the input spectrum.
7. A non-destructive testing system for maize seed vigor based on near-infrared spectroscopy, characterized in that, This includes a hardware platform and a software system deployed on the hardware platform; The hardware platform includes a near-infrared spectroscopy acquisition module, a sample carrying and transport module, and an embedded control system. The spectral acquisition module includes a spectrometer, an optical fiber probe, and a light source; the light source includes at least two halogen lamps, symmetrically installed on both sides of the detection area and arranged at a 45° angle to the horizontal plane, for providing uniform near-infrared incident light to the corn seeds to be tested; the spectrometer is used to receive the near-infrared light reflected by the corn seeds to be tested through the optical fiber probe and convert it into raw spectral data. The sample carrying and conveying module is used to carry the corn seeds to be tested and convey them sequentially to the detection position; The embedded control system is electrically connected to the spectral acquisition module and the sample carrying and conveying module, and is used to run the software system and control the collaborative work of each module according to the instructions of the software system; The software system includes a data acquisition and control module, a combined preprocessing module, a model dynamic loading and inference module, a data management module, and a batch detection and report generation module; among which... The data acquisition and control module is used to configure the spectrometer parameters and communicate with the lower-level machine through a serial port. After receiving the photoelectric trigger signal, it performs spectral acquisition. The combined preprocessing module is used to preprocess the raw spectral data; The model dynamic loading and inference module is used to load the trained seed vigor discrimination model, and to perform inference on the preprocessed spectral data to output the vigor discrimination results of the maize seeds to be tested. The data management module is used to automatically save the collected spectral data, preprocessing parameters, prediction results and collection time to the local historical record library; The batch detection and report generation module is used to load spectral data files in batches with one click and automatically generate detection reports. The seed vigor discrimination model that has been trained is obtained by the non-destructive detection method for maize seed vigor based on near-infrared spectroscopy according to any one of claims 1 to 6.
8. The non-destructive testing system for maize seed vigor based on near-infrared spectroscopy according to claim 7, characterized in that, The sample carrying and conveying module includes a replaceable sample tray, a sliding platform, mechanical baffles, and a photoelectric sensor. The sample tray has multiple independent grooves, each for placing a single corn seed to be tested. The sample tray is fixed to the sliding platform by positioning pins and a magnetic suction device. A row of mechanical baffles is fixedly installed on the side of the sliding platform, the number of which is the same as the number of independent grooves, and their installation positions are aligned with the central axis of each independent groove. The photoelectric sensor is fixedly installed at the detection position. When the sliding platform moves the sample tray to the detection position, the photoelectric sensor is activated. When the position is reached, the corresponding mechanical baffle enters the U-shaped groove of the photoelectric sensor and blocks the light path. The photoelectric sensor outputs a hardware interrupt signal to the embedded control system. Upon receiving the hardware interrupt signal, the embedded control system immediately stops the movement of the sliding platform and sends a position command to the host computer via serial port. After receiving the position command, the host computer calls the near-infrared spectral acquisition module to complete the spectral acquisition of a single seed and sends a confirmation signal to the host computer after the acquisition is completed, so that the sliding platform continues to move to the next detection position. The embedded control system uses the actual photoelectric trigger signal as the basis for each stop and acquisition.
9. The non-destructive testing system for maize seed vigor based on near-infrared spectroscopy according to claim 7, characterized in that, The combined preprocessing module provides a variety of preprocessing methods, including standard normal variable transformation, multivariate scattering correction, derivative transformation, and Savitzky-Golay smoothing. Users can select multiple methods and freely sort them to form a combined preprocessing chain to perform chain-like processing on the original spectral data. The combined preprocessing module also supports real-time preview of the comparison between the original spectral curve and the preprocessed spectral curve during the processing.
10. The non-destructive testing system for maize seed vigor based on near-infrared spectroscopy according to claim 7, characterized in that, The model dynamic loading and inference module has a unified model loading interface, which allows users to select and load the trained seed viability discrimination model file from an external storage device. The model dynamic loading and inference module automatically identifies the deep learning framework type corresponding to the model file by analyzing the file extension; the deep learning framework type includes at least one of the Scikit-learn framework, Keras framework, PyTorch framework and ONNX framework. Based on the identified framework type, the model dynamic loading and inference module dynamically loads the runtime environment that matches the framework and parses the model file into a discriminative model instance that can be called.
