Skin cancer affects the lives of millions of people every year, as it is considered the most popular form of cancer. In the USA alone, approximately three and a half million people are diagnosed with skin cancer annually. The survival rate diminishes steeply as the skin cancer progresses. Despite this, it is an expensive and difficult procedure to discover this cancer type in the early stages. In this study, a threshold-based automatic approach for skin cancer detection, classification, and segmentation utilizing a meta-heuristic optimizer named sparrow search algorithm (SpaSA) is proposed. Five U-Net models (i.e., U-Net, U-Net++, Attention U-Net, V-net, and Swin U-Net) with different configurations are utilized to perform the segmentation process. Besides this, the meta-heuristic SpaSA optimizer is used to perform the optimization of the hyperparameters using eight pre-trained CNN models (i.e., VGG16, VGG19, MobileNet, MobileNetV2, MobileNetV3Large, MobileNetV3Small, NASNetMobile, and NASNetLarge). The dataset is gathered from five public sources in which two types of datasets are generated (i.e., 2-classes and 10-classes). For the segmentation, concerning the “skin cancer segmentation and classification” dataset, the best reported scores by U-Net++ with DenseNet201 as a backbone architecture are 0.104, $$94.16\%$$
94.16
%
, $$91.39\%$$
91.39
%
, $$99.03\%$$
99.03
%
, $$96.08\%$$
96.08
%
, $$96.41\%$$
96.41
%
, $$77.19\%$$
77.19
%
, $$75.47\%$$
75.47
%
in terms of loss, accuracy, F1-score, AUC, IoU, dice, hinge, and squared hinge, respectively, while for the “PH2” dataset, the best reported scores by the Attention U-Net with DenseNet201 as backbone architecture are 0.137, $$94.75\%$$
94.75
%
, $$92.65\%$$
92.65
%
, $$92.56\%$$
92.56
%
, $$92.74\%$$
92.74
%
, $$96.20\%$$
96.20
%
, $$86.30\%$$
86.30
%
, $$92.65\%$$
92.65
%
, $$69.28\%$$
69.28
%
, and $$68.04\%$$
68.04
%
in terms of loss, accuracy, F1-score, precision, sensitivity, specificity, IoU, dice, hinge, and squared hinge, respectively. For the “ISIC 2019 and 2020 Melanoma” dataset, the best reported overall accuracy from the applied CNN experiments is $$98.27\%$$
98.27
%
by the MobileNet pre-trained model. Similarly, for the “Melanoma Classification (HAM10K)” dataset, the best reported overall accuracy from the applied CNN experiments is $$98.83\%$$
98.83
%
by the MobileNet pre-trained model. For the “skin diseases image” dataset, the best reported overall accuracy from the applied CNN experiments is $$85.87\%$$
85.87
%
by the MobileNetV2 pre-trained model. After computing the results, the suggested approach is compared with 13 related studies.