Lightweight automatic prompt arbitrary segmentation method and device for medical images
By employing a lightweight self-prompting method, utilizing the Hiera-L backbone network and a multi-scale feature refinement network, and combining a semantic attention auto-prompting encoder and a sequential fusion decoder, the contradiction between domain adaptation and lightweight design in medical image segmentation models is resolved, achieving high-precision automatic segmentation.
Patent Information
- Application Number
- CN202611655520.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-10-26
- Publication Date
- 2026-11-24
AI Technical Summary
Existing medical image segmentation models present a contradiction between domain adaptability and lightweight design. They have a large number of parameters and are prone to overfitting, rely heavily on manual prompts, have insufficient encoder feature enhancement, and lack deep multi-scale fusion in the decoder, making it difficult to meet the needs of high-throughput automated clinical processing.
A lightweight self-prompting method is adopted, which generates internal prompting signals by combining a cascaded Hiera-L backbone network and a multi-scale feature refinement network with a semantic attention auto-prompting encoder and a sequential fusion decoder, thereby achieving low-cost domain adaptation and high-precision segmentation.
It achieves low-cost domain adaptation, eliminates reliance on manual prompts, improves segmentation accuracy, and meets the needs of high-throughput automated clinical processing.
Smart Images

Figure CN123160894A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of data processing technology, and in particular to a lightweight automatic prompting method and apparatus for arbitrary segmentation of medical images. Background Technology
[0002] Medical image segmentation is a core technology in precision medicine. Its purpose is to automatically and accurately identify and delineate target regions (such as tumor lesions, organ structures, and diseased tissues) from medical images, such as endoscopic images, ultrasound images, computed tomography (CT) images, and magnetic resonance imaging (MRI) images. This technology is an indispensable foundational tool in high-frequency clinical scenarios such as clinical lesion diagnosis and quantitative analysis, surgical navigation planning, and radiotherapy target delineation.
[0003] Early medical image segmentation methods mainly relied on deep learning segmentation models such as U-Net and TransUNet, which were specifically designed for particular tasks (hereinafter referred to as "dedicated segmentation models"). These models performed well on a single modality and a single task, but they had an essential drawback: whenever faced with a new imaging modality (such as switching from endoscopy to ultrasound) or a new segmentation task, a large amount of labeled data had to be collected again and the model had to be trained from scratch. Their generalization ability was very limited, making it difficult to meet the needs of multimodal and small-sample medical applications.
[0004] In 2023, Meta introduced the Arbitrary Segmentation Model (SAM), which was pre-trained on massive amounts of natural image data. The overall architecture of SAM consists of three parts: an image encoder, a cue encoder, and a mask decoder. In 2024, Meta further released the second-generation version of SAM, SAM2, upgrading the image encoder to a Hiera hierarchical visual Transformer backbone network. This network can output four feature maps at different scales in a single forward propagation (denoted as layers 1 to 4, with 144, 288, 576, and 1152 channels respectively), making it more suitable for subsequent intensive decoding tasks. SAM2's Hiera-L backbone network has approximately 214 million parameters, containing rich general visual prior knowledge.
[0005] However, SAM has the following shortcomings in medical image segmentation scenarios, which seriously restricts its clinical application: 1. The contradiction between domain adaptation and lightweight design: The SAM2 encoder has a huge number of parameters (approximately 214 million), and full fine-tuning is extremely costly and prone to overfitting. Although existing efficient parameter fine-tuning methods (LoRA, linear adapter, etc.) reduce the number of training parameters, their linear or low-rank structures are insufficient for modeling the nonlinear multi-scale features of medical images, resulting in limited domain adaptation effects.
[0006] 2. The problem of dependence on manual prompts: The SAM series models adopt a prompt-driven segmentation paradigm, which requires manual interactive prompts to perform segmentation, and cannot meet the needs of high-throughput automated processing in clinical practice; although existing automatic prompting methods (such as AutoSAM) have eliminated manual prompts, they have not sufficiently adapted the encoder to the domain, and the quality of automatically generated prompt signals is limited.
[0007] 3. Insufficient encoder feature enhancement: Most existing methods directly use the original features output by the SAM encoder, lacking multi-scale receptive field expansion and channel-space dual attention refinement mechanisms for medical images. This results in insufficient enhancement of superficial lesion edge details and deep organ structure semantics, affecting subsequent decoding accuracy.
[0008] 4. Decoder multi-scale fusion is not deep: Existing fully automatic SAM methods (such as SAM2-UNet and DeSAM) mostly use standard convolutional fusion or simple splicing strategies in their decoders, which fail to achieve progressive deep interactive fusion between features of different scales. Under lightweight constraints, it is difficult to simultaneously recover fine boundaries and maintain high-level semantic consistency. Summary of the Invention
[0009] This application proposes a lightweight automatic prompting method and apparatus for arbitrary segmentation of medical images, which can solve one of the problems existing in the background art.
[0010] To achieve the above objectives, this application adopts the following technical solution: Firstly, a lightweight, automatic prompting method for arbitrary segmentation of medical images is provided, including: Obtain the medical image to be segmented; The medical image to be segmented is input into a trained medical image segmentation model to obtain the segmentation result; The medical image segmentation model includes: An image encoder is used to extract N layers of features from medical images using a Hiera-L backbone network based on several cascaded arbitrary segmentation models SAM2, resulting in an N-layer feature map. A multi-scale feature refinement network is used to independently perform multi-scale receptive field expansion and channel-space dual attention calibration refinement processing on the feature maps of the corresponding layers output by the image encoder, to obtain N layers of enhanced image features. A semantic attention auto-cue encoder is used to automatically generate internal cue signals through cross-attention computation between learnable semantic tokens and the enhanced image features of the Nth layer; The decoder is used to perform layer-by-layer decoding of the enhanced image features of the N-1 layers under the guidance of the internal prompting signal, so as to obtain the N-1 layer decoded features; The fusion module is used to fuse the decoding features of layer N-1 to obtain fused features; A prediction head is used to make predictions based on the fused features to obtain a segmentation mask for the predicted target region.
[0011] In one possible design of the first aspect, the Hiera-L backbone network includes several cascaded standard Transformer blocks, each of which has an externally embedded parameter-efficient fine-tuning adapter module, MonaAdapter, to control the trainable parameters of the image encoder to be less than 5% of all parameters, and the parameters of the standard Transformer blocks are frozen during training.
[0012] In one possible design approach of the first aspect, the Hiera-L backbone network is specifically used to perform the following processes in sequence: normalization and learnable scaling, dimensionality reduction projection, multi-scale depth-separable convolution processing, nonlinear activation and regularization, and dimensionality increase projection and residual backinjection. Specifically, the multi-scale depth-separable convolution processing involves performing three consecutive 3×3 depth-separable convolutions to sample the local texture and structural features of the image at multiple levels under different effective receptive fields, while capturing fine-grained edge information and slightly larger-scale texture patterns.
[0013] In one possible design of the first aspect, the multi-scale feature refinement network includes N multi-scale convolutional attention enhancement modules (MSCAEs). Each MSCAE specifically includes a multi-scale receptive field parallel expansion branch (RFB), a channel attention branch (CAB), and a spatial attention branch (SAB). The multi-scale receptive field parallel expansion branch takes the feature map of the corresponding layer output by the image encoder as input. The channel attention branch and the spatial attention branch take the output of the multi-scale receptive field parallel expansion branch as input. The outputs of the multi-scale receptive field parallel expansion branch, the channel attention branch, and the spatial attention branch are fused to obtain the enhanced image features. The multi-scale receptive field parallel expansion branch is used to perform convolution operations with different receptive field ranges. The channel attention branch is used to achieve selective enhancement or suppression of the channel dimension. The spatial attention branch is used to achieve selective focusing of the spatial dimension.
[0014] In one possible design of the first aspect, the semantic attention auto-completion encoder is specifically used for: Group G can learn semantic token initialization; Apply learnable positional encoding to the enhanced image features; Using the learnable semantic token as the query and the image features after being injected with the location encoding as the key and value, multi-head cross-attention calculation is performed to enable the learnable semantic token to aggregate different prompt feature patterns and spatial location information from the image features, thereby generating the internal prompt signal.
[0015] In one possible design of the first aspect, the decoder is specifically used for: The internal prompt signal features are upsampled at layer N-1 to obtain layer N-1 upsampled features. The layer N-1 upsampled features are fused with the layer N-1 enhanced image features to obtain layer N-1 merged features. The layer N-1 grouped spatial multi-scale fusion module is used to process the layer N-1 merged features to obtain layer N-1 decoded features. The grouped spatial multi-scale fusion module includes a main path and several parallel leaf branches. The leaf branches are used to extract corresponding scale features using grouped convolution and fuse the extracted corresponding scale features into the main path in a preset order to obtain fused multi-scale features.
[0016] In one possible design of the first aspect, channel rearrangement is performed after the grouped convolution to redistribute the feature information that was originally isolated in different groups to the groups.
[0017] In one possible design of the first aspect, the N-1 layer decoding features correspond to the main output and N-1 side outputs. The total loss of the medical image segmentation model includes: the main output loss term and the N-1 side output loss terms. Both the main output loss term and the side output loss term include weighted binary cross-entropy loss and weighted cross-union ratio loss.
[0018] In a second aspect, a medical image segmentation apparatus is provided, comprising one or more functional units or modules for performing the method as described in any possible implementation of the first aspect.
[0019] Beneficial effects: Based on the above technical solution, the SAM2 pre-trained encoder is used as the feature extraction base. A lightweight adapter is used to achieve low-cost domain adaptation. An automatic prompting encoder is used to completely eliminate the dependence on manual prompts. Multi-scale enhancement and sequential fusion decoder are used to improve segmentation accuracy. Thus, SAM2 is transformed into a lightweight, self-prompting, and high-precision automatic medical image segmentation model. Attached Figure Description
[0020] To more clearly illustrate the technical solutions in the embodiments of this application, the drawings used in the description of the embodiments or related technologies will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0021] Figure 1 This is a flowchart of the medical image segmentation method provided in Embodiment 1 of this application; Figure 2 This is a structural diagram of the medical image segmentation model provided in Embodiment 1 of this application; Figure 3 This is the overall network framework diagram of the lightweight self-prompting SAM provided in Embodiment 2 of this application; Figure 4 This is a data processing flowchart of the MonaAdapter parameter high-efficiency adapter provided in Embodiment 2 of this application; Figure 5 This is the MonaOp internal data flow diagram provided in Embodiment 2 of this application; Figure 6 This is a schematic diagram of the multi-scale receptive field module provided in Embodiment 2 of this application; Figure 7 This is a schematic diagram of the channel attention module provided in Embodiment 2 of this application; Figure 8 This is a schematic diagram of the spatial attention module provided in Embodiment 2 of this application; Figure 9 This is a schematic diagram of the semantic attention auto-completion encoder provided in Embodiment 2 of this application; Figure 10 This is a schematic diagram of the 3×3 grouped convolution structure provided in Embodiment 2 of this application; Figure 11 This is a schematic diagram of the sequential grouping multi-scale fusion structure provided in Embodiment 2 of this application; Figure 12 This is a flowchart of the training process for the lightweight self-suggesting SAM provided in Embodiment 2 of this application. Detailed Implementation
[0022] To make the objectives, technical solutions, and advantages of this application clearer, the following detailed description is provided in conjunction with the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the scope of this application.
[0023] It should be noted that although functional modules are divided in the device schematic diagram and the logical order is shown in the flowchart, in some cases, the steps shown or described may be performed in a different order than the module division in the device or the order in the flowchart. The terms "first," "second," etc., in the specification and the above-mentioned figures are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence.
[0024] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this application belongs. The terminology used herein is for the purpose of describing embodiments of this application only and is not intended to limit this application.
[0025] Example 1 like Figure 1 As shown, this embodiment provides a lightweight automatic prompting method for arbitrary segmentation of medical images, including: Step S101: Obtain the medical image to be segmented; Step S102: Input the medical image to be segmented into the trained medical image segmentation model to obtain the segmentation result.
[0026] Among them, such as Figure 2 As shown, the medical image segmentation model includes: Image encoder 201 is used to extract N layers of features from medical images based on a Hiera-L backbone network of several cascaded arbitrary segmentation models SAM2, to obtain N layers of feature maps, where N is a natural number greater than 1. The multi-scale feature refinement network 202 is used to independently perform multi-scale receptive field expansion and channel-space dual attention calibration refinement processing on the feature maps of the corresponding layers output by the image encoder to obtain N layers of enhanced image features. Semantic attention auto-cue encoder 203 is used to automatically generate internal cue signals through cross-attention calculation between learnable semantic tokens and the enhanced image features of the Nth layer; Decoder 204 is used to perform layer-by-layer decoding of the enhanced image features of layer N-1 under the guidance of the internal prompt signal, so as to obtain the decoded features of layer N-1. The fusion module 205 is used to fuse the decoding features of layer N-1 to obtain fused features; The prediction head 206 is used to make predictions based on the fused features to obtain a segmentation mask for the predicted target region.
[0027] The Hiera-L backbone network is the flagship hierarchical visual Transformer image / video encoder in the Meta SAM 2 series, a core backbone model that balances accuracy and speed. Compared to the original SAM's ViT-H encoder, Hiera-L has only 35% of the parameters, yet achieves higher mIoU in image segmentation and significantly improved inference speed. Compared to other Hiera variants in the same series, it achieves the optimal balance between accuracy and speed, making it the preferred choice for most general-purpose scenarios.
[0028] In one possible implementation, the Hiera-L backbone network includes several cascaded standard Transformer blocks, each of which has an externally embedded parameter-efficient fine-tuning adapter module (MonaAdapter) to control the trainable parameters of the image encoder to be less than 5% of the total parameters. During training, the parameters of the standard Transformer blocks are frozen.
[0029] The standard Transformer block is the core building block of the Transformer architecture. Whether it is the original Natural Language Processing (NLP) model or the later vision model (such as the basic components in ViT and Hiera-L), its basic structure follows the combination of "self-attention mechanism + feedforward neural network", supplemented by residual connections and layer normalization.
[0030] The parameter-efficient fine-tuning adapter module is a novel method for fine-tuning visual adapters. By adjusting less than 5% of the backbone network parameters, it surpasses the performance of full-parameter fine-tuning in multiple visual tasks, while significantly reducing adaptation and storage costs.
[0031] In one possible implementation, the Hiera-L backbone network is specifically used to perform the following processes in sequence: normalization and learnable scaling, dimensionality reduction projection, multi-scale depth-separable convolution processing, nonlinear activation and regularization, and dimensionality increase projection and residual backinjection. Specifically, the multi-scale depth-separable convolution processing involves performing three consecutive 3×3 depth-separable convolutions to sample the local texture and structural features of the image at multiple levels under different effective receptive fields, while capturing fine-grained edge information and slightly larger-scale texture patterns.
[0032] In one possible implementation, the multi-scale feature refinement network includes N multi-scale convolutional attention enhancement modules (MSCAE). Each MSCAE specifically includes a multi-scale receptive field parallel expansion branch (RFB), a channel attention branch (CAB), and a spatial attention branch (SAB). The multi-scale receptive field parallel expansion branch takes the feature map of the corresponding layer output by the image encoder as input. The channel attention branch and the spatial attention branch take the output of the multi-scale receptive field parallel expansion branch as input. The outputs of the multi-scale receptive field parallel expansion branch, the channel attention branch, and the spatial attention branch are fused to obtain the enhanced image features. The multi-scale receptive field parallel expansion branch is used to perform convolution operations with different receptive field ranges. The channel attention branch is used to selectively enhance or suppress the channel dimension. The spatial attention branch is used to selectively focus the spatial dimension.
[0033] In one possible implementation, the semantic attention auto-completion encoder is specifically used for: Group G can learn semantic token initialization, where G is a natural number; Apply learnable positional encoding to the enhanced image features; Using the learnable semantic token as the query and the image features after being injected with the location encoding as the key and value, multi-head cross-attention calculation is performed to enable the learnable semantic token to aggregate different prompt feature patterns and spatial location information from the image features to generate the internal prompt signal.
[0034] In one possible implementation, the decoder is specifically used for: The internal prompt signal features are upsampled at layer N-1 to obtain layer N-1 upsampled features. The layer N-1 upsampled features are fused with the layer N-1 enhanced image features to obtain layer N-1 merged features. The layer N-1 grouped spatial multi-scale fusion module (GSMF) is used to process the layer N-1 merged features to obtain layer N-1 decoded features. The grouped spatial multi-scale fusion module includes a main path and several parallel leaf branches. The leaf branches are used to extract corresponding scale features using grouped convolution and fuse the extracted corresponding scale features into the main path in a preset order to obtain fused multi-scale features.
[0035] In one possible implementation, channel rearrangement is performed after the grouped convolution to redistribute the feature information that was originally isolated in different groups to the various groups.
[0036] In one possible implementation, the N-1 layer decoding features correspond to the main output and N-1 side outputs. The total loss of the medical image segmentation model includes: the main output loss term and the N-1 side output loss terms. Both the main output loss term and the side output loss term include weighted binary cross-entropy loss and weighted cross-union ratio loss.
[0037] By implementing the above technical solutions, using the SAM2 pre-trained encoder as the feature extraction base, achieving low-cost domain adaptation through a lightweight adapter, completely eliminating reliance on manual prompts through an automatic prompting encoder, and improving segmentation accuracy through multi-scale enhancement and sequential fusion decoders, SAM2 is transformed into a lightweight, self-prompting, and high-precision automatic medical image segmentation model.
[0038] Example 2 This embodiment addresses the two core shortcomings of SAM2 in medical image segmentation: "large parameters" and "cue-driven" approach. It proposes a lightweight, self-cueing medical image segmentation method based on SAM. The core idea is to use a pre-trained SAM2 encoder as a feature extraction base, achieve low-cost domain adaptation through a lightweight adapter, completely eliminate reliance on manual cues through an automatic cue encoder, and improve segmentation accuracy through multi-scale enhancement and sequential fusion decoders. This transforms SAM2 into a lightweight, self-cueing, and high-precision automatic medical image segmentation model.
[0039] The lightweight auto-prompting SAM segmentation method proposed in this embodiment is named "Lightweight Auto-PromptingSAM". It only requires an input RGB medical image to output the segmentation mask of the target region end-to-end, without any form of manual prompting signal.
[0040] This embodiment comprises four stages, which can be understood along two main technical lines: The lightweight approach runs through the first and fourth stages—the Multi-Cognitive Visual Adapter (MonaAdapter) achieves encoder domain adaptation with less than 5% parameters (first stage), and the Sequential Grouped Multi-Scale Lightweight Decoder (SGML-Decoder) achieves low-parameter decoding through "grouped convolution + channel rearrangement" (fourth stage). Together, they reduce the overall training and deployment resource requirements of the model to a level affordable for consumer-grade hardware. The automatic prompting approach runs through the second and third stages—MSCAE performs multi-scale enhancement on encoder features (second stage), and Semantic Attention automatically generates internal prompts from the enhanced features (third stage). Together, they achieve a paradigm shift from "human-driven prompting" to "end-to-end automatic segmentation." These two lines converge at the decoder: the lightweight encoder provides high-quality, low-noise domain features, and the automatic prompting mechanism provides the decoder with segmentation guidance signals that require no manual intervention, jointly supporting high-precision, fully automated medical image segmentation.
[0041] The overall architecture comprises the following four core processing stages in the order of data flow: The first stage – Mona Adaptive SAM Image Encoder (addressing the core defect of "large number of parameters"): The Hiera-L hierarchical visual Transformer of the SAM2 pre-trained model is used as the feature extraction backbone network. The MonaAdapter parameter high-efficiency fine-tuning adapter module designed in this embodiment is embedded outside each standard Transformer block. All original parameters of the backbone network are frozen, and only the adapter parameters (accounting for less than 5% of all parameters) are trained to achieve lightweight domain adaptation.
[0042] The second stage – Multi-scale Convolutional Attention Enhancement Module (MSCAE) (addressing the defect of "insufficient encoder feature enhancement"): The four-layer feature maps output by the encoder are independently subjected to multi-scale receptive field expansion and channel-space dual attention calibration and refinement to suppress background noise, highlight the feature response of the lesion area, and compress the number of channels to a uniform 64 channels.
[0043] The third stage – Semantic Attention-based Semantic Enhancement Auto-Cue Encoder (addressing the core deficiency of "cue-driven"): By calculating the cross-attention between learnable semantic tokens and enhanced image features, it automatically generates internal cue signals, completely replacing the original "manual cue" interaction mode of SAM, and realizing a paradigm shift from "cue-driven" to "end-to-end automatic segmentation".
[0044] The fourth stage – Sequential Grouping Multi-Scale Lightweight Decoder (SGML-Decoder) (addressing the defect of "deep multi-scale fusion of the decoder"): adopts a three-level upsampling structure to restore spatial resolution step by step. Each fusion operation is completed by the upsampling GSMF unit (Up_GSMF) designed in this embodiment, realizing progressive deep interactive fusion of multi-scale features.
[0045] The overall inference data flow can be summarized as follows: Input RGB medical image → Extract four-layer multi-scale features via "Hiera-L backbone + MonaAdapter" → Unify and refine the features of each layer to 64 channels via MSCAE → Generate internal cue signals using SemanticAttention automatic cue encoder → Upsample and fuse grouped multi-scale features using a three-level SGML-Decoder → Output segmentation mask from a 1×1 convolutional prediction head. No manual cue signals are required throughout the entire process.
[0046] This embodiment provides a method for automatic medical image segmentation based on lightweight self-prompting SAM and its training method.
[0047] This embodiment's method is applied to the automatic segmentation of target regions in medical images. During inference, only RGB medical images are received; external prompts such as manual clicks, bounding selections, or coarse masks are not accepted. The network follows... Figure 3 The data stream shown completes feature extraction, multi-scale refinement, internal prompt generation, step-by-step decoding, and result output.
[0048] Combination Figure 3 The automatic medical image segmentation method includes the following steps. The output of each step serves as the input for subsequent steps, and the final output is a medical image segmentation mask corresponding to the method name.
[0049] Step S1: Receive the RGB medical image to be segmented, and use... Figure 3 The image encoder extracts four-layer multi-scale medical image features.
[0050] S1.1: Scale the input image to a preset size; in this embodiment, 352×352 pixels are used and normalized to obtain a normalized three-channel input image.
[0051] S1.2: The input image is first fed into the patch embedding layer, and then into the Hiera-L hierarchical visual transformer backbone. Hiera-L uses a hierarchical structure to extract multi-scale visual features, its original pre-trained parameters are kept frozen, and trainable Mona parameter efficient adapters (MonaAdapter) are embedded around each visual transformer module (Transformer block) to learn medical image domain features while preserving general visual priors.
[0052] S1.3: As Figure 4 and Figure 5 As shown, MonaAdapter receives input feature x, and first calculates x. norm =s1·LayerNorm(x)+s2·x, where s1 is initially 1×10 -6 s2 is initially set to 1; then, through dimensionality reduction projection, the channel dimension is reduced from C to 64, and the tensor is transformed from [B, H, W, C] arrangement to [B, C, H, W] arrangement before being input into MonaOp. MonaOp performs three layers of 3×3 depthwise convolutions in sequence: the output of the first layer is compared with the identity residual x down The sum is then input into the second layer, and the output of the second layer is again summed with x. down The summation is then fed into the third layer; the output of the third layer is fused across channels using a 1×1 pointwise convolution, and then combined with x. down Adding them together gives x conv The tensor is then restored to a BHWC permutation, and GELU activation, Dropout with a dropout rate of 0.1, and upscaling projection are performed sequentially to obtain the adaptive feature offset x. up Finally, xup The original input x of MonaAdapter is added element by element, and the result is fed into the frozen HieraTransformer block to obtain the output of this layer.
[0053] Where x represents the feature tensor of the input MonaAdapter; x norm This represents the feature tensor obtained after layer normalization of the input features and weighted fusion with the original input according to learnable coefficients; s1 and s2 represent two learnable scaling coefficients; C represents the number of channels of the input features; B represents the batch size; and H and W represent the height and width of the feature map, respectively. BHWC indicates that the dimensions of the tensor are arranged in the order [B, H, W, C], i.e., [batch, height, width, channels]; BCHW indicates that the dimensions of the tensor are arranged in the order [B, C, H, W], i.e., [batch, channels, height, width]. down x represents norm The 64-channel feature tensor obtained after dimensionality reduction projection and conversion to BCHW arrangement; MonaOp represents the convolution transformation operator consisting of three 3×3 depthwise convolutions, layer-by-layer identity residual connections, and 1×1 pointwise convolutions; x conv x represents down The convolutional feature tensor obtained after MonaOp transformation; x up x represents conv The adaptation feature offset tensor is obtained after permutation restoration, GELU activation, random deactivation, and up-dimensional projection.
[0054] Layer Normalization (LayerNorm) is used to normalize the feature dimensions of a single sample to stabilize the feature distribution; Depthwise Convolution performs convolution on each channel separately to extract spatial features with a low parameter count; Pointwise Convolution is a 1×1 convolution used to fuse information from different channels.
[0055] Gaussian Error Linear Unit (GELU) is used to introduce smooth nonlinearity; Dropout randomly sets some features to zero with a preset probability during training to suppress overfitting; Residual Connection preserves the original information and improves gradient propagation by adding the input to the transformed result.
[0056] S1.4: Output four layers of features X1, X2, X3 and X4; their number of channels are 144, 288, 576 and 1152 respectively, and their spatial resolutions are H / 4×W / 4, H / 8×W / 8, H / 16×W / 16 and H / 32×W / 32 respectively.
[0057] Step S2: Using Figure 3 The four multi-scale convolutional attention enhancement modules (MSCAE) in the model perform multi-scale receptive field expansion and channel-space dual attention refinement on the four layers of features obtained in step S1, resulting in four layers of 64-channel enhanced features E1, E2, E3, and E4. Figure 6 , Figure 7 and Figure 8 As shown.
[0058] S2.1: Input the features of each layer into the multi-scale receptive field block (RFB). The RFB includes a 1×1 convolution branch and three branches that use 1×3 and 3×1 convolutions with dilated rates of 3, 5 and 7 respectively. The results of the four branches are concatenated by channel, compressed by 3×3 convolution, and added to the 1×1 residual projection before performing rectified linear unit activation (ReLU) to obtain 64-channel multi-scale features F.
[0059] S2.2: Feed F in parallel into the Channel Attention Block (CAB) and the Spatial Attention Block (SAB). The CAB performs global average pooling and global max pooling on F respectively, and obtains the channel weights Mc∈R through shared multilayer perceptron mapping, summation, and a sigmoid activation function. (B×64×1×1) SAB performs average pooling and max pooling along the channel dimension, and after concatenation, it is subjected to 7×7 convolution and Sigmoid activation to obtain spatial weights Ms∈R. (B×1×h×w) .
[0060] S2.3: Calculate E=F⊙Mc⊙Ms element-wise, so that channel weights and spatial weights jointly suppress background interference and enhance the response of the target region. The four layer outputs E1 to E4 maintain their respective spatial resolutions, and the number of channels is 64 for each layer.
[0061] Step S3: Utilize Figure 3 The semantic attention auto-encoder in the code generates internal semantic cue features G4 that do not rely on human interaction from the deepest enhanced feature E4 obtained in step S2, such as... Figure 9 As shown, G is the number of semantic tokens, and in this embodiment, G=3; each group is used to learn complementary latent semantic hints, Q is the query, K is the key, and V is the value.
[0062] S3.1: Set E4∈R (B×64×H / 32×W / 32) Flattened into N = H / 32 × W / 32 64-dimensional image tokens, and superimposed with learnable positional codes, forming a cross-attention key K and value V.
[0063] S3.2: Set up G groups of learnable semantic tokens; in this embodiment, G=3, and each group contains N 64-dimensional tokens. Expand and reshape them in batches to Q∈R. (B×GN×64) Eight attention heads are used as input for the query. Each attention head computes a softmax(QK). T / √8)V, to aggregate spatial and semantic information associated with each set of semantic tokens from image features.
[0064] Here, G represents the number of semantic token groups, which is a preset structural parameter; K represents the key matrix in cross-attention, and the two have different meanings.
[0065] S3.3: Reshape the updated token into three sets of 64-channel features and concatenate them channel by channel to obtain G4∈R (B ×192×H / 32×W / 32) G4 acts as an input decoder that automatically generates prompts within the network, eliminating the need for operators to provide click, box, or mask prompts.
[0066] Step S4: Utilize Figure 3 The three-level Sequential Grouped Multi-scale Lightweight Decoder (SGML-Decoder) progressively fuses the auto-suggestion feature G4 from step S3 with the shallow enhancement feature from step S2, resulting in three segmentation predictions of the same size as the input image. Figure 11 As shown.
[0067] S4.1: The 192-channel G4 is upsampled by 2x using bilinear interpolation and then aligned with the 64-channel E3 before being concatenated by channel to form a 256-channel feature. This is then processed by the first-level Grouped Spatial Multi-scale Fusion (GSMF) module to obtain the 64-channel D1, and finally, the first-side output P is obtained through 1×1 convolution and 16x upsampling. side1 .
[0068] The GSMF module uses multiple parallel grouped convolutional branches to extract features at different scales, and then merges the features extracted by each branch into the main path in a preset order to obtain fused multi-scale features.
[0069] S4.2: Upsample D1 by 2x and concatenate it with the 64-channel E2 to obtain a 128-channel feature. This feature is then processed by the second-level GSMF module to obtain the 64-channel D2. Finally, the side output P is obtained through 1×1 convolution and 8x upsampling. side2 .
[0070] S4.3: Upsample D2 by 2x and concatenate it with the 64-channel E1 to obtain a 128-channel feature. This feature is then processed by the third-level GSMF module to obtain the 64-channel D3. Finally, the main output P is obtained through a 1×1 convolution and 4x upsampling. head .
[0071] S4.4: Each GSMF module has four parallel leaf branches and one main path. Each path uses 3×3 grouped convolution, batch normalization, and ReLU activation, followed by channel shuffle. Grouped convolution divides the input channels into several groups and performs independent convolution within each group to reduce the number of parameters; channel shuffle rearranges the channels in each group to facilitate cross-group information exchange. The 3×3 grouped convolution and its subsequent batch normalization, ReLU activation, and channel shuffle processes are as follows: Figure 10 As shown, the four leaf branches are concatenated with the main trunk features in a preset order and then grouped and convolved again, so that the information of each branch accumulates step by step in the main trunk path. In this embodiment, the number of groups g=8 and the number of leaf branches is 4, which are different parameters.
[0072] Step S5: Perform result fusion and judgment on the three-way segmentation prediction, and output the final segmentation mask of the target region in the medical image.
[0073] S5.1: According to the current embodiment, P head P side1 and P side2 The elements are added together to form the fused unnormalized predicted values (logits) Z; Sigmoid activation is applied to Z to obtain the foreground probability map, and then min-max normalization is performed based on the minimum and maximum values of the individual images.
[0074] S5.2: Compare the normalized probability map with the preset threshold τ; in this embodiment, τ=0.5, the positions greater than τ are marked as target regions, and the remaining positions are marked as background, thus obtaining the binary segmentation mask corresponding to the input medical image, thereby completing the automatic segmentation of medical images without manual prompting.
[0075] like Figure 12As shown, this embodiment also provides a training method based on Lightweight Self-Prompting SAM.
[0076] The training process incorporates medical image segmentation applications, using RGB medical images and their ground truth segmentation annotations to perform end-to-end optimization of the network. The frozen Hiera-L original parameters are not updated, and new modules such as MonaAdapter, MSCAE, SemanticAttention, and SGML-Decoder are added to the training.
[0077] Step T1: Obtain training sample pairs, including RGB medical images and the real binary segmentation labels corresponding to their pixel positions; perform random rotation, horizontal flipping and vertical flipping on the images and labels using the same random seed, then uniformly scale them to 352×352 pixels, and normalize the images.
[0078] Step T2: Input the preprocessed image into the network described in steps S1 to S4 to obtain the main output P. head First side output P side1 Second-side output P side2 The ground truth annotations are used only to calculate the training loss and are not used as input to the auto-completion encoder.
[0079] Step T3: Based on the actual segmentation annotations Y Generate boundary augmentation weight map This allows the boundary neighborhood to receive higher training weights than the flat region; the composite structural loss, consisting of weighted binary cross-entropy and weighted cross-union ratio loss, is calculated for each of the three logits.
[0080] Let the output branch r∈{head, side1, side2}, P r This represents the unnormalized predicted value (logits) output by this branch. For the ... b Pixel position of each sample ,make Where B represents the batch size. This is a true label.
[0081] In the formula, r is the output branch identifier, head, side1, and side2 represent the main output branch, the first side output branch, and the second side output branch, respectively; b is the sample number in the batch, ranging from 1 to B; i and j are the position indices of the pixel in the height and width directions, respectively; the superscript (r) and subscripts b, i, and j of p represent the foreground prediction probability given by the r-th output branch for the pixel position (i, j) in the b-th sample; the subscripts b, i, and j of w represent the boundary enhancement weights of the corresponding pixels; sigmoid represents the activation function that maps the unnormalized prediction value to the interval between 0 and 1; the subscript of AvgPool is 31×3. 1 represents a two-dimensional average pooling operation with a kernel size of 31×31, a stride of 1, and padding of 15; the subscripts i and j of the summation symbol Σ represent summation over all pixel positions in the image; ln represents the natural logarithm; the superscript (r) and subscript b of I represent the weighted intersection of the corresponding output branch and the sample, and the superscript (r) and subscript b of U minus the superscript (r) and subscript b of I represent the weighted union; LwBCE, LwIoU, and Lstruct represent the weighted binary cross-entropy loss, the weighted cross-union ratio loss, and the composite structure loss, respectively; α, β, and γ are the weight coefficients of the losses corresponding to the main output branch, the first side output branch, and the second side output branch, respectively.
[0082] The weighted binary cross-entropy loss is expressed as: The training process uses numerically stable equivalent forms for computation.
[0083] make , The weighted crossover ratio loss is expressed as: In the formula, the constant 1 is the smoothing term.
[0084] The composite structure loss of a single output branch is .therefore, .
[0085] Step T4: Add the losses of the three composite structures with equal weights to obtain... ;right L total Backpropagation is performed, updating all trainable parameters using the AdamW optimizer, while the frozen Hiera-L original parameters are not updated. In one embodiment, the initial learning rate is 1×10⁻⁶. -4 The weight decay coefficient is 1×10 -4 The batch size is 16.
[0086] The general expression for the total loss of three-way depth monitoring is as follows: In this embodiment, α=β=γ=1, therefore .
[0087] Step T5: Determine whether the preset number of training rounds or convergence conditions have been met; if not, read the next batch of training samples and return to step T1 to continue training; if the conditions are met, save the model parameters. In this embodiment, the number of training rounds is 100. After training is complete, the deployment phase only inputs the RGB medical image to be segmented, and outputs the segmentation mask according to steps S1 to S5.
[0088] (I) Detailed Explanation of the First Stage MonaAdapter parameters, efficient adapters, and their embedding methods: To address the core flaw of "large parameters leading to high cost of full fine-tuning and easy overfitting", this embodiment adopts a technical approach of freezing all parameters of the SAM2 encoder and training only the lightweight adapter.
[0089] The image encoder in this embodiment is built upon the Hiera-L hierarchical visual Transformer backbone network used in the SAM2 model. This backbone network has been pre-trained on massive amounts of natural image data, possessing approximately 214 million parameters and exhibiting powerful general visual feature extraction capabilities. However, directly applying this pre-trained natural image model to medical image segmentation tasks results in performance degradation due to domain differences; furthermore, fully fine-tuning all 214 million parameters requires enormous computational resources (GPU memory) and a large amount of labeled medical data, making overfitting a likely problem.
[0090] Therefore, this embodiment adopts the following technical solution to modify the encoder: Step K1: Freeze the backbone network parameters. Set all the original parameters of the Hiera-L backbone network to an untrainable state (i.e., gradients are not backpropagated to these parameters). This step preserves the general visual prior knowledge learned by SAM2 on massive amounts of data.
[0091] Step K2 involves embedding a MonaAdapter around each Transformer block. The Hiera-L backbone network contains multiple serially connected standard Transformer blocks. In this embodiment, each standard Transformer block is wrapped with a MonaAdapter module. Specifically, the original Transformer block is stored as an internal submodule of the MonaAdapter, and the MonaAdapter completely replaces the original Transformer block's position. After the replacement, when data flows through this location, it no longer directly enters the original Transformer block, but first enters the MonaAdapter for processing. After processing, the MonaAdapter internally calls the original Transformer block.
[0092] Step K3, the internal forward computation process of the MonaAdapter. The complete data processing flow of the MonaAdapter is executed sequentially through the following five sub-steps: Sub-step K3.1, Normalization and Learnable Scaling. Receive the input feature vector x (dimension dim, i.e., the feature dimension of the Transformer) from the previous layer. First, perform LayerNorm normalization on it; then, use two learnable scalar scaling factors s1 and s2 for a weighted combination. s1 is initialized to a minimum value (1×10⁻⁶). -6 ), s2 is initialized to 1.0. The calculation formula is: x norm =LayerNorm(x)×s1+x×s2. This design allows the adapter to approach an identity mapping in the early stages of training (i.e., it hardly changes the input), and gradually learns meaningful adaptive transformations as training progresses, avoiding excessive perturbation to the original features of SAM2 at the beginning of training.
[0093] Sub-step K3.2, dimensionality reduction projection. The scaled feature x is then projected... norm The feature x is obtained by projecting from a high-dimensional space (dim-dimensional) to a low-dimensional intermediate space (64-dimensional in this embodiment) through a fully connected linear layer. down All subsequent calculations are performed in a low-dimensional 64-dimensional space, which significantly reduces the amount of computation and parameters.
[0094] Sub-step K3.3, multi-scale depthwise separable convolution processing (MonaOp module). x down The data is fed into the MonaOp convolution module for processing. Internally, the MonaOp module performs three consecutive 3×3 depthwise separable convolutions (64 input channels). Specifically, the output of the first 3×3 depthwise convolution is compared with x... down After summing the residuals, the result is fed into a second 3×3 depthwise convolution; the output of the second layer is also the same as x. down After summing the residuals, the result is fed into a third 3×3 depthwise convolution layer; the output of the third layer is then integrated across channels using a 1×1 pointwise convolution; the final result is then compared with x again. down The residuals are summed and then output. These three sequential depthwise convolutions are equivalent to multi-level sampling of the local texture and structural features of medical images under different effective receptive fields (equivalent receptive fields are approximately 3×3, 5×5, and 7×7 respectively). They can simultaneously capture fine-grained edge information and slightly larger texture patterns. Due to the use of depthwise separable convolutions, the number of parameters and computational cost are extremely low.
[0095] Sub-step K3.4, Nonlinear Activation and Regularization. The output of the MonaOp module is sequentially applied with the GELU nonlinear activation function and Dropout (dropout rate 0.1) random deactivation operation to introduce nonlinear expressiveness and prevent overfitting.
[0096] Sub-step K3.5, dimensionality upscaling and residual backinjection. A fully connected linear layer is used to upscale the 64-dimensional low-dimensional space back to the original high-dimensional space (dim-dimensional), yielding the adaptive feature offset x generated by the adapter. up Then x up The original input x of MonaAdapter is added element-wise (residual connection) to obtain features that are injected with adaptive information from the medical field. These features are then fed into the original standard Transformer block saved in step 2 for further processing.
[0097] Through the above design, the trainable parameters of the entire model are limited to a small number of parameters within all MonaAdapters (including scaling factors s1 / s2, two projected fully connected layers, and MonaOp convolutional layer parameters), accounting for less than 5% of the total model parameters. This enables this embodiment to complete training on GPU devices with sufficient video memory, while simultaneously achieving efficient transfer adaptation of the encoder to the medical imaging domain.
[0098] (II) Detailed Explanation of the Second Stage The second phase involves a multi-scale convolutional attention enhancement module (MSCAE).
[0099] To address the deficiency of "insufficient encoder feature enhancement"—the original features output by the SAM2 encoder lack multi-scale enhancement and semantic calibration for medical images—this embodiment cascades the MSCAE module after each layer of the encoder output to perform receptive field expansion and dual attention refinement on the features.
[0100] The four feature maps (x1, x2, x3, x4) output by the encoder are each independently fed into an MSCAE module for processing. Each MSCAE module has the same structure, but differs in the number of input channels (144, 288, 576, and 1152 respectively), while the number of output channels is uniformly 64. Each MSCAE module internally performs the following two stages of processing sequentially: Phase 1: This phase involves the RFB multi-scale receptive field parallel expansion branch.
[0101] The MSCAE module internally constructs four parallel convolutional branches, each performing convolution operations on the input feature map with different receptive field ranges: Branch 0 (point-level branch): Uses only a 1×1 convolutional layer (with batch normalization and ReLU activation) to preserve point-level discriminative information in the input features without changing the spatial resolution.
[0102] Branch 1 (Small Receptive Field Branch): The process proceeds sequentially through 1×1 convolution → asymmetric convolution pairs (first 1×3 convolution, then 3×1 convolution, each including batch normalization and ReLU activation) → 3×3 dilated convolution (dilation = 3, including batch normalization and ReLU activation). The asymmetric convolution pair decomposition increases the effective coverage of the convolution kernel without increasing the number of parameters; the dilated convolution with a dilation rate of 3 expands the equivalent receptive field of this branch to approximately region 7.
[0103] Branch 2 (Medium receptive field branch): sequentially goes through 1×1 convolution → asymmetric convolution pairs (first 1×5 convolution then 5×1 convolution) → 3×3 dilated convolution (dilation = 5). The equivalent receptive field of this branch expands to a region of approximately 15.
[0104] Branch 3 (large receptive field branch): sequentially goes through 1×1 convolution → asymmetric convolution pair (first 1×7 convolution then 7×1 convolution) → 3×3 dilated convolution (dilation = 7). The equivalent receptive field of this branch expands to a region of approximately 23.
[0105] The output features of the four branches mentioned above are concatenated along the channel dimension, resulting in 4 × 64 = 256 channels. A 3 × 3 convolutional layer (including batch normalization and ReLU activation) then compresses these 256 channels back to 64 channels, achieving the aggregation and integration of multi-scale features. Simultaneously, the original input feature map is also processed by a 1 × 1 convolution (including batch normalization and ReLU activation) to generate a residual path (also with 64 channels). The aggregated multi-scale features are then element-wise added to this residual path, and finally processed by the ReLU activation function to obtain the output features of stage one.
[0106] Phase Two: This phase involves refining the dual attention of the channel and space.
[0107] The 64-channel feature map output from Stage 1 is fed into the channel-spatial dual attention module for further refinement. The channel-spatial dual attention module contains one channel attention branch (CAB) and one spatial attention branch (SAB). Both branches take the same feature map output from Stage 1 as input and compute the channel weights and spatial weights in parallel. The operation of the Channel Attention Branch (CAB) is as follows: Global average pooling (averaging the entire spatial dimension into a single value, outputting a batch × channel × 1 × 1 shape) and global max pooling (taking the maximum value of the spatial dimension, also outputting a batch × channel × 1 × 1 shape) are simultaneously performed on the input feature map, resulting in two pooling results. Both paths share the same two-layer fully connected network (i.e., first a 1 × 1 convolution to reduce the number of channels to 1 / 16 of the original number, then ReLU activation, and finally another 1 × 1 convolution to restore the original number of channels). The outputs of the two paths are element-wise summed and then mapped to the 0-1 interval using the Sigmoid activation function, resulting in a channel attention weight map (with a batch × channel × 1 × 1 shape). Channels with higher values in this weight map indicate that the channel is more discriminative for the current segmentation task. This channel weight, together with the spatial weights generated by the spatial attention branch, acts on the stage-one output features, selectively enhancing or suppressing the channel dimension—enhancing feature channels related to lesions and suppressing the responses of irrelevant background channels.
[0108] The Spatial Attention Branch (SAB) operation process is as follows: For the same feature map output from Stage 1, the average and maximum values are calculated along the channel dimension, each yielding a two-dimensional planar image (both with a shape of batch × 1 × height × width). These two planar images are then concatenated along the channel dimension to form a dual-channel feature map (with a shape of batch × 2 × height × width). A 7×7 convolutional layer is used to model the spatial neighborhood of this dual-channel image, which is then mapped to the 0-1 interval using a Sigmoid activation function, resulting in a spatial attention weight map (with a shape of batch × 1 × height × width). Higher spatial values in this weight map indicate that the location is more likely to belong to the target region to be segmented. This spatial weight, together with the channel weights generated by the channel attention branch, acts on the Stage 1 output features to achieve selective focusing in the spatial dimension—highlighting the spatial response of key lesion regions and suppressing interference from background regions.
[0109] After parallel calculation and joint calibration of the channel weights and spatial weights, the final output feature of the MSCAE module for this layer (64 channels) is obtained. The features of the four encoder layers are processed by their respective MSCAE modules to obtain the enhanced features f1, f2, f3, and f4 (all 64 channels).
[0110] (III) Detailed Explanation of the Third Stage The third stage involves a semantically enhanced auto-suggestion encoder based on cross-attention.
[0111] To address the core flaw of "cue-driven" SAM2, which requires manual interactive cues to perform segmentation, this embodiment designs a SemanticAttention auto-cue encoder. Through cross-attention calculation of learnable semantic tokens and image features, it automatically generates internal cue signals, completely replacing the original SAM cue encoder.
[0112] The original SAM model employs a "cue-driven" segmentation paradigm, requiring users to manually provide cues such as points, boxes, or masks during inference to guide segmentation. This interactive mode is cumbersome in high-throughput clinical scenarios, severely hindering automated deployment. To completely eliminate reliance on manual cues, this embodiment designs a semantically enhanced auto-cue encoder (SemanticAttention) based on cross-attention, enabling the model to autonomously extract task-related semantic and spatial information from the MSCA-enhanced image features and automatically generate internal cue signals.
[0113] The processing flow of the SemanticAttention module is as follows: Step P1: Initialize learnable semantic tokens. A preset set of G groups of learnable semantic tokens is used, each group containing N tokens, where N is the total number of spatial locations in the feature map H×W, and each token has a dimension of C. In this embodiment, C=64 and G=3. All tokens are organized as a three-dimensional learnable parameter tensor of shape [G,N,C]. G represents the number of token groups used to form internal cue features, not the final number of segmentation categories; each group of tokens learns different cue feature patterns during end-to-end training and serves as the query for the cross-attention mechanism.
[0114] In this embodiment, G is preset to 3. G is a structural parameter that can be adjusted according to task requirements and does not represent the number of categories of the target to be segmented. During the end-to-end training process, the three sets of semantic tokens aggregate complementary latent semantic information, which may involve features such as target boundaries, local textures, internal regions, and morphological structures. Since independent semantic supervision is not applied to each set, each set is not pre-defined to correspond one-to-one with a specific feature type.
[0115] Step P2, positional embedding injection. Learnable positional embeddings are applied to the MSCAE-enhanced image features. The image features are flattened and transposed from [B,C,H,W] to [B,N,C], where N=H×W; the shape of the learnable positional embedding parameters is [1,N,C], expanded along the batch dimension to [B,N,C], and then added element-wise to the image features to preserve information about each spatial location.
[0116] Step P3, Cross-Attention Calculation. Multi-head cross-attention is performed using semantic tokens as queries and the injected position-encoded image features as keys and values. First, the semantic tokens [G, N, C] are expanded along the batch dimension and reshaped into Q ∈ R. (B×GN×C) Using image feature sequences as Then, split the data into eight attention points and project them linearly to calculate... ,in Finally, the attention points are concatenated and passed through a fully connected layer to obtain the update token [B, G×N, C].
[0117] This cross-attention mechanism enables each group of learnable semantic tokens to aggregate different cue feature patterns and their spatial location information from image features, generating internal cue signals that do not require manual clicks, boxes, or mask input.
[0118] Step P4, Output Reconstruction. The cross-attention output is restored from [B,G×N,C] to [B,G,H×W,C], and then transposed and reshaped sequentially to [B,C×G,H,W]. In this embodiment, C=64 and G=3, therefore the number of channels for the output auto-completion feature G4 is 192.
[0119] The introduction of this auto-completion encoder enables this embodiment to complete segmentation without any form of manual prompting input during inference, achieving a paradigm shift from "prompt-driven" to "auto-completion." Semantic tokens are optimized end-to-end during training, requiring no additional annotation, and automatically learn how to extract effective segmentation prompts from image features.
[0120] (iv) Detailed explanation of the fourth stage The fourth phase involves the Sequential Grouping Multiscale Lightweight Decoder (SGML-Decoder) and its GSMF module.
[0121] To address technical problem 4, "deep multi-scale fusion of decoders"—existing fully automatic SAM methods have simple decoder fusion strategies, making it difficult to simultaneously recover fine boundaries and maintain semantic consistency under lightweight constraints—this embodiment designs an SGML-Decoder composed of multiple GSMF modules to achieve progressive deep interactive fusion of multi-scale features.
[0122] The decoder is responsible for progressively restoring the low-resolution, high-semantic abstract features generated by the encoder into dense segmentation predictions with the same resolution as the original input. The decoder designed in this embodiment adopts a three-level upsampling architecture, with each level consisting of an Up_GSMF module. The following details the process in order: Step R1, First-level upsampling fusion (up1). The auto-suggestion feature G4 (192 channels, spatial resolution H / 32×W / 32) output by SemanticAttention is upsampled by 2x bilinear interpolation and then aligned with the third-layer enhancement feature E3 (64 channels, spatial resolution H / 16×W / 16) and concatenated by channel to form a 256-channel merged feature. This is then fed into the first GSMF module, which outputs the 64-channel first-level decoding feature D1. D1 is mapped to the category channels by a 1×1 convolution and then subjected to 16x bilinear interpolation to obtain the first-side output side1.
[0123] Step R2, second-level upsampling fusion (up2). The first-level decoding feature d1 (64 channels) is used as the current decoder feature and upsampled by 2x bilinear interpolation; simultaneously, the second-level enhancement feature f2 (64 channels) is obtained as the skip connection feature; the two are concatenated to 128 channels and fed into the second GSMF module, outputting the second-level decoding feature d2 with 64 channels. A second auxiliary output branch is derived from d2: after 1×1 convolution, it is upsampled by 8x bilinear interpolation to obtain the second auxiliary supervised segmentation prediction side2.
[0124] Step R3, third-level upsampling fusion (up3). The second-level decoding feature d2 (64 channels) is used as the current decoder feature and upsampled by 2x bilinear interpolation; simultaneously, the first-level enhancement feature f1 (64 channels) is obtained as the skip connection feature; the two are concatenated to 128 channels and fed into the third GSMF module, outputting 64 channels of the third-level decoding feature d3. After d3 is convolved by 1×1, it is upsampled by 4x bilinear interpolation to obtain the final segmentation prediction output head.
[0125] Detailed internal structure of the Grouped Spatial Multi-Scale Fusion Block (GSMF module): The GSMF module is the core innovative unit of the decoder in this embodiment. Its function is to achieve sequential fusion of multi-scale features while maintaining a low number of parameters. This embodiment sets up 4 leaf branches, with 64 output channels and 8 groups for grouped convolution; the number of leaf branches and the number of convolution groups are two different parameters. The first-stage GSMF module receives 256 channels of input, while the second and third-stage GSMF modules receive 128 channels of input.
[0126] Branch A is a leaf branch (with a total of 4 independent parallel branches), specifically involving: Leaf branch 1: Perform 3×3 grouped convolution (groups=g (8 in this example) on the input x) → batch normalization → ReLU activation, output leaf x1 (64 channels); Leaf branch 2: Performs the same operation as above independently, outputting leaf. x2(64 channels); Leaf branch 3: Executes independently as above, outputting leaf. x3 (64 channels); Leaf branch 4: Performs the same operation as above independently, outputting leaf. x4 (64 channels).
[0127] Each leaf branch is followed by a channel shuffle. Due to different initialization parameters, each leaf branch gradually learns to extract features of different spatial frequencies during training.
[0128] Branch B is the main path, specifically involving: Initial convolution of the backbone: Perform 3×3 grouped convolution (groups=g (8 in this example) on the input x) → batch normalization → ReLU activation, outputting the main branch. x0 (64 channels); Perform channel rearrangement.
[0129] First convolution of the main branch: Perform 3×3 grouped convolution (groups=g (8 in this example) on main_x0) → batch normalization → ReLU activation, outputting main x1 (64 channels); Perform channel rearrangement.
[0130] Branch C: Sequence fusion process (core innovative step).
[0131] First fusion: leaf x1 With main x1 The concatenation (128 channels) is fed into a 3×3 grouped convolution → batch normalization → ReLU activation followed by compression back to 64 channels, outputting the main function. x2 ; Perform channel rearrangement.
[0132] Second fusion: leaf x2 With main x2 The concatenation (128 channels) is fed into a 3×3 grouped convolution → batch normalization → ReLU activation followed by compression back to 64 channels, outputting the main function. x3 ; Perform channel rearrangement.
[0133] Third fusion: leaf x3 With main x3 The concatenation (128 channels) is fed into a 3×3 grouped convolution → batch normalization → ReLU activation followed by compression back to 64 channels, outputting the main function. x4 ; Perform channel rearrangement.
[0134] Fourth fusion: leaf x4 With main x4The concatenation (128 channels) is fed into a 3×3 grouped convolution → batch normalization → ReLU activation and then compressed back to 64 channels, which is the final output OUT; channel rearrangement is then performed.
[0135] Detailed explanation of the channel shuffle operation: This operation is performed after each group convolution. Assume the input feature map shape is [batch, number of channels C, height H, width W], and the number of groups is g. The operation process is as follows: First, the channel dimension is expanded into g groups, reshaping the shape to [batch, g, C / g, H, W]. Then, the first dimension (group dimension) and the second dimension (channel dimension within each group) are transposed and interchanged, becoming [batch, C / g, g, H, W]. Finally, the last three dimensions are flattened, restoring the shape to [batch, C, H, W]. The effect of this operation is to redistribute the feature information that was originally isolated in different groups, allowing subsequent group convolutions to access feature information from other groups, thus avoiding the information silo problem caused by group convolutions. This is one of the key technologies in this embodiment for maintaining a large effective receptive field under extremely low parameter conditions.
[0136] The essential difference between the above-mentioned sequence fusion design concept and the traditional parallel fusion scheme is that the traditional scheme usually simply stacks features of multiple scales in parallel and then fuses them at once (such as directly splicing them and then adding a convolutional layer). This approach ignores the hierarchical interaction between features of different scales. In contrast, the GSMF module in this embodiment adopts a method of gradual interaction between the main path and multiple leaf branches, so that multi-scale information is gradually integrated into the main path in the order of "shallow details → mid-level structure → deep semantics". This realizes a bottom-up semantic evolution process from local details to global semantics, and continuously deepens the high-level semantic understanding while restoring fine boundaries.
[0137] (V) Loss Function Design and Training Strategy This embodiment uses a composite structure loss function in conjunction with a deep supervision strategy for model training to address two common challenges in medical image segmentation tasks: (1) class imbalance between foreground and background - the area of the lesion region is usually much smaller than the background region; (2) ambiguity and uncertainty of lesion boundaries - the edges of lesions often lack clear intensity transitions.
[0138] Step E1: Spatial Weight Map Generation. A spatial weight map w with the same resolution as the original image is generated based on the ground truth mask. The generation method is as follows: the foreground mask of the ground truth mask is smoothed using 31×31 average pooling, and the absolute difference between the smoothed result and the original mask is taken. The difference is larger at lesion boundaries (up to 1.0) and approaches 0 at non-boundary areas. Based on this, a weight map w = 1 + 5 × |AvgPool(mask) - mask| is generated, with a maximum weight of approximately 6.0 for boundary regions and a weight of 1.0 for flat non-boundary regions. The purpose of this weight map is to artificially increase the importance of boundary pixels during the loss calculation process, prompting the model to pay more attention to boundary regions that are difficult to segment accurately.
[0139] Step E2: Calculation of the weighted binary cross-entropy loss term. Let z be the original output of the model (logits, without Sigmoid activation), y be the true segmentation label (0 for background, 1 for foreground), and w be the spatial weight map. The weighted binary cross-entropy loss is calculated as follows: First, apply the Sigmoid function to z to map it to the probability value p = Sigmoid(z) in the interval (0,1); then calculate the binary cross-entropy value at each pixel position and multiply the corresponding weight w into the loss value of that pixel; finally, take the average of the weighted losses for all pixels.
[0140] Specifically, it can be expressed as follows: , where p = Sigmoid(z).
[0141] Step E3: Calculation of the weighted intersection-union (IoU) loss term. Using the probability value p, the true label y, and the weighted graph w, the weighted IoU loss is calculated. Specifically, the sum of the element-wise products of p and y (i.e., the weighted true positive portion), the sum of the element-wise products of p and (1-y) (i.e., the weighted false positive portion), and the sum of the element-wise products of (1-p) and y (i.e., the weighted false negative portion) is the weighted union. The weighted IoU loss is defined as 1 minus the ratio of the weighted intersection to the weighted union. This loss term directly optimizes the segmentation overlap rate index and provides a good gradient signal for small lesions.
[0142] Specifically, it can be expressed as follows: , .in, That is, the weighted union, with the constant 1 being the smoothing term.
[0143] Step E4, structural loss at a single location. The two loss terms from steps E2 and E3 are added together to obtain the composite structural loss applied to a single output. .
[0144] The specific expression of composite structure loss is as follows The three corresponding outputs are: .
[0145] Step E5, the total loss of deep supervision. In this embodiment, the aforementioned composite structural loss is applied to the three outputs (side1, side2, and head) of the decoder respectively. Three sub-losses were obtained. Total loss The weighted sum of the three: In this embodiment, the weight coefficients are set to λ1=1.0, λ2=1.0, and λ3=1.0, meaning the three output branches adopt an equal-weight design. The final output receives the same optimization strength as the intermediate auxiliary output, simplifying hyperparameter tuning while ensuring the effective transmission of deep supervision signals. This deep supervision design guides the intermediate features of each level of the decoder towards the correct segmentation semantic direction, effectively improving the gradient propagation quality of deep networks, accelerating convergence, and enhancing final accuracy.
[0146] The following are the implementation parameters during training: the optimizer used is AdamW; the initial learning rate is 1×10⁻⁶. -4 The weight decay coefficient is 1×10. -4 The training batch size was 16; the input size was 352×352 pixels; and the number of training epochs was 100. During training, the original parameters of the Hiera-L backbone network were frozen, and only the parameters of newly added modules such as MonaAdapter, MSCAE, SemanticAttention, and SGML-Decoder were updated.
[0147] This embodiment has the following advantages: 1. Freeze the backbone and adapt it lightly with MonaAdapter. Freeze the original parameters of the SAM2 Hiera-L encoder and wrap each standard Transformer block with a trainable MonaAdapter; the MonaAdapter sequentially adopts near identity double scaling combination, 64-dimensional bottleneck projection, MonaOp multi-scale transformation with three layers of cascaded 3×3 depth convolution, layer-by-layer residual connection and dimension-upgrading residual backinjection.
[0148] Advantages: While retaining the pre-trained backbone visual priors, only the parameters of the adapter and other newly added modules are updated, reducing the number of trainable parameters and computational resources required for medical image domain transfer; near-identical initialization helps reduce the perturbation of pre-trained features in the early stage of training; the 64-dimensional bottleneck and MonaOp multi-scale structure take into account both lightweight computation and local multi-scale information extraction.
[0149] 2. Four-layer multi-scale convolution and channel-spatial joint attention enhancement. MSCAE modules are set up for the four layers of features output by the encoder. Each MSCAE first uses the RFB four-branch structure to expand the receptive field at different scales, then uses CAB and SAB to generate channel weights and spatial weights, and multiplies them element-wise with the same feature to form four layers of 64-channel enhanced features.
[0150] Advantages: It enables each layer of features to simultaneously include local edges, regional structures, and deep semantic information, and suppresses background interference from both channel and spatial dimensions, which is beneficial to improving the network's ability to represent medical targets of different sizes, with blurred boundaries and irregular shapes.
[0151] 3. Semantic Attention Auto-Cue Encoding. G sets of learnable semantic tokens are set; in this embodiment, G=3, where G represents the number of token sets used to form internal prompt features, not the final number of segmentation categories. These semantic tokens are used as queries, and the deepest enhanced image features injected with learnable positional encoding are used as keys and values. Multi-head cross-attention is then used to generate C×G channels of internal auto-cue features.
[0152] Advantages: It can generate internal prompts with semantic and spatial location information from image features without requiring operators to input additional clicks, boxes, or mask prompts during the inference stage, reducing manual interaction and improving the automation level of batch medical image segmentation processes.
[0153] 4. SGML-Decoder: A lightweight, sequentially grouped multi-scale decoder. The auto-completion features and the shallow enhancement features output by MSCAE are progressively upsampled, aligned, and concatenated, and then fused at each level using a GSMF module. The GSMF module accumulates branch information progressively along the main path through sequential fusion of multiple leaf branches and the main path, 3×3 grouped convolution, and channel rearrangement after convolution.
[0154] Advantages: It achieves the step-by-step fusion of cross-layer detailed information and deep semantic information with lower parameters and computational overhead; channel rearrangement promotes information exchange between different convolutional groups, which is beneficial for restoring target boundaries and improving the expressive power of decoded features.
[0155] 5. Boundary-weighted composite structure loss and depth supervision. A boundary-enhancing weight map is generated based on the average pooling difference of the real segmentation annotations. The sum of the weighted binary cross-entropy loss and the weighted intersection-union ratio loss is calculated for the three outputs head, side1, and side2 respectively. The three composite structure losses are then weighted and summed to perform backpropagation. In this embodiment, the three output branches are set with equal weights.
[0156] Advantages: It increases the contribution of boundary neighborhood pixels in training and improves gradient propagation at each level of the decoder through joint supervision of the main output and intermediate side outputs, which is beneficial for taking into account pixel classification, region overlap and boundary localization.
[0157] Overall, the above technical solutions form a complete data processing chain around efficient parameter adaptation, multi-scale feature enhancement, automatic prompt generation, and lightweight decoding. Furthermore, boundary-aware deep supervised training further constrains the outputs at each level, thereby achieving automatic segmentation for medical images.
[0158] This application also provides a medical image segmentation apparatus, including one or more functional units or modules, for performing the method described in any of the above embodiments.
[0159] This application also provides an electronic device, including: a processor, and a memory coupled to the processor, the memory being used to store a computer program; the processor being used to execute the computer program stored in the memory, so that the electronic device performs the method as described in any of the above embodiments.
[0160] Electronic devices can be computing devices such as desktop computers, laptops, handheld computers, and cloud servers. These electronic devices may include, but are not limited to, processors and memory.
[0161] The processor can be a Central Processing Unit (CPU), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc. A general-purpose processor can be a microprocessor or any conventional processor. The processor is the control center of the electronic device, connecting various parts of the device via various interfaces and lines.
[0162] The memory can be used to store the computer program, and the processor implements various functions of the electronic device by running or executing the computer program stored in the memory and calling the data stored in the memory.
[0163] The memory may primarily include a program storage area and a data storage area. The program storage area may store the operating system, applications required for at least one function, etc.; the data storage area may store data created based on the use of the mobile phone, etc. In addition, the memory may include high-speed random access memory, and may also include non-volatile memory, such as hard disk, memory, plug-in hard disk, smart media card (SMC), secure digital (SD) card, flash card, at least one disk storage device, flash memory device, or other volatile solid-state storage device.
[0164] This application also provides a storage medium, which is a computer-readable storage medium. The computer program is stored in the computer-readable storage medium, and when executed by a processor, the computer program can implement the steps of the various method embodiments described above. The computer program includes computer program code, which can be in the form of source code, object code, executable file, or some intermediate form. The computer-readable medium can include: any entity or device capable of carrying the computer program code, a recording medium, a USB flash drive, a portable hard drive, a magnetic disk, an optical disk, a computer memory, a read-only memory (ROM), a random access memory (RAM), an electrical carrier signal, a telecommunication signal, and a software distribution medium, etc.
[0165] This application also provides a computer program product, including: a computer program or instructions that, when the computer program or instructions are run on a computer, cause the computer to perform any of the above possible implementation methods.
[0166] The above description is the preferred embodiment of this application. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of this application, and these improvements and modifications are also considered to be within the scope of protection of this application.
Claims
1. A lightweight automatic prompt arbitrary segmentation method for medical images, characterized by, include: Obtain the medical image to be segmented; The medical image to be segmented is input into a trained medical image segmentation model to obtain the segmentation result; The medical image segmentation model includes: An image encoder is used to extract N layers of features from medical images using a Hiera-L backbone network based on several cascaded arbitrary segmentation models SAM2, resulting in an N-layer feature map. A multi-scale feature refinement network is used to independently perform multi-scale receptive field expansion and channel-space dual attention calibration refinement processing on the feature maps of the corresponding layers output by the image encoder, to obtain N layers of enhanced image features. A semantic attention auto-cue encoder is used to automatically generate internal cue signals through cross-attention computation between learnable semantic tokens and the enhanced image features of the Nth layer; The decoder is used to perform layer-by-layer decoding of the enhanced image features of the N-1 layers under the guidance of the internal prompting signal, so as to obtain the N-1 layer decoded features; The fusion module is used to fuse the decoding features of layer N-1 to obtain fused features; A prediction head is used to make predictions based on the fused features to obtain a segmentation mask for the predicted target region.
2. The method of claim 1, wherein, The Hiera-L backbone network includes several cascaded standard Transformer blocks. Each standard Transformer block has an externally embedded parameter-efficient fine-tuning adapter module, MonaAdapter, to control the trainable parameters of the image encoder to be less than 5% of all parameters. During training, the parameters of the standard Transformer blocks are frozen.
3. The method of claim 2, wherein, The Hiera-L backbone network is specifically used to perform the following processes in sequence: normalization and learnable scaling, dimensionality reduction projection, multi-scale depth-separable convolution processing, nonlinear activation and regularization, and dimensionality increase projection and residual backinjection. Specifically, the multi-scale depth-separable convolution processing involves performing three consecutive 3×3 depth-separable convolutions to sample the local texture and structural features of the image at multiple levels under different effective receptive fields, while capturing fine-grained edge information and slightly larger-scale texture patterns.
4. The method of claim 1, wherein, The multi-scale feature refinement network includes N multi-scale convolutional attention enhancement modules (MSCAEs). Each MSCAE specifically includes a multi-scale receptive field parallel expansion branch (RFB), a channel attention branch (CAB), and a spatial attention branch (SAB). The multi-scale receptive field parallel expansion branch takes the feature map of the corresponding layer output by the image encoder as input. The channel attention branch and the spatial attention branch take the output of the multi-scale receptive field parallel expansion branch as input. The outputs of the multi-scale receptive field parallel expansion branch, the channel attention branch, and the spatial attention branch are fused to obtain the enhanced image features. The multi-scale receptive field parallel expansion branch is used to perform convolution operations with different receptive field ranges. The channel attention branch is used to selectively enhance or suppress the channel dimension. The spatial attention branch is used to selectively focus the spatial dimension.
5. The method of claim 1, wherein, The semantic attention auto-completion encoder is specifically used for: Group G can learn semantic token initialization; Apply learnable positional encoding to the enhanced image features; Using the learnable semantic token as the query and the image features after being injected with the location encoding as the key and value, multi-head cross-attention calculation is performed to enable the learnable semantic token to aggregate different prompt feature patterns and spatial location information from the image features, thereby generating the internal prompt signal.
6. The method of claim 1, wherein, The decoder is specifically used for: The internal prompt signal features are upsampled at layer N-1 to obtain layer N-1 upsampled features. The layer N-1 upsampled features are fused with the layer N-1 enhanced image features to obtain layer N-1 merged features. The layer N-1 grouped spatial multi-scale fusion module is used to process the layer N-1 merged features to obtain layer N-1 decoded features. The grouped spatial multi-scale fusion module includes a main path and several parallel leaf branches. The leaf branches are used to extract corresponding scale features using grouped convolution and fuse the extracted corresponding scale features into the main path in a preset order to obtain fused multi-scale features.
7. The method of claim 6, wherein, The grouped convolution is followed by channel rearrangement to redistribute the feature information that was originally isolated in different groups to the various groups.
8. The method of claim 1, wherein, The N-1 layer decoding features correspond to the main output and N-1 side outputs. The total loss of the medical image segmentation model includes: the main output loss term and N-1 side output loss terms. Both the main output loss term and the side output loss term include weighted binary cross-entropy loss and weighted cross-union ratio loss.
9. A medical image segmentation apparatus characterized by comprising: It includes one or more functional units or modules for performing the method of any one of claims 1-8.
