Mulch film is usually mixed in with cotton during machine-harvesting and processing, which reduces the cotton quality. This paper presents a novel sorting algorithm for the online detection of film on cotton using hyperspectral imaging with a spectral region of 1000-2500 nm. The sorting algorithm consists of a group of stacked autoencoders, two optimization modules and an extreme learning machine (ELM) classifier. The variable-weighted stacked autoencoders (VW-SAE) are constructed to extract the features from hyperspectral images, and an artificial neural network (ANN), which is one optimization module, is applied to optimize the parameters of the VW-SAE. Then, the extracted features are input in the ELM to classify four types of objects: background, film on background, cotton and film on cotton. The ELM is optimized by a new optimizer (grey wolf optimizer), which can adjust the hidden nodes and parameters of the ELM simultaneously. A group of experiments was carried out to evaluate the performance of the proposed sorting algorithm using cotton that was provided by a Xinjiang municipality cotton ginning company. The experimental results show that the VW-SAE can improve the classification accuracies by approximately 15 %. The overall recognition rate of the proposed algorithm is over 95 %, and its recognition time is comparable to some state-of-the-art methods. INDEX TERMS Cotton, sorting system, plastic film, deep learning, hyperspectral imaging, grey wolf optimizer, variable-wise weighted stacked autoencoder.