Harnessing hyperspectral imaging and machine learning techniques for accurate discrimination of peanut plants and weeds Authors: Adel Bakhshipour, Shahriar Ramezanpour Published: 2025 ABSTRACT AbstractEffective weed detection for precise management remains a pertinent issue in modern agriculture. In this study, hyperspectral imaging (HSI) was combined with machine learning (ML) to differentiate between peanut plants and four common weeds found in peanut fields. Several spectral preprocessing methods—Moving Window Averaging (MWA), Median Filtering (MF), Gaussian Filtering (GF), and Savitzky–Golay smoothing (SGS)—were applied. Feature selection algorithms, including Correlation-based feature selection (CFS), Principal Components Analysis (PCA), and Wrapper Feature Selection (WFS), were then used to extract the most informative wavelengths. Among the various classifiers evaluated, the combination of MF preprocessing, WFS algorithm, and LDA classifier (MF-WFS-LDA) achieved the best performance, while the WFS method selected 12 optimal wavelengths from a total of 465. The accuracy, precision, recall, and RMSE values of this model in the training stage were 99.71%, 0.997, 0.997, and 0.054, respectively. These statistics were 96.67%, 0.967, 0.968, and 0.088, respectively, in the test stage. Furthermore, it successfully differentiated peanuts from each weed species using a minimal number of optimal wavelengths. These findings highlight the potential of integrating HSI with ML for precise weed detection in peanut cultivation. However, further validation under diverse environmental and field conditions is recommended.Keywords: Linear discriminant analysis, Precision agriculture, Spectral signature, Weed detection, Wrapper feature sectionSubject terms: Engineering, Environmental sciences, Mathematics and computing, Plant sciences Introduction Peanut (Arachis hypogaea) is among the important agricultural species cultivated in most tropical and subtropical regions1. Also known as groundnut, this crop is appreciated for its various applications in both food and non-food industries. Peanuts are a nutritious food source that is high in protein, carbohydrates, unsaturated fats, vitamins, and minerals, with multiple health benefits2. Furthermore, this oil-rich seed is widely used in the oil extraction industry and for producing processed products such as peanut butter, chocolate, and animal feed3. Currently, the top producers of peanuts are China, India, Nigeria, the United States, and Sudan4. Over the last ten years, the area devoted to groundnut crops has expanded significantly from 27.2 million hectares in 2013 to approximately 30.5 million hectares in 2022. This increase in cultivation has led to a rise in production, which grew from about 47.0 million tons to 54.2 million tons during the same period5. Weed infestation induces a critical challenge in peanut production, as it can considerably diminish overall productivity. Weeds compete intensely with crops for essential resources such as light, water, nutrients, and space, making them a major constraint in peanut cultivation6. Weeds can also serve as hosts for insects and diseases, negatively impacting the pegging, and podding stages of peanuts and reducing both the quality and quantity of the final product7. A previous study has indicated that weed-related reductions in peanut yields can be as high as 70%8, which shows the critical importance of implementing effective weed control strategies in peanut production. Conventional weed control methods include mechanical, chemical, and manual techniques9. Mechanical control, such as plowing, is environmentally friendly but labor-intensive and energy-consuming, with potential crop damage. Chemical control using herbicides is cost-effective for large areas but risks weed resistance, environmental pollution, and health hazards. Manual weeding, while accurate, is time-consuming and inefficient for large-scale farms10,11. The adoption of advanced and precise methods for weed detection and management has become a necessity in modern agriculture. Advanced technologies such as imaging systems, artificial intelligence (AI), and machine learning (ML) have revolutionized weed management by significantly enhancing accuracy and reducing costs12. These tools enable precise weed identification and localized application of control measures, thereby minimizing herbicide usage, lowering operational costs, and mitigating environmental impacts13. Moreover, the challenges posed by climate change, including altered weed growth dynamics and increased crop competition, render traditional methods insufficient. Cutting-edge technologies address these issues by analyzing environmental data and modeling weed growth patterns, enabling anticipatory and effective management strategies14. Additionally, the overuse of chemical herbicides has escalated the emergence of herbicide-resistant weed species, complicating control efforts. Precision techniques, such as site-specific herbicide application, address this challenge by targeting infested areas, thereby reducing the likelihood of resistance development15. These innovations align with the principles of sustainable agriculture by integrating spatial and temporal data for precision farming, improving economic outcomes while reducing ecological impacts16. Hyperspectral imaging (HSI) combines imaging and spectroscopy to collect and process detailed information across the electromagnetic spectrum17. Unlike traditional imaging systems that capture data in three broad bands (RGB), HSI operates by acquiring data across hundreds of narrow spectral bands. This process generates a three-dimensional “data cube”, where the two spatial dimensions represent the physical layout of the scene, and the third spectral dimension contains the reflectance data at each wavelength. This rich spectral information enables HSI to effectively distinguish materials with even subtle differences in their chemical composition18,19. Full descriptions of HSI systems and their recent applications in different agricultural sectors have been adequately detailed in several recent review articles20,21. HSI techniques are utilized across a vast range of agro-industrial applications from monitoring the soil water22 and nutrient23 contents, precision tillage24, crop health evaluation25, precise weed management26, and site-specific fertilization27, to species recognition28, yield mapping and prediction29, as well as crop quality assessment30. ML is a subdivision of AI that enables computers to learn from data and make predictions without explicit programming. It is widely used in many industries due to its ability to identify patterns in large datasets and make data-driven decisions31. ML involves a combination of various data preprocessing, feature selection (FS), and modeling methods to achieve a specific pattern recognition or prediction goal. ML techniques are categorized into supervised learning, unsupervised learning, reinforcement learning, and semi-supervised learning approaches, which are discussed in detail in a review article32. The integration of appropriate ML methods with HSI technology significantly enhances the analysis and interpretation of these high-dimensional datasets. This combination is particularly impactful in fields such as agriculture and environmental monitoring, where the need for precise data interpretation is critical33. By leveraging advanced ML algorithms, large volumes of spectral data acquired through HSI can be efficiently processed, classified, and analyzed, leading to more accurate, reliable, and timely decision-making processes34. The integration of HSI systems with ML algorithms for recognition operations in various agricultural fields is reported in recent informative review articles34,35. Su36 wrote a comprehensive review article on the application of ML techniques to discriminate crops and weeds using RGB, point spectroscopy, and HSI systems. A recent study applied HSI in conjunction with ML algorithms to detect weeds within agricultural fields. Multilayer Perceptron (MLP) based on the spectra and superpixels (Sp) method produced the most reliable and robust prediction result (89.1% accuracy)37. HSI in the range of 450–998 nm, after applying different preprocessing and wavelength selection/reduction algorithms was used for the detection and classification of Invasive alien plants (IAPs). The support vector machines (SVM) model was able to discriminate seven IAPs with an overall accuracy of 89.39%38. In another study, an HSI system in the spectral range of 450–998 nm was used for the detection of Mikania micrantha Kunth, as a dangerous invasive weed. Principal Component Analysis (PCA) was employed to reduce the dimensionality of hyperspectral data prior to applying SVM and Random Forest ML models. Results showed that a combination of Savitzky-Golay smoothing (SGS), PCA, and RF achieved an accuracy of 88.71%. In contrast, the SG-PCA-SVM combination resulted in a weaker accuracy of 84.68%39. Despite advancements in precision agriculture, accurate identification and classification of weeds among main plants remains a challenge. Furthermore, our literature review indicates that most previous studies focused on for weed detection in major crops such as wheat, rice, and maize, and there is a lack of research investigating HSI and ML for discrimination between peanuts and weeds so far. To fill this gap, this research aims to evaluate the effectiveness of HSI and ML to accurately differentiate weeds from peanut plants. A comprehensive hyperspectral-based framework was developed for discriminating peanut plants from four common weed species. Different spectra preprocessing methods applied, followed by supervised, unsupervised, and wrapper feature selection (WFS) methods, and the optimal wavelengths were introduced to various classical classifiers to distinguish peanut plants from weeds. Unlike conventional wavelength selection approaches such as CARS or UVE, which are used in relevant research, the WFS strategy directly evaluates and optimizes wavelength subsets according to each classifier’s performance. This facilitates more targeted and effective wavelength selection, along with improved discrimination performance. Material and methods Hyperspectral data acquisition The study was conducted on the peanut plant (Arachis hypogaea) along with four common weeds found in peanut cultivation fields, including Jimsonweed (Datura stramonium) called as weed1 in this study, Pigweed (Amaranthus blitum) as weed2, Common lambsquarters (Chenopodium album) as weed3, and Common purslane (Portulaca oleracea) as weed4. The species examined in this study were formally identified by Mr. Hossein Asaadi, an expert in plant taxonomy and breeding, and the head of the Plant Breeding and Agriculture Laboratory and the Herbarium at the Faculty of Agricultural Sciences, University of Guilan, with over 25 years of professional experience in this field. Voucher specimens of all studied plant species have been deposited in the Herbarium of the Faculty of Agricultural Sciences, University of Guilan, and registered with voucher numbers FAA926, SOD846, AMA1100, AMC329, and POP204 for Arachis hypogaea,Datura stramonium,Amaranthus blitum, Chenopodium album, and Portulaca oleracea, respectively. Sample images of these species are provided in Fig. 1. Hyperspectral images of the plant and weed samples were obtained on May 29, 2022, from a peanut field in Astaneh Ashrafiyeh County, (latitude 37°16’ N, longitude 49°56’ E, with an altitude of about 3 m), situated near the Caspian Sea in northern Iran. Sample images of studied plants; (a) peanut, common purslane, common lambsquarters, and jimsonweed, (b) peanut, pigweed, and jimsonweed, (c) peanut and common purslane. The workflow of in study is graphically illustrated in Fig. 2. Fresh peanut and weed plants were carefully uprooted from the field with their roots intact and immediately transferred to the laboratory. During transport, the samples were kept under shaded and cool conditions, and their roots were wrapped in moist paper towels to prevent dehydration and to minimize physiological changes. A hyperspectral imager (HYSPIM, HSI-Vis-NIR_15 fps) was employed to capture hyperspectral images in the 400–950 nm wavelength range. The system comprised a line-scanning imager, four 150W halogen lamps for illumination, an RGB camera, and a horizontally moving platform for sample positioning. The plant samples were placed on the platform and the imager lens was placed 25 cm above the samples. The exposure time and platform speed were adjusted to 0.3s and 3mm/s, respectively. The resulting raw hypercubes had dimensions of 122 × 130 spatial pixels and 568 spectral bands. Graphical representation of the methodological workflow of this study, from data acquisition to model evaluation. The raw hyperspectral reflectance data () were then calibrated using white and dark reference images, where the dark reference image (), with almost 0% reflectance, was taken with the lights off and an opaque cap on the lens. The white reference image (), with an almost 99% reflectance, was obtained from a calibration standard Teflon whiteboard provided by the HSI manufacturer. The calibrated data cubes () were calculated using Eq.140 for further analysis. During the initial assessments, to eliminate reflectance measurements with high noise-to-signal ratios, the noisy wavelengths at the beginning and end of the spectra were excluded from further analysis. Consequently, the wavelengths retained for analytical operations ranged from 450 to 900.6 nm, which corresponds to a total of 465 wavelengths. Afterward, three blocks of 16 × 16 pixels were manually cropped from the regions corresponding to species images in each data cube. These blocks were selected to represent typical leaf areas and avoid background and overlapping areas. The average spectral values across these three regions were then calculated for each wavelength to represent the reflectance spectrum of each sample. A total of 100 samples were collected from each species, resulting in a total number of 500 samples overall. Methodology overview This study used a stepwise strategy to obtain the most effective classification structure for distinguishing peanut plants from four common weeds in the fields. To mitigate the noise effect on the reflectance values, various preprocessing methods including Moving Window Averaging (MWA), Median Filtering (MF), Gaussian Filtering (GF), and Savitzky–Golay smoothing (SGS) were applied to the spectral data and the preprocessed spectra were then saved for further analysis. Further, to reduce the number of analyses, in the first stage, feature selection algorithms were applied to the raw data in the range of 450 nm to 900.6 nm. The optimal wavelength vectors were used for peanut and weed discrimination using different classifiers. Further details of this methodology are explained below. Pretreatment of spectra Hyperspectral data preprocessing methods are widely used in spectral-based studies to reduce the effect of noise and enhance data quality, thereby improving the extracted features and better interpretation41. In this study, four smoothing algorithms were applied to the original raw reflectance spectra, including Moving Window Averaging (MWA), Median Filtering (MF), Gaussian Filtering (GF), and SGS. The preprocessing algorithms were performed with the window sizes of 7. In the MWA and MF methods, the statistical average and median reflectance values are calculated within a sliding window and replaced at the window’s central wavelength. Gaussian smoothing removes noise by discrete convolving the signal with a Gaussian function42. In the SGS technique, the polynomial and least squares fitting is performed to calculate the value of the window’s center43. In this study, the SGS algorithms used a polynomial order of 2. The spectra preprocessing operations were performed in Unscrambler software (version X10.1; CAMO, Norway). Wavelength selection In the development of classification models to differentiate between weeds and peanut plants, spectral reflectance values are used as input variables for the classifiers. Therefore, there were 465 input features for model training in this study. The high number of input features can increase the complexity and the time required for both the development and operation of the model. Additionally, some of these input features (reflectance values) may not significantly impact recognition and could even impair the model’s performance. To address this issue, feature selection/reduction methods were employed to eliminate redundant or repetitive variables, thereby reducing dimensionality, minimizing complexity, and preventing potential overfitting. Three general feature selection strategies were investigated in this study, including Correlation-based Feature Selection (CFS), which is a supervised method; PCA, which is an unsupervised method; and WFS, which is a model-based feature selection method. The CFS method selects a subset of features from the original data that contributes most to predicting the data class while maintaining minimal inter-correlation among the selected features44. PCA is used to transform the initial spectral data into a set of linearly independent variables called PCs45. The WFS method selects a subset of wavelengths so that the performance of a particular classifier is optimized46. In this study, WFS using Best First Search (BFS) algorithm was performed based on maximizing accuracy and minimizing Root Mean Squared Error (RMSE). BFS is a widely used heuristic algorithm for reducing the number of selected features in small-scale attribute sets47. Classification algorithms Four classification algorithms were used to differentiate peanut plants from four studied weed species based on their spectral data, namely LDA, SVM, RF, and k-Nearest Neighbors (kNN). LDA is a supervised classification method that maps the data to a new space based on the separability of data. The purpose of this method is to transform the data to a new space in such a way that the inter-class variance of the data in the new space is maximum whilst the inter-class variance of the data is minimum48. SVM is a supervised learning method used for categorizing data into classes. It achieves this by mapping data points into a high-dimensional space using kernel functions and formulating hyperplane equations that best separate the different classes of data49. In the SVM model, the polynomial kernel function was employed and the error penalty parameter (c) was set to 1. The RF classifier is a widely used supervised learning algorithm that employs ensemble learning. Rather than depending on a single decision tree, the RF classifier combines multiple decision trees to classify a dataset. The final classification result is determined by the majority vote from the decisions made by these trees on various subsets of the data50. KNN is a supervised classification algorithm that assigns data points to specific groups without requiring assumptions about the distribution of the data. The classification decision in kNN is done solely based on the values of neighboring data points51. The letter "k" represents the number of closest neighbors considered, and in this study, it was set to 1. Analytical operations including feature selection and model development were performed in WEKA software environment (version 3.9.6, University of Waikato, Hamilton, New Zealand). Performance evaluation To develop the classification models, the dataset was randomly divided into two groups: 70% for training and 30% for evaluation. A tenfold cross-validation algorithm was employed during the training process to avoid overfitting and ensure the generalization of the results. The performance of the models was evaluated based on four criteria, namely; accuracy, precision, recall, RMSE, and F1 score to provide a more holistic view of model performance and robustness. Models with a higher accuracy and F1 score, and a lower RMSE were considered superior. In the models with similar accuracy and RMSE values, the precision and recall measures were considered, with higher values of these metrics being more desirable. A thorough explanation of these criteria and their calculation formulas is provided in the literature52–54. Results and discussion Results of spectra pretreatment methods The results of applying various preprocessing methods to the reflectance spectra of the studied plants are illustrated in Fig. 3. As shown in Fig. 3(b) to Fig. 3(e), all the applied filters successfully reduced local noises in the spectral curves. Each spectrum in these figures represents the average reflectance of three 16 × 16 pixel ROIs per sample. The smoothing algorithms were highly effective at removing impulse noises, which is common in hyperspectral data, thereby increasing the signal-to-noise ratio. It is also observed that the general trend of the treated spectra did not show a significant difference when compared to the raw spectra. This shows that the impact of error factors on the changes in the recorded spectra was very little, and the spectral reflectance was predominantly influenced by the condition of the plants. This quality was because the hyperspectral images of the plants were taken under controlled environmental conditions. Consequently, the results of the analyses of this study are unlikely to be affected by potential errors, noise, or random factors. The raw (a) and pretreated reflectance spectrum of plant samples using the MWA (b), MF (c), GF (d), and SGS (e) methods (Green line peanut, orange line weed1, maroon line weed2, red line weed3, and blue line weed4. Moreover, Fig. 3 shows that the spectral reflectance trends of different plants are very similar. At many wavelengths, the spectral reflectance of peanut plants closely resembles those of various weeds. As a result, the reflectance data at these wavelengths does not provide useful information for distinguishing peanut plants from the examined weeds, making them redundant. Therefore, feature selection methods can be employed to eliminate these non-informative wavelengths. Optimal classifier structure CFS, PCA, and WFS feature selection methods were applied to the raw spectral data of plants (465 wavelengths from 450 nm to 900.6 nm) and the selected wavelengths were used fed into four different classifiers. The results of these models are presented in Table 1. The performance metrics indicate that the accuracies of most of the investigated algorithms were very high for the differentiation of plant species. This suggests that the spectral reflectance of plants contains suitable discriminatory information for distinguishing the plant species and possesses the potential for effective application in weed detection. Table 1Results of evaluated classifiers for discrimination of plant and weeds using raw spectral data and feature selection methods.ClassifierFS methodNo. of wavelengthsAccuracyPrecisionRecallRMSEF1 scoreLDA-46598.570.9860.9860.0900.986CFS2796.570.9660.9660.1060.966PCA995.710.9580.9570.1190.957WFS1399.140.9910.9910.0800.991SVM-46597.710.9780.9770.3180.977CFS2797.140.9720.9710.3180.971PCA997.430.9750.9740.3180.974WFS1598.290.9830.9830.3170.983RF-46591.710.9180.9170.1610.917CFS2792.290.9240.9230.1530.923PCA993.710.9370.9370.1550.937WFS1494.570.9470.9460.1450.946kNN-46591.710.9210.9170.1810.917CFS2794.860.9500.9490.1420.948PCA994.860.9520.9490.1420.948WFS1395.710.9590.9570.1300.957 Results of evaluated classifiers for discrimination of plant and weeds using raw spectral data and feature selection methods. Evaluation of the feature selection algorithms demonstrated that, from the original set of 465 wavelengths, the supervised CFS method identified 27 wavelengths as significant features for classification, while the unsupervised PCA method generated 9 input vectors. In the context of the WFS methodology, the chosen features were contingent upon the classifier model, resulting in different counts ranging from 13 to 15 wavelengths across different models. It was also observed that, across all models, the application of the WFS yielded superior performance outcomes. The WFS method exhibits a considerable decrease in the number of input features. It also improved the classification accuracy in comparison to the raw, CFS-selected, and PCA-generated input vectors. Consequently, the WFS method was designated as the optimal technique for the reduction of input wavelengths in the further analyses of this research. Moreover, it was observed that the integration of the WFS method with the LDA classifier resulted in the highest classification accuracy. The accuracy of the WFS-LDA model was 99.14%. The RMSE and F1 score of this classifier were 0.080 and 0.991, respectively. Therefore, to evaluate and select the most effective wavelength treatment methods in the following steps, different preprocessing methods were combined with the WFS method along with the LDA classifier, while other feature selection methods and classifiers were not considered in the search for the optimal structure. In the subsequent step, four spectra processing algorithms of MWA, MF, GF, and SGS were applied to the wavelength data. Then, the treated wavelengths were fed to the WFS algorithm to select the optimal wavelengths. Afterward, the classification structures were developed and compared using WFS-selected features. The resulting performance metrics of the model training stage are shown in Table 2. This table shows that applying signal smoothing algorithms in our study causes a slight increase in the accuracy of the classification algorithm. In this regard, the performance metrics of all models were higher than those obtained with raw data after WFS (99.14%). Moreover, the MF-WFS-LDA model has achieved the overall classification accuracy of 99.71% among the evaluated arrangements. The precision, recall, RMSE and F1 score of this model in the training stage were 0.997, 0.997, 0.054, and 0.997 respectively, which were the most appropriate statistics among the developed models. Table 2Results of WFS-LDA models for discrimination of plant and weeds using different processed spectral data in the training stage.Processing algorithmNo. of wavelengthsAccuracy (%)PrecisionRecallRMSEF1 scoreMWA1199.430.9940.9940.0590.994MF1299.710.9970.9970.0540.997GF1099.140.9920.9910.0670.991SGS1199.430.9940.9940.0580.994 Results of WFS-LDA models for discrimination of plant and weeds using different processed spectral data in the training stage. Since there was a small difference between the performances of the compared structures, the ability of classifiers was also evaluated on a separate dataset to decide the best model. The LDA models based on the WFS algorithm were applied to the raw and different processed spectral data. The test results are available in Table 3. The results of this table confirm that the developed structures had a high ability to classify peanut plants and weeds. In the test stage, the maximum classification accuracy was 96.67% obtained by MF-WFS-LDA model, while the RMSE and F1 score of this model were 0.088 and 0.967, respectively, showing the highest performance of MF-WFS-LDA model among the evaluated combinations. Therefore, the MF-WFS-LDA structure was chosen as the best structure to classify peanut plants from weeds. The lowest performance in the test stage belonged to the raw data given to WFS-LDA (accuracy = 94.67, RMSE = 0.119, and F1 = 0.950), which proves the effectiveness of the spectra processing process in increasing the performance of the classification model. Table 3Results of WFS-LDA models for discrimination of plant and weeds using raw and different processed spectral data in the test stage.Model structureAccuracy (%)PrecisionRecallRMSEF1 scoreRaw spectra-WFS-LDA94.670.9470.9540.1190.950MWA-WFS-LDA96.000.9600.9600.0940.960MF-WFS-LDA96.670.9670.9680.0880.967GF-WFS-LDA95.330.9530.9580.1010.955SGS-WFS-LDA96.000.9600.9620.0950.961 Results of WFS-LDA models for discrimination of plant and weeds using raw and different processed spectral data in the test stage. The MF method was found effective in smoothing spectra and eliminating noise in precision agriculture studies using HSI55,56. The results of this study also conform the reports on the effectiveness of WFS methods for identifying optimal wavelengths in HSI for precision agriculture57,58. The LDA method was introduced by Che’Ya, et al.59 as an effective method for detecting weeds from sorghum plants using hyperspectral data. The LDA model was also able to discriminate dicot weed from the corn crop using blue-green fluorescence spectral data (400–490 nm)60. Tables 2 and 3 also show that the SGS method performed very well, achieving high overall accuracy of 99.43% during the training stage and 96.00% in the test stages of the WFS-LDA model. This indicates the high reliability and stability of this method in this study. Previous studies have shown that the SG-based preprocessing methods, such as smoothing and first-order and second-order SG, demonstrate outstanding performance for spectral data preprocessing in agro-food studies61–64, confirming that the SG method can be used as a reliable and efficient preprocessing technique for analyzing plant hyperspectral data and detecting weeds. The confusion matrices of MF-WFS-LDA for discrimination of peanut and weed plants in the training and test stages are presented in Table 4. Table 4Confusion matrices of MF-WFS-LDA model for discrimination of plant and weeds in training and test stages.ClassTrainTestPeanutWeed1Weed2Weed3Weed4PeanutWeed1Weed2Weed3Weed4Peanut690001290001Weed1070000027030Weed2007000003000Weed3000700010290Weed4000070000030 Confusion matrices of MF-WFS-LDA model for discrimination of plant and weeds in training and test stages. Another important point is the number of selected wavelengths. In the MF-WFS-LDA model, the obtained classification performances (99.71% in the training stage and 96.67% in the test stage) were achieved with 12 optimal wavelengths, but the other models obtained somewhat lower accuracies by using one or two fewer selected wavelengths. Therefore, since reducing the number of wavelengths is a step towards developing dedicated sensors in the future, if one or two fewer wavelengths are very important for the manufacturer of the desired dedicated sensor in the future, other algorithms are suggested. Selected wavelengths The previous section noted that the WFS method was the most effective approach for selecting optimal features, as it yielded the highest final classification performance. By employing the WFS method, 12 wavelengths were chosen from the MF-preprocessed reflections as discriminative wavelengths. The selected wavelengths 452.8 nm, 520.3 nm, 522.2 nm, 564.3 nm, 570 nm, 674.3 nm, 691.8 nm, 707.4 nm, 712.2 nm, 717.1 nm, 724.9 nm, and 834.1 nm. An examination of the wavelengths indicates that there is one wavelength in the blue range, four in the green range, four in the red range, and one in the near-infrared range. This suggests that the wavelengths in the visible spectrum significantly contribute to the detection and discrimination of peanut plants and the weeds studied. However, it is important to note that using a conventional camera for color imaging may not provide high resolution for distinguishing between the studied plants. Unlike a conventional camera, which provides three layers of images, the studied plants of this research required 12 different wavelengths in the visible range to be effectively identified. The average and standard deviation of the spectral reflectances of the studied plants are illustrated in Fig. 4. It is evident how the reflectance values vary across different ranges. Notably, the spectral reflectance values of different plants between 725 and 775 nm are very similar, making it difficult to select an optimal wavelength from this range. Furthermore, in the range of 775 nm to 900 nm, only one specific wavelength has been identified as optimal. This selection is likely due to the high intercalation of spectral data within this range, which narrowed the options down to just one wavelength. This is also true for the wavelength range of 450 nm to 525 nm. Eventually, several local extrema can be observed in the spectral reflectances between 525 and 725 nm. This particular range contains the most discriminating wavelengths, highlighting the differences in the spectral behavior of the plants in this waveband. In a related research, the spectral region of 550 nm to 750 nm was reported to have informative wavelengths for differentiating broadleaf weeds from soybean leaves37. Average values and standard deviation ranges of spectral reflectance for the studied plants within the spectral range of 450 nm to 900.6 nm. Discrimination of peanut plants from individual weeds Due to the high performance of the LDA model and the MF preprocessed data, this combination was used in conjunction with the WFS feature selection method to separate peanut plants from weeds individually. The results are presented in Table 5. It was obtained that the MF-WFS-LDA combination resulted in high accuracies (> 99.29% in the training stage) for the classification of peanut plants from each of the weeds individually. This shows that there are some distinctive points in the spectral reflectance of these plants that can be effectively used to distinguish these weeds from peanuts. This structure was assessed using separate test data, yielding accuracies of 98.33%, 95.00%, 96.67%, and 91.67% for discriminating the peanut plants from weed1, weed2, weed3, and weed4, respectively. The confusion matrices of these models for discrimination of individual weeds from peanut plat are available in Table 6. Table 5Results of MF-WFS-LDA models for discrimination of plant from individual weeds in training and test stages.Discriminated weed from peanutNo. of wavelengthsTrain/testAccuracy (%)PrecisionRecallRMSEF1 scoreWeed13Train100.001.0001.0000.0361.000Test98.330.9840.9830.1100.983Weed24Train100.001.0001.0000.0331.000Test95.000.9550.9500.1270.952Weed33Train99.290.9930.9930.1100.993Test96.670.9690.9670.1420.968Weed410Train99.290.9930.9930.1050.993Test91.670.9170.9170.2170.917 Results of MF-WFS-LDA models for discrimination of plant from individual weeds in training and test stages. Table 6Confusion matrices of MF-WFS-LDA model for discrimination of plant from individual weeds in the training and test stages.ClassTrainTestClassTrainTestPeanutWeed1PeanutWeed1PeanutWeed2PeanutWeed2Peanut700300Peanut700273Weed1070129Weed2070030ClassPeanutWeed3PeanutWeed3ClassPeanutWeed4PeanutWeed4Peanut691282Peanut700282Weed3070030Weed4069327 Confusion matrices of MF-WFS-LDA model for discrimination of plant from individual weeds in the training and test stages. Table 5 also reports that the WFS resulted in a limited number of identifying optimal wavelengths for separating weeds from the peanut plant. Specifically, 3, 4, 3, and 10 optimal wavelengths were selected for distinguishing weed1, weed2, weed3, and weed4, respectively. These chosen wavelengths enable the design of customized optical sensors that can effectively detect each of these weeds and differentiate them from peanut plants in practical applications. The optimal wavelengths for distinguishing weed1 from peanut were 455.7 nm, 508.8 nm, and 685. For distinguishing weed2 from peanut, four wavelengths (456.6 nm, 501.2 nm, 697.6 nm, 724 nm) were selected as optimal wavelengths. The wavelengths selected for distinguishing weed3 from peanut were 457.5 nm, 509.8 nm, and 685.9 nm. Unlike the previous three cases, the number of wavelengths selected to separate weed4 from the peanut plant was greater. Ten optimal wavelengths (551.8 nm, 552.8 nm, 569 nm, 571.9 nm, 574.8 nm, 575.8 nm, 644.2 nm, 696.6 nm, 705.4 nm, and 720.1 nm) were selected for distinguishing peanut from weed4. This shows that making a dedicated sensor to separate each of Weed1, Weed2, and Weed3 from the peanut plant is much easier and more reliable than making a dedicated sensor to separate Weed4 from the peanut plant. The plots of average and standard deviation for the spectral reflectances of the peanut plant and each of the studied weeds are shown separately in Fig. 5. For weed1 and weed3, the differences in spectral reflectance between these weeds and the peanut plant are noticeable in the range of less than 525 nm, as well as between 600 and 700 nm. In the case of weed2, there is a slight difference in reflectance between the peanut plant and this weed, observed in the range from 675 to 725 nm. For weed4, the overlap in spectral reflectance of this weed with the peanut plant is greater than those observed for the other three weeds. Therefore the number of selected wavelengths to achieve a desired classification accuracy was greater in the case of weed4. Also in the case of weed4, the final classification accuracy on the test data was significantly lower than for other weeds. Average values and standard deviation ranges of spectral reflectance for the peanut and individual weeds within the spectral range of 450 nm to 900.6 nm. (a) weed1, (b) weed2, (c) weed3, and (d) weed4. The findings of this study align with previous research on the effective combinatorial use of HSI and ML for detecting invasive weeds. It was reported that barnyard grass and weedy rice species can be recognized from rice crop using HSI and ML methods65. This methodology was employed to identify Mikania micrantha with an accuracy of 88.71%39. Additionally, it was effectively applied to differentiate Palmer amaranth from soybean plant, achieving an accuracy of 93.95%66. Eventually, it should be recognized that despite the high classification accuracies achieved in this study and related research, some limitations still exist. The hyperspectral data were collected from a single geographical region using samples grown under specific environmental and cultivation conditions. Therefore, the model’s ability to generalize to other locations, environmental variations, different growth stages, or additional weed species remains uncertain. Moreover, the classification performance was evaluated using controlled HSI setups, which may differ from field-based imaging conditions. Therefore, further studies are required to validate the robustness and practical applicability of the proposed method under diverse field conditions and in operational environments. It is important to note here that the combination of a BFS-based WFS algorithm with LDA classifier yielded the most desirable results in this study. The BFS algorithm is a well-known heuristic search strategy in AI, particularly effective for feature selection67. Meanwhile, LDA highlights the most discriminative features during the classification. Therefore, the integration of BFS-based WFS with LDA in this study provided a hybrid-like multi-step wavelength selection framework, whose advantage over other methods was evident from the performance statistics. Previous studies indicate that hybrid or multi-step approaches are generally more effective in identifying optimal wavelengths for detection problems68–70. Conclusion In modern precision agriculture, accurate discrimination between crops and weeds is a critical requirement to enhance crop management and reduce reliance on herbicides. In this study, a classification approach based on HSI and ML techniques was developed for weeds detection in peanut cultivation fields, including Jimsonweed, Pigweed, Common lambsquarters, and Common purslane. A stepwise approach was employed to ensure that important factors influencing the model’s performance were addressed. In this regard, different spectra preprocessing methods (MWA, MF, GF, and SGS), followed by feature selection algorithms (CFS, PCA, and WFS) and classifiers (LDA, SVM, RF, and kNN), were developed for the differentiation of the peanut plant from four common weeds in peanut cultivation. The performance of classifiers was evaluated using multiple metrics (accuracy, precision, recall, RMSE, and F1 score). The MF-WFS-LDA combination provided the best overall performance among the tested models, achieving a training accuracy of 99.71% and a test accuracy of 96.67% using 12 selected wavelengths out of 465 primary wavelengths. This configuration also achieved high classification performance in distinguishing peanut plants from each weed species individually, with training accuracies of 100.00%, 100.00%, 99.29%, and 99.29%, respectively. The corresponding test accuracies were 98.33%, 95.00%, 96.67%, and 91.67%. These results were obtained using 3, 4, 3, and 10 WFS-selected wavelengths, respectively. The results of this study highlight the potential of combining HSI with ML algorithms for effective weed discrimination in controlled conditions and a specific geographical location. However, further research is recommended to evaluate the robustness and applicability of this method across diverse environmental conditions and field scenarios. It is also important to note that, this study was conducted using a limited dataset of 500 samples. To develop a commercial hyperspectral weed detection system, future investigations are needed with a significantly larger database size, more weed types, and real field conditions. In this regard, modern modeling approaches such as deep learning are proposed to enhance the detection performance. Acknowledgements The authors would like to thank the University of Guilan for its support of this research. Author contributions A.B. conceptualized the study, administered the project, developed the methodology, conducted the investigation, implemented the software, curated the data, performed the formal analysis, wrote the original draft, and contributed to the review and editing of the manuscript. S.R. contributed to the investigation and formal analysis, wrote the original draft, and participated in the review and editing of the manuscript. Funding This research did not receive any external funding. Data availability Data will be made available on request. Declarations Competing interests The authors declare no competing interests. Ethics The research was conducted in accordance with the ethical guidelines established by the University of Guilan. As this study involved commonly cultivated agricultural plants and did not include genetic modification, environmental release, or work with protected species, it was exempt from formal ethics committee approval. Therefore, no specific ethics approval was required for this research. Footnotes Publisher’s note Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations. References Associated Data Data Availability Statement Data will be made available on request.