Differentiable markov mask refinement method and system for medical cross-modality image generation

By employing multi-step differentiable Markov state transitions and boundary-constrained activity boundary indicators, the problem of mask-task mismatch in medical cross-modal image generation is solved, achieving adaptive mask updating and accurate generation, thereby improving image quality and accuracy.

CN122656894BActive Publication Date: 2026-11-27JIMEI UNIV
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202611160564.0
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-08-03
Publication Date
2026-11-27
Estimated Expiration
2046-08-03

AI Technical Summary

Technical Problem

In current medical cross-modal image generation, the mismatch between manually labeled masks and spatial cues for the generation task leads to spatial drift and discrete noise in the mask regression process. Furthermore, existing regularization terms conflict with the gradient of the generation task, making it difficult to achieve effective spatial constraints.

Method used

By employing a multi-step differentiable Markov state transition and a boundary-constrained activity boundary indicator, the diagnostic-guided hard mask is transformed into a task-adaptive soft mask. Through a parameter-sharing mask refinement network and a diffusion-based medical image generation model, the mask is progressively updated to generate a task-adaptive soft mask. The mask refinement process is optimized using morphological gradients and stopping gradient signals.

Benefits of technology

It improves the adaptability of the mask to the generation task, reduces spatial drift and noise, enhances the accuracy and quality of medical cross-modal image generation, and ensures the geometric interpretability and task adaptability of the mask.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122656894B_ABST
    Figure CN122656894B_ABST
Patent Text Reader

Abstract

The application discloses a differentiable Markov mask refinement method and system for medical cross-modality image generation, and the method comprises the following steps: acquiring a source modality medical image and an initial diagnosis-oriented mask image which is spatially registered with the source modality medical image; constructing a parameter-shared mask refinement network for outputting a signed correction field, wherein a positive value indicates foreground expansion and a negative value indicates foreground contraction; taking the initial mask image as an initial state, performing multi-step differentiable Markov state transition, and updating a current soft mask image based on an active boundary indicator of the current soft mask image in each step, so that the correction field is limited in a boundary area until a task-adaptive soft mask image for medical cross-modality image synthesis is generated. The diagnosis-oriented hard mask image is converted into the task-adaptive soft mask image through the multi-step differentiable Markov state transition and the boundary-limited active boundary indicator, the adaptability of spatial cues and generation tasks is improved, and the problems of mask inconsistency with tasks and one-time regression lacking geometric constraints leading to drift and noise are solved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of image analysis and processing, and in particular to a differentiable Markov mask thinning method and system for medical cross-modal image generation. Background Technology

[0002] Medical cross-modal image generation is an important technological direction in the fields of healthcare data processing and medical image generation. It aims to use computer systems to infer and generate target modal medical image data from source modal medical image data. For example, it can generate positron emission tomography (PET) metabolic images based on morphological information from computed tomography (CT) scans, or generate enhanced T1-weighted magnetic resonance imaging (T1CE), T2-weighted magnetic resonance imaging (T2-weighted MRI), or fluid attenuation inversion recovery sequence (FLAIR) images from T1-weighted magnetic resonance imaging (T1-weighted MRI). This technology has significant application value in reducing duplicate scans, assisting in missing sequence completion, reducing patient radiation dose and examination burden, and can provide crucial data support for subsequent lesion segmentation, diagnostic assistance, treatment planning, and clinical research analysis. In recent years, diffusion models, diffusion bridge models, and U-shaped network-based generative models have demonstrated strong image synthesis capabilities in natural image translation tasks and are gradually being introduced into the field of medical imaging.

[0003] To ensure that the generative model focuses on the lesion area during image translation, existing technologies typically inject spatial prior information into the network using one of two methods: First, manually annotated lesion masks are directly concatenated with the source modality image along the channel dimension and then input into the generative network; second, the annotated mask is used as a cross-attention condition and fused with image features in the intermediate layer of the generative network. However, the manually annotated masks relied upon by these methods primarily serve diagnostic or segmentation tasks. Their boundaries usually reflect the extent of the lesion as determined by the physician based on the imaging features of that modality in the source modality image, and are not necessarily equivalent to the most informative spatial region when inferring the target modality from the source modality. Taking CT-to-PET generation as an example, the CT lesion mask depicts the morphological extent of the lesion visible in the source modality, while the CT morphological cues needed to predict metabolic activity may be located at the lesion edge, surrounding tissue, or adjacent anatomical structures, rather than the lesion area itself. Taking the generation of T1-weighted MRI to T1CE or FLAIR as an example, the tumor mask obtained by combining annotations of enhanced tumor, peritumoral edema, and necrotic core cannot separately express the differentiated task requirements related to the contrast enhancement appearance or edema signal. Therefore, directly using the diagnostic-guided hard mask as a fixed spatial cue for the generation task will lead to a structural deviation between the spatial cue and the generation task.

[0004] To address the mismatch between masks and tasks, some studies have attempted to use high-dimensional networks to directly regress the task-optimal continuous mask, hoping to replace fixed manual annotation. However, this one-off regression strategy has significant drawbacks: due to the lack of effective constraints on the mask update range, the network output mask is prone to uncontrolled spatial drift, manifesting as abnormal expansion or excessive contraction of the foreground region, and discrete noise near the mask boundary. The fundamental reason is that the mask regression process lacks a clear geometrically feasible region, and the loss gradient of the generation task may become unstable when backpropagated through deep networks to the mask regression module, causing the optimization direction to deviate from the expected direction. If the mask shape is constrained only by applying total variational regularization or boundary preservation regularization, although the smoothness of the mask can be improved to some extent, such regularization terms often conflict with the direction of the generation task gradient, making the mask visually smooth but deviating from the optimization direction that is truly beneficial for reducing the target modality generation error. Summary of the Invention

[0005] The purpose of this invention is to provide a differentiable Markov mask refinement method and system for medical cross-modal image generation. By using multi-step differentiable Markov state transitions and boundary-constrained active boundary indicators, the diagnostic-guided hard mask is transformed into a task-adaptive soft mask, which improves the adaptability between spatial cues and medical cross-modal image generation tasks. It solves the problems of inconsistency between artificial masks and the spatial cues required for generation tasks, as well as spatial drift and discrete noise caused by the lack of geometric constraints in one-time mask regression.

[0006] To address the aforementioned technical problems, a first aspect of this invention provides a differentiable Markov mask thinning method for medical cross-modal image generation, comprising the following steps:

[0007] S1: Acquire a source modal medical image and an initial diagnostic guidance mask spatially registered with the source modal medical image, wherein the initial diagnostic guidance mask is a binary or continuous value mask indicating the lesion region;

[0008] S2: Construct a parameter-sharing mask thinning network, which is a convolutional network with an encoder-decoder structure, including an input mapping convolutional block, multiple downsampling blocks, a bottleneck block, multiple upsampling blocks, and an output convolutional layer connected in sequence. The upsampling blocks are fused with the features of the corresponding downsampling blocks through skip connections. The output convolutional layer is used to output a signed correction field. Positive values ​​in the signed correction field indicate foreground expansion, and negative values ​​indicate foreground contraction.

[0009] S3: Using the initial diagnostic guidance mask as the initial state, perform multi-step differentiable Markov state transitions. Each state transition is based on the activity boundary indicator determined by the current soft mask, and the signed correction field output by the mask refinement network is restricted to the boundary region to update the current soft mask, until a task-adaptive soft mask for medical cross-modal image synthesis is generated.

[0010] Furthermore, the execution of the multi-step differentiable Markov state transition described in step S3 includes the following sub-steps:

[0011] S31: Map the initial diagnostic guidance mask to the range [0,1] as the current soft mask, and set the total number of refinement steps and the single-step update amplitude;

[0012] S32: Perform a single state transition step to update the current soft mask and obtain an intermediate soft mask;

[0013] S33: Cut the intermediate soft mask to the range [0,1] and use it as the new current soft mask;

[0014] S34: Repeat steps S32 to S33 until the total number of refinement steps is completed, and obtain the task-adaptive soft mask.

[0015] Furthermore, the single state transition step described in step S32 includes the following sub-steps:

[0016] S321: Perform grayscale dilation and grayscale erosion operations on the current soft mask to obtain the outer boundary band and the inner boundary band;

[0017] S322: Merge the outer boundary band with the inner boundary band, and obtain the active boundary indicator after normalization and thresholding.

[0018] S323: Input the current soft mask into the mask thinning network to obtain the signed correction field;

[0019] S324: Multiply the signed correction field with the active boundary indicator pixel by pixel to obtain the restricted correction field;

[0020] S325: Add the current soft mask to the constrained correction field scaled according to the single-step update amplitude pixel by pixel to obtain the intermediate soft mask.

[0021] Furthermore, the generation of the activity boundary indicator in steps S321 and S322 includes the following sub-steps:

[0022] S3211: Using a square structural element with a preset radius, perform a grayscale expansion operation on the current soft mask to obtain the expansion result;

[0023] S3212: Using the square structural element, perform a grayscale etching operation on the current soft mask to obtain the etching result;

[0024] S3221: Calculate the difference between the expansion result and the corrosion result to obtain the unsigned morphological gradient;

[0025] S3222: Normalize the unsigned morphological gradient by the sum of the current sample's maximum boundary response and a preset stability constant to obtain a normalized gradient;

[0026] S3223: Compare the normalized gradient with a preset boundary activation threshold, set the pixels with values ​​greater than the threshold to be active, and set the rest to be inactive, to obtain the active boundary indicator.

[0027] Furthermore, after step S34, the following sub-steps are also included:

[0028] Step S35: Save the intermediate soft mask obtained from each execution of step S32 to obtain the intermediate mask sequence. The intermediate mask sequence, together with the initial diagnostic guidance mask and the task adaptive soft mask, constitute the mask evolution trajectory.

[0029] Step S36: Superimpose each mask in the mask evolution trajectory onto the source modality medical image in chronological order to generate a mask evolution visualization image sequence. The mask evolution visualization image sequence is used to demonstrate the spatial cue change process from the diagnostic guidance mask to the task adaptive soft mask.

[0030] Furthermore, the setting of the total number of refinement steps and the single-step update magnitude in step S31 includes:

[0031] Set the total number of refinement steps and the initial single-step update magnitude, and determine the corresponding current step update magnitude for each refinement step. The current step update magnitude is calculated based on the initial single-step update magnitude and the current refinement step index according to a preset decay strategy. The preset decay strategy makes the current step update magnitude decrease as the refinement step index increases.

[0032] In step S325, scaling is performed using the current step update magnitude, based on the single-step update magnitude.

[0033] Furthermore, after generating the task-adaptive soft mask for medical cross-modal image synthesis in step S3, the following sub-steps are also included:

[0034] S301: Input the task-adaptive soft mask and the source modality medical image into the diffusion-based medical image generation model to obtain the target modality estimation image, and calculate the denoising task loss based on the target modality estimation image; the diffusion-based medical image generation model is a neural network model that generates the target modality medical image based on the source modality medical image and the task-adaptive soft mask; the denoising task loss is calculated based on the target modality estimation image and the real target modality image, where the real target modality image is the target modality medical image spatially registered with the source modality medical image;

[0035] S302: Calculate the gradient of the soft mask obtained in each step of the multi-step differentiable Markov state transition process in step S3 with respect to the denoising task loss, and perform a gradient stop operation to obtain the gradient teacher signal corresponding to each refinement step.

[0036] S303: Calculate the gradient teacher loss based on the gradient teacher signal and the signed correction field output by the mask thinning network in the corresponding step;

[0037] S304: Calculate the total variation regularization loss and the boundary distance regularization loss, and solve for the auxiliary gradients corresponding to the total variation regularization loss and the boundary distance regularization loss;

[0038] S305: Combine the auxiliary gradient with the main task refinement gradient corresponding to the gradient teacher loss to obtain the combined gradient;

[0039] S306: Update the parameters of the mask thinning network using the combined gradient.

[0040] Furthermore, the step S305, which involves combining the auxiliary gradient with the main task refinement gradient corresponding to the gradient teacher loss in a goal-consistent manner, includes the following sub-steps:

[0041] S3051: Using the main task refined gradient, total variation regularized gradient, and boundary distance regularized gradient as inputs, calculate the difference vector between the total variation regularized gradient and the boundary distance regularized gradient;

[0042] S3052: Calculate the inner product of the difference vector and the main task refinement gradient, and the inner product of the boundary distance regularization gradient and the main task refinement gradient;

[0043] S3053: Determine the feasible interval of the total variational regularization weights based on the two inner products;

[0044] S3054: Solve for the minimum norm solution of the auxiliary gradient combination formed by the total variation regularized weights and the boundary distance regularized weights, and project it into the feasible interval to obtain the final auxiliary weights;

[0045] S3055: If the feasible interval is empty, then reset the final auxiliary power to zero;

[0046] S3056: The total variational regularized gradient and the boundary distance regularized gradient are weighted and summed using the final auxiliary weights, and then added to the main task refinement gradient to obtain the combined gradient.

[0047] Further, step S304 calculates the boundary distance regularization loss, including the following sub-steps:

[0048] Step S3041: Perform morphological dilation and morphological erosion operations on the initial diagnostic guidance mask, and calculate the difference between the two to obtain the initial boundary response;

[0049] Step S3042: Construct an initial boundary set from the pixels that are greater than zero in the initial boundary response;

[0050] Step S3043: Calculate the Euclidean distance from each pixel to the initial boundary set to obtain a distance map;

[0051] Step S3044: Input the distance map into a monotonically increasing function controlled by a preset temperature parameter to obtain the boundary distance weights;

[0052] Step S3045: Multiply the boundary distance weight by the deviation of the task adaptive soft mask relative to the initial diagnostic guide mask pixel by pixel and sum them to obtain the boundary distance regularization loss.

[0053] Further, step S301, which involves inputting the task-adaptive soft mask and the source modality medical image into the diffusion-based medical image generation model, includes the following sub-steps:

[0054] Step S30111: Perform multi-scale encoding on the task adaptive soft mask to obtain multi-scale mask features;

[0055] Step S30112: In the denoising network of the diffusion-type medical image generation model, multiple resolution layers are selected. In each selected resolution layer, the image features of that layer are used as queries, and the mask features corresponding to that layer are used as keys and values. Cross-attention calculation is performed to obtain the mask conditional enhancement features of that layer.

[0056] Step S30113: Fuse the mask condition enhancement features of each selected resolution layer with the original image features of the corresponding layer to obtain the fused features used for denoising prediction.

[0057] Further, the step S301 of calculating the denoising task loss between the estimated target modality image and the true target modality image includes the following sub-steps:

[0058] Step S30121a: Map the target modality estimation image and the real target modality image to the standard ingress value space through the standard ingress value transformation function to obtain the estimated standard ingress value map and the real standard ingress value map. The standard ingress value transformation function is used to convert the image intensity into standard ingress value.

[0059] Step S30122a: Determine the set of voxels in the tumor region using the initial diagnostic guidance mask, wherein the set of voxels in the tumor region is the set of foreground pixels in the initial diagnostic guidance mask;

[0060] Step S30123a: Within the voxel set of the tumor region, calculate the mean absolute error between the estimated standard uptake map and the true standard uptake map to obtain the average error of the standard uptake value;

[0061] Step S30124a: The average error of the standard ingestion value is weighted and summed with a preset base loss function to obtain the denoising task loss. The preset base loss function is the average absolute error between the estimated target modality image and the real target modality image.

[0062] Further, the step S301 of calculating the denoising task loss between the estimated target modality image and the true target modality image includes the following sub-steps:

[0063] Step S30121b: Determine the set of voxels in the tumor region using the initial diagnostic guidance mask, wherein the set of voxels in the tumor region is the set of foreground pixels in the initial diagnostic guidance mask;

[0064] Step S30122b: Within the voxel set of the tumor region, calculate the pixel-wise absolute intensity difference between the estimated target modality image and the true target modality image;

[0065] Step S30123b: Average the absolute intensity difference of each pixel within the voxel set of the tumor region to obtain the average pixel error;

[0066] Step S30124b: The average pixel error is weighted and summed with a preset base loss function to obtain the denoising task loss, where the preset base loss function is the average absolute error between the target modality estimation image and the real target modality image.

[0067] Furthermore, the training of the mask thinning network and the diffusion-based medical image generation model is performed sequentially in the following stages:

[0068] First stage: Fix the parameters of the mask refinement network, and train the diffusion medical image generation model using only the source modal medical images and the initial diagnostic guidance mask until the diffusion medical image generation model meets the first preset convergence condition;

[0069] Second stage: Fix the parameters of the diffusion-type medical image generation model, or set its learning rate to be lower than the first preset threshold, and execute steps S301 to S306 to train the mask thinning network until the mask thinning network meets the second preset convergence condition.

[0070] The third stage involves simultaneously updating the parameters of the mask thinning network and the diffusion-based medical image generation model with a non-zero learning rate, performing joint fine-tuning until the third preset convergence condition is met.

[0071] Furthermore, after obtaining the gradient teacher signal corresponding to each refinement step in step S302, the following sub-steps are also included:

[0072] S3021: For the gradient teacher signal corresponding to each refinement step, perform L2 normalization according to the preset normalization dimension to obtain the normalized gradient teacher signal.

[0073] S3022: Compare the norm of the normalized gradient teacher signal with a preset norm interval. If the norm exceeds the upper limit of the preset norm interval, then prune according to the upper limit; if the norm is lower than the lower limit of the preset norm interval, then prune according to the lower limit.

[0074] S3023: The normalized gradient teacher signal after pruning is used as the final gradient teacher signal in this refinement step, and is used for the calculation of the subsequent gradient teacher loss.

[0075] Furthermore, the calculation of the gradient teacher loss in step S303 includes the following sub-steps:

[0076] S3031: Obtain the gradient teacher signal corresponding to each refinement step and the signed correction field output by the mask refinement network in the corresponding step, and calculate the single-step residual of each refinement step;

[0077] S3032: Assign a preset step weight to each refinement step, wherein the step weight monotonically remains constant or decreases exponentially as the refinement step index increases;

[0078] S3033: The single-step residuals of each refinement step are summed according to the corresponding step weights to obtain the gradient teacher loss.

[0079] Furthermore, the source modal medical image is a T1-weighted magnetic resonance imaging image, and the initial diagnostic guidance mask is a tumor mask obtained by combining at least one annotation of enhanced tumor, peritumoral edema, and necrotic core.

[0080] When the target modality is contrast-enhanced T1-weighted magnetic resonance imaging, a first training process is performed. The mask refinement network parameters obtained in the first training process enable the task to adaptively highlight the morphological regions related to the contrast-enhanced appearance using a soft mask.

[0081] When the target modality is a liquid attenuation inversion recovery sequence image, a second training process is performed. The masking refinement network parameters obtained in the second training process enable the task to adaptively highlight the morphological regions related to edema-sensitive areas and the entire tumor region using a soft mask.

[0082] The source modality medical image and initial diagnostic guidance mask used in the first training process are the same as those used in the second training process, but the target modality medical image is different.

[0083] Furthermore, the construction of the parameter-shared mask thinning network described in step S2 includes the following sub-steps:

[0084] S21: Construct input mapping convolutional blocks to map the input soft mask to a high-dimensional feature space;

[0085] S22: Construct at least two downsampling blocks, and downsample the output of the input mapping convolutional block step by step to extract multi-scale features;

[0086] S23: Construct a bottleneck block and process the last-level downsampled features to obtain the bottleneck features;

[0087] S24: Construct upsampling blocks with the same number as the downsampling blocks, perform upsampling on the bottleneck features step by step, and fuse them with the features of the corresponding downsampling blocks through skip connections in each upsampling stage;

[0088] S25: Construct an output convolutional layer to generate the signed correction field based on the output of the last upsampling block.

[0089] Furthermore, after generating the task-adaptive soft mask for medical cross-modal image synthesis in step S3, the method further includes:

[0090] Step S41: Compare the task-adaptive soft mask with a preset binarization threshold, set pixels greater than or equal to the threshold as foreground, and pixels less than the threshold as background, to obtain a binarized task-adaptive mask;

[0091] Step S42: Input the binarization task adaptive mask and the source modal medical image into the diffusion medical image generation model to generate the target modal medical image.

[0092] Furthermore, the source modal medical image is a computed tomography (CT) image, the target modal medical image is a positron emission tomography (PET) image, and the initial diagnostic guidance mask is a lesion annotation mask in the CT image;

[0093] The task-adaptive soft mask described in step S3 is used to indicate morphological regions in the source modal computed tomography images that are useful for inferring metabolic activity in positron emission tomography.

[0094] Accordingly, a second aspect of the present invention provides a differentiable Markov mask thinning system for medical cross-modal image generation, which performs medical image processing based on the above-described differentiable Markov mask thinning method for medical cross-modal image generation, including:

[0095] The data acquisition module is used to acquire source modal medical images and an initial diagnostic guidance mask spatially registered with the source modal medical images. The initial diagnostic guidance mask is a binary or continuous value mask that indicates the lesion area.

[0096] The network construction module is used to construct a parameter-sharing mask refinement network. The mask refinement network is used to output a signed correction field based on the input soft mask. In the signed correction field, positive values ​​indicate foreground expansion and negative values ​​indicate foreground contraction.

[0097] The state transition module is used to perform multi-step differentiable Markov state transitions with the initial diagnostic guidance mask as the initial state. Each state transition is based on the activity boundary indicator determined by the current soft mask, which restricts the signed correction field output by the mask refinement network to the boundary region to update the current soft mask, until a task-adaptive soft mask for medical cross-modal image synthesis is generated.

[0098] Accordingly, a third aspect of the present invention provides an electronic device, comprising: at least one processor; and a memory connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, the instructions being executed by the at least one processor to cause the at least one processor to perform the above-described differentiable Markov mask thinning method for medical cross-modal image generation.

[0099] Accordingly, a fourth aspect of the present invention provides a computer-readable storage medium having computer instructions stored thereon that, when executed by a processor, implement the above-described differentiable Markov mask thinning method for medical cross-modal image generation.

[0100] The above-described technical solutions of the embodiments of the present invention have the following beneficial technical effects:

[0101] 1. By modeling the refinement process of the initial diagnostic guide mask as a multi-step differentiable Markov state transition, and using an active boundary indicator based on morphological gradients at each step to strictly limit the mask update to the narrow band region of the current foreground and background boundary, the mask changes only occur gradually in a controllable manner near the original boundary. This allows for task-driven outward expansion or inward contraction while ensuring that the pixel states of the high-confidence regions inside the boundary and the external background regions far from the boundary are not arbitrarily modified. Thus, the unconstrained spatial drift problem in one-time high-dimensional regression is transformed into a stable asymptotic process within the feasible set of the boundary. This significantly improves the spatial rationality of the refinement results while maintaining the geometric interpretability of the mask.

[0102] 2. By introducing a gradient teacher signal that stops the gradient during the training phase, the denoising task loss of the final output of the diffusion-based medical image generation model is backpropagated step by step to each intermediate state of the mask thinning network. This allows the signed correction field of each thinning step to directly learn the direction to reduce the final generation error, rather than simply approximating a fixed intermediate target or regularization term. As a result, the macroscopic cross-modal image generation quality target is decomposed into local correction tasks that can be executed in each step, shortening the optimization path between the task supervision signal and the mask correction field. This enables the final generated task-adaptive soft mask to truly serve to improve the generation accuracy of the target modality medical image.

[0103] 3. When training the mask refinement network, instead of simply linearly superimposing the total variation regularization gradient, boundary distance regularization gradient, and main task refinement gradient, we solve for the minimum norm combination of auxiliary gradients that does not oppose the main task direction constraint, forming a combined gradient consistent with the descent direction of the main task. At the same time, we introduce monotonically increasing weights based on the Euclidean distance from the pixel to the initial mask boundary in the boundary distance regularization, so that changes near the original boundary are only weakly penalized, while large-scale drifts far from the boundary are strongly constrained. This suppresses local mask noise and long-distance distortion while avoiding the auxiliary regularization from covering the optimization direction of the main task, achieving a synergistic improvement in mask smoothness and task adaptability. Attached Figure Description

[0104] Figure 1 This is a flowchart of a differentiable Markov mask thinning method for medical cross-modal image generation provided in an embodiment of the present invention;

[0105] Figure 2 This is a schematic diagram illustrating the principle of micro-Markov mask refinement provided in an embodiment of the present invention;

[0106] Figure 3This is a diagram showing the construction result of the boundary indicator and boundary distance weight provided in the embodiment of the present invention;

[0107] Figure 4 This is a multi-step Markov mask refinement trajectory diagram provided in the embodiments of the present invention;

[0108] Figure 5 This is a task loss-driven gradient teacher visualization diagram provided in an embodiment of the present invention;

[0109] Figure 6 This is a geometric interpretation diagram of the target-consistent auxiliary gradient combination provided in the embodiments of the present invention;

[0110] Figure 7 This is a medical cross-modal generation verification and quality control diagram provided in an embodiment of the present invention;

[0111] Figure 8 This is a block diagram of a differentiable Markov mask refinement system for cross-modal medical image generation provided in an embodiment of the present invention.

[0112] Figure label:

[0113] 1. Data acquisition module; 2. Network construction module; 3. State transition module. Detailed Implementation

[0114] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to specific embodiments and the accompanying drawings. It should be understood that these descriptions are merely exemplary and not intended to limit the scope of the invention. Furthermore, descriptions of well-known structures and techniques are omitted in the following description to avoid unnecessarily obscuring the concept of the invention.

[0115] This invention systematically improves the spatial cueing mechanism in medical cross-modal image generation by constructing a dual-network architecture where a parameter-sharing mask thinning network and a diffusion-based medical image generation model work together. In this architecture, the mask thinning network is designed as an iterative optimization unit performing multi-step differentiable Markov state transitions under morphologically constrained conditions. Each state transition strictly constrains the update range of the signed correction field within a narrow foreground-background boundary region of the current mask through an active boundary indicator. This ensures that mask changes occur gradually and controllably only near the original boundary, rather than relying on a one-time high-dimensional regression to directly predict the final mask. The soft mask generated through multi-step iterations no longer serves diagnostic segmentation purposes but instead acts as a task-adaptive spatial cue directly associated with the downstream generation task's objective function, injected into the diffusion-based medical image generation model to guide the cross-modal image synthesis process. This architectural improvement transforms spatial cue generation from a fixed preprocessing step into a closed-loop optimization process that can be trained end-to-end and adaptively adjusted according to the generation task objective, resolving the structural contradiction between the inconsistent distribution of spatial information required by the diagnostic-guided hard mask and the generation task.

[0116] Please refer to Figure 1 The first aspect of this invention provides a differentiable Markov mask thinning method for medical cross-modal image generation, comprising the following steps:

[0117] S1: Obtain the source modal medical image and the initial diagnostic guidance mask spatially registered with the source modal medical image. The initial diagnostic guidance mask is a binary or continuous value mask indicating the lesion region.

[0118] The acquired source modality medical image can be a computed tomography (CT) image, a T1-weighted magnetic resonance imaging (MRI) image, or other imaging modalities that provide anatomical structural information. The initial diagnostic guidance mask, spatially registered with it, is a binary or continuous soft mask used to indicate the lesion region, obtained through manual annotation, automatic segmentation algorithms, or a fusion of both. The source of this mask determines that its boundary primarily reflects the lesion range that the physician is concerned with in the diagnostic or segmentation task, such as the lesion outline in a CT image or a tumor subregion in an MRI image. Because this type of mask serves diagnostic purposes, its boundary position may deviate from the image region that actually contains information when inferring the target modality from the source modality. Therefore, it needs to be adjusted adaptively in subsequent steps. In this step, both the source modality image and the initial mask undergo spatial registration and necessary normalization processing to ensure a strict spatial correspondence, providing a geometrically consistent basis for subsequent pixel-level mask refinement operations.

[0119] In an optional implementation, for computed tomography-to-positron emission tomography (CT-PET) synthesis, data including paired PET / CT scans and lesion annotations can be used. Spatial registration is performed on the two modalities of the same subject, and the images are resampled to the same pixel spacing and matrix size based on physical spatial coordinates. CT images can be truncated and normalized according to preset window widths and levels, and PET images can be converted to standard uptake values ​​or normalized according to robust quantiles. Only slices or masses with effective masks are retained, and CT lesion annotations are used as... .

[0120] For multi-sequence magnetic resonance imaging (MRI) synthesis, data including T1, T1CE, T2, and FLAIR sequences, along with tumor subregion annotations, can be used. Registration, skull removal, bias field correction, and intensity normalization are performed on each sequence. Enhanced tumor, peritumoral edema, necrosis, and non-enhanced core are merged into an initial mask as needed for the task. T1-T1CE and T1-FLAIR sequences can share the same data preprocessing workflow, but task-specific refinement parameters are trained or configured separately.

[0121] The dataset is divided into training, validation, and test sets at the subject level to avoid leakage caused by slices from the same subject crossing sets. One implementation configuration can use ratios of 70%, 10%, and 20%; the fluorodeoxyglucose PET / CT lesion dataset (FDG-PET-CT-Lesions) can contain 501 scans, and the Brain Tumor Segmentation Challenge 2020 dataset (BraTS2020) contains 369 scans. The specific data size is not a limitation of this invention. Random flipping, rotation, cropping, intensity perturbation, and mild elastic deformation can be performed on the training images, but the source modality, target modality, and mask must use the same spatial transformation. For masks with excessively small areas or abnormal boundaries, a minimum connected component threshold can be set and quality labels can be recorded.

[0122] S2: Construct a parameter-sharing mask thinning network. The mask thinning network is a convolutional network with an encoder-decoder structure, which includes an input mapping convolutional block, multiple downsampling blocks, a bottleneck block, multiple upsampling blocks, and an output convolutional layer connected in sequence. The upsampling blocks are fused with the features of the corresponding downsampling blocks through skip connections. The output convolutional layer is used to output a signed correction field. Positive values ​​in the signed correction field indicate foreground expansion, and negative values ​​indicate foreground contraction.

[0123] The constructed parameter-sharing mask thinning network is a lightweight convolutional neural network. Its function is to receive the soft mask of the current step as input and output a signed correction field with values ​​that can be positive or negative. Positive pixels in this correction field suggest enhancing a local background region in the current mask to foreground (i.e., performing an expansion operation); negative pixels suggest weakening or shrinking a local foreground region to background (i.e., performing a shrinking operation). This signed design allows the same network to simultaneously handle both undersegmentation and oversegmentation boundary deviations that may exist in the initial mask, without requiring separate correction modules. The specific structure of the mask thinning network can adopt a U-shaped network design, including input mapping convolutional layers, downsampling blocks, bottleneck blocks, upsampling blocks, and skip connections. Finally, the correction field is directly generated through an output layer without a non-negative activation function. All convolutional layer parameters are completely shared across multiple thinning steps, which significantly reduces the number of parameters to be trained. Simultaneously, it forces the network to learn a general update rule that is independent of specific step indices and depends only on the current mask state, providing a structural basis for the Markov property of state transitions.

[0124] S3: Using the initial diagnostic guidance mask as the initial state, perform multi-step differentiable Markov state transitions. Each state transition is based on the activity boundary indicator determined by the current soft mask, which restricts the signed correction field output by the mask refinement network to the boundary region to update the current soft mask, until a task-adaptive soft mask for medical cross-modal image synthesis is generated.

[0125] Starting with the initial diagnostic guide mask as the starting point for state transitions, it is mapped to a continuous soft mask between 0 and 1, followed by a multi-step differentiable Markov state transition process. Each state transition follows the same operational paradigm: First, an active boundary indicator is generated based on the current soft mask through morphological operations. Specifically, a square structuring element with a preset radius can be used to perform grayscale dilation and grayscale erosion operations on the current soft mask to obtain an outer boundary band and an inner boundary band, which correspond to the potential regions where the mask can expand outward and contract inward, respectively. After merging the outer and inner boundary bands, an unsigned morphological gradient is calculated, normalized, and compared with a preset boundary activation threshold to obtain a binary or continuous boundary indicator that is activated only near the current foreground-background boundary. The function of this indicator is to strictly limit the allowed region for mask updates to within the narrow boundary band, ensuring that the high-confidence foreground and background regions far from the boundary remain unchanged during the refinement process. Subsequently, the current soft mask is input into the parameter-sharing mask refinement network constructed in step S2 to obtain a signed correction field. This correction field is then multiplied pixel-by-pixel with the active boundary indicator, thus retaining only the correction values ​​within the boundary region and masking any updates in other regions. Next, the constrained correction field is scaled by a preset single-step update magnitude and then added pixel-by-pixel with the current soft mask. The result is truncated to between 0 and 1 to obtain the updated soft mask state. This process is repeated as a complete state transition step, and the number of steps can be preset according to the task complexity until the final task-adaptive soft mask is obtained. Throughout the multi-step iteration, since each update depends only on the current mask state and the shared parameter network, and the boundary indicator only allows changes near the boundary, the mask evolution path has interpretable Markov properties, enabling a smooth transition from the initial diagnostic guidance mask to spatial cues that are closer to the generation task requirements. The value of each pixel in the final generated soft mask can be interpreted as the confidence that the pixel belongs to the task-related region. This continuous confidence distribution can describe the spatial range that needs to be focused on when inferring the target mode from the source mode more finely than the hard mask.

[0126] like Figure 2 As shown, Figure 2 Part a presents a side-by-side comparison of the source modal CT image, the target modal PET image, the initial diagnostic guidance mask, and the task-adaptive soft mask generated through multi-step differentiable Markov state transitions at the same spatial location, intuitively demonstrating the difference between the manual diagnostic mask and the spatial cues required to generate the task. Figure 2 Part b in the diagram uses a red outline to mark the original mask boundary and a cyan outline to mark the allowed update narrowband support region determined by the active boundary indicator, illustrating the spatial constraint principle of the boundary-constrained update mechanism. Figure 2Part c of the paper presents the trend curves of the upper bound of task risk and the gradient teacher residual decreasing as the number of refinement steps increases during the multi-step refinement process, reflecting the stabilizing effect of the gradient teacher signal on the multi-step optimization process. Figure 2 The d part places the main task refined gradient, the total variation regularized gradient, the boundary distance regularized gradient, and the auxiliary gradient after the objective consistency combination in the same geometric space. The auxiliary regularization is indicated by arrows and half-space regions. It only participates in parameter updates if it does not oppose the direction of the main task. The arrows, letter labels and title positions have been separated to avoid visual overlap.

[0127] Through the steps described above, this method transforms the diagnostic-oriented artificial hard mask into a continuous soft spatial cue that adapts to the cross-modal image generation task. Compared to directly using a fixed hard mask or a one-time regression mask, this boundary-constrained multi-step differentiable Markov state transition mechanism ensures that mask changes occur gradually and with a controllable amplitude only near the original boundary. This allows the task-driven boundary to expand outward or contract inward while avoiding disordered drift and discrete noise far from the boundary. Thus, while maintaining the geometric interpretability of the spatial cue, it significantly improves its adaptability to downstream image generation tasks, providing more accurate spatial conditions for the subsequent generation of high-quality medical target modal images.

[0128] Specifically, step S3 involves performing a multi-step differentiable Markov state transition, including the following sub-steps:

[0129] S31: Map the initial diagnostic guide mask to the range [0,1] as the current soft mask, and set the total refinement steps and the single-step update magnitude.

[0130] In the specific implementation of the multi-step differentiable Markov state transition, the initialization of the refinement process is first completed through sub-step S31. The initial diagnostic guide mask is mapped to a continuous interval of 0 to 1. The purpose is to relax the originally binary hard mask, which might only contain 0s and 1s, into a continuous-value soft mask, so that the value of each pixel can represent the confidence or membership degree of that pixel belonging to the foreground region, providing a numerical basis for the gradual and continuous changes of the mask in subsequent steps. For the initial mask, which is already a continuous value, this mapping operation also serves as a normalization function, ensuring that its value range is consistent with the numerical range of subsequent update operations. Simultaneously, two key control parameters need to be set in this step: the total number of refinement steps and the update amplitude per step. The total number of refinement steps determines the number of state transitions the mask needs to undergo from its initial state to its final state. Its value directly affects the precision of the mask refinement. Too few steps may prevent the mask from converging sufficiently to the optimal state, while too many steps may increase computational overhead and introduce redundant boundary oscillations. In practice, the total number of steps for 2D image tasks can be set between 5 and 20 steps, while for 3D volumetric data tasks, it can be adjusted appropriately based on the voxel resolution. The single-step update amplitude controls the maximum modification of the correction field to the current mask in each state transition. Its value needs to match the output range of the signed correction field. An excessively large amplitude may cause overshoot and oscillations near the boundaries, while an excessively small amplitude requires more steps to achieve the same level of boundary adjustment. In practical applications, it can be set within a small numerical range, ensuring that the change in each step is controlled within a fraction of a pixel value, thus guaranteeing the smoothness of the evolution process.

[0131] S32: Perform a single state transition step to update the current soft mask and obtain the intermediate soft mask.

[0132] In the single-step state transition, an active boundary indicator is first generated based on the current soft mask. This indicator extracts the foreground-background boundary region of the current mask through morphological dilation and erosion operations, forming an active region that only covers the narrow boundary band. The width of this active region is controlled by a preset structuring element radius. The selection of the structuring element radius determines the width of the narrow boundary band. In 2D tasks, it is typically set to 1 to 5 pixels, while in 3D tasks, different radius values ​​can be set in the axial and interlayer directions to accommodate anisotropic voxel spacing. After determining the active boundary region, the current soft mask is input into the parameter-shared mask refinement network constructed in step S2. This network outputs a signed correction field based on the spatial morphology of the current mask, where positive values ​​indicate the expansion direction of enhancing the local background into the foreground, and negative values ​​indicate the contraction direction of weakening the local foreground into the background. Subsequently, the signed correction field is multiplied pixel-by-pixel with the active boundary indicator. This multiplication operation strictly limits the effective range of the correction field to a narrow boundary band. Correction values ​​outside the boundary region, regardless of magnitude, are set to zero, ensuring that only pixels located at the current foreground-background boundary undergo state changes in this update. Finally, the constrained correction field is scaled by a preset single-step update increment and added pixel-by-pixel to the current soft mask to obtain the intermediate result of this state transition, i.e., the intermediate soft mask. The entire single-step state transition process is fully differentiable, allowing the final target mode generation loss to be propagated through all thinning steps to the mask thinning network via backpropagation.

[0133] S33: Truncate the intermediate soft mask to the range [0,1] and use it as the new current soft mask.

[0134] A pixel-by-pixel truncation operation is performed on the intermediate soft mask, restricting the value of each pixel to a closed interval between 0 and 1. This truncation step serves a numerical stabilization purpose: after updating the intermediate mask with a signed correction field, some pixel values ​​may exceed the valid range of 0 to 1 due to excessive correction. If this is not addressed before proceeding to the next update, the accumulated numerical offset may cause the mask state to gradually deviate from the valid probabilistic interpretation space, resulting in a drift in the input distribution upon which morphological operations and network inference are based in subsequent steps. By immediately truncating the mask values ​​back to the 0-1 interval after each state transition, it is ensured that the current soft mask at each step is always a semantically valid continuous value mask, providing numerically stable input conditions for the generation of the activity boundary indicator and the prediction of the correction field in the next round.

[0135] As an optional implementation, boundary-constrained multi-step mask refinement can be configured as follows:

[0136] Will Convert to a floating-point tensor. For each step... Max pooling is used to achieve grayscale dilation, and max pooling followed by negative scaling is used to achieve grayscale erosion, thus keeping the morphological operations within a differentiable computational graph. (Structure element radius) The results can be determined through a validation set search; for two-dimensional tasks, the search can start from a range of 1 to 5 pixels, while for three-dimensional tasks, the axial and interlayer radii can be set respectively.

[0137] After summing the inner and outer boundary bands, use the maximum boundary response of the current sample plus the stability constant. Normalize, then with A boundary indicator is formed by comparison. The indicator can be a hard threshold or a soft gate approximated by a sigmoid. This configuration corresponds to the active boundary constraint in this invention, used to ensure that the correction field acts only near the current foreground-background interface.

[0138] The refined network is preferably a lightweight U-shaped network, including an input mapping convolutional block, two downsampling blocks, a bottleneck block, two upsampling blocks, and skip connections corresponding to the downsampling layers. The input channel may contain only... You can also attach source images. Distance map The current step encoding is used. The output layer does not use non-negative activation, allowing the correction field to take positive and negative values; the maximum correction amplitude can be limited using tanh.

[0139] Shared parameters for each step This can significantly reduce the number of parameters and keep the state transition rules consistent. Determines the intensity of a single-step change. Determine the iteration depth. Excessive size can cause boundary oscillations. If the value is too small, sufficient adjustments cannot be made; a joint search can be performed on the validation set, or... Decrease with each step. After each update, a [0,1] truncation is performed to ensure that the intermediate states retain a valid probabilistic interpretation.

[0140] S34: Repeat steps S32 to S33 until the total number of refinement steps is completed, and obtain the task-adaptive soft mask.

[0141] The entire multi-step refinement process is completed through iterative iterations. The single-step update of sub-step S32 and the numerical truncation of sub-step S33 are considered a complete operation cycle, repeated until the total refinement steps set in sub-step S31 are reached. In each iteration, the truncated soft mask from the previous round serves as the input for the new round's soft mask. After undergoing the same boundary-constrained state transition operation, a new intermediate result is generated and truncated again, forming a progressively evolving mask state chain. Since each update is confined within a dynamically changing boundary narrow band, as the mask boundary gradually moves during iteration, the activation area of ​​the active boundary indicator also undergoes corresponding spatial displacement, allowing the mask boundary to expand outward or contract inward in a gradual manner. In the early stages of iteration, the mask's morphological changes are relatively large, mainly completing the directional migration of the initial diagnostic boundary to the task-related region; as the number of iterations increases, the boundary gradually approaches the task's optimal position, the correction amplitude of subsequent steps naturally decreases, and the mask state tends to stabilize. After completing the preset total number of refinement steps, the truncated soft mask output in the last iteration becomes the final task-adaptive soft mask. Throughout the entire iterative process, all refinement steps share the same mask refinement network parameters. The number of parameters does not increase with the number of refinement steps, and the state transition rules for each step remain consistent, reflecting the core characteristic of Markov processes that the next state depends only on the current state.

[0142] The above-mentioned multi-step differentiable Markov state transition process can be formally described by the following core mathematical model.

[0143] In any refinement step This invention employs the following differentiable Markov state transition. Given the current mask, the next state depends only on the current state, the current boundary indicator, and the output of the shared parameter network:

[0144]

[0145] in, Indicates pixel-by-pixel truncation. This represents pixel-wise multiplication. This update is part of a differentiable computation graph, allowing the final generation loss to propagate back through all refinement steps. The final mask is represented as:

[0146]

[0147] Define the radius as Square structural elements And perform grayscale morphological operations on the current soft mask:

[0148]

[0149] Depend on Determine the activity boundary area The cumulative activity region is obtained by taking the union of the activity regions from each step. The final mask remains consistent with the initial mask outside the cumulative activity region, thus forming a feasible set of edge constraints.

[0150]

[0151] This method constructs the refinement process of the initial diagnostic guidance mask as a controllable, differentiable, Markov-property-compliant multi-step state transition sequence. This design decomposes the instability problem in one-time high-dimensional mask regression into a series of boundary-constrained small-amplitude update operations. This ensures that the mask changes at each step remain within an interpretable narrow band, and establishes a unified update strategy across multiple steps through a shared parameter network. This reduces the number of network parameters while guaranteeing the convergence and stability of the refinement process. The resulting spatial cues are better suited to the needs of subsequent medical cross-modal image generation tasks.

[0152] Furthermore, each state transition step in step S32 includes the following sub-steps:

[0153] S321: Perform grayscale dilation and grayscale erosion operations on the current soft mask to obtain the outer boundary band and the inner boundary band.

[0154] In the specific execution of a single state transition step, grayscale dilation and grayscale erosion operations are first performed on the current soft mask to obtain two boundary bands: an outer one and an inner one. The grayscale dilation operation uses a square structuring element of a preset radius, taking the maximum value within each pixel neighborhood of the soft mask. This effectively pushes the boundary of the foreground region outward, resulting in an outer boundary band that is slightly dilated than the current mask. Similarly, the grayscale erosion operation uses a structuring element of the same radius, taking the minimum value within each pixel neighborhood of the soft mask. This effectively shrinks the boundary of the foreground region inward, resulting in an inner boundary band that is slightly smaller than the current mask. In practice, grayscale dilation can be achieved by performing a sliding window maximum pooling operation on the soft mask, while grayscale erosion can be achieved by performing the same maximum pooling operation on the negative values ​​of the soft mask and then taking the negative value. This implementation method ensures that morphological operations remain within the differentiable computational graph of the automatic differentiation framework. The selection of the structuring element radius determines the width of the boundary band. The larger the radius, the wider the extracted boundary band, and the larger the area that allows for mask variation. In practical applications, the structuring element radius for 2D image tasks can be set to 1 to 5 pixels, while for 3D volumetric data tasks, different radii can be set in the axial and interlayer directions to accommodate anisotropic voxel spacing. The two boundary bands obtained through grayscale dilation and erosion operations define the spatial range within which the current mask foreground can expand outward and contract inward, respectively, providing a complete geometric candidate region for subsequent bidirectional correction.

[0155] S322: Merge the outer boundary band and the inner boundary band, and obtain the active boundary indicator after normalization and thresholding.

[0156] The outer and inner boundary bands are merged into a unified boundary response map, and an active boundary indicator is generated through normalization and thresholding. The merging operation is performed by adding the two boundary bands pixel by pixel. The result reflects the intensity response of each pixel near the current mask boundary; larger response values ​​indicate closer proximity to the foreground-background boundary. To ensure comparability of boundary responses across different samples and refinement steps, the merged boundary response is normalized. Specifically, the response value of each pixel is divided by the sum of the maximum boundary response of the current sample and a preset stability constant. This stability constant is introduced to avoid division by zero and suppress noise amplification in smooth regions where the overall boundary response is weak. The normalized boundary response map is compared with a preset boundary activation threshold. Pixels with values ​​greater than the threshold are set to active, while the remaining pixels are set to inactive, resulting in a binary active boundary indicator. The active region corresponds to the narrow band at the foreground-background boundary of the current soft mask. In engineering practice, the Sigmoid function can be used instead of hard threshold comparison to generate a soft boundary indicator with continuous values, resulting in a smooth transition between active and inactive regions. The role of the active boundary indicator is to provide spatial gating for the application range of the subsequent correction field, ensuring that only pixels located near the boundary can receive correction updates from the mask thinning network.

[0157] like Figure 3 As shown, the construction process of the active boundary indicator includes the following steps: Figure 3 The current soft mask state of part a in the diagram. Figure 3 part b in Figure 3 In part c, the outer and inner boundary bands are obtained through grayscale expansion and grayscale etching, respectively. Together, they define the spatial range within which the mask can expand outward and contract inward. Figure 3 The 'd' part in the figure represents the morphological gradient response obtained from the difference between the dilation and erosion results, highlighting the transition region at the boundary between the current foreground and background. Figure 3 The 'e' part is the active boundary indicator obtained after normalization and comparison with the preset boundary activation threshold. Only this active region is allowed to receive updates from the subsequent correction field.

[0158] S323: Input the current soft mask into the mask refinement network to obtain the signed correction field.

[0159] The current soft mask is fed as input into the parameter-sharing mask thinning network constructed in step S2. This network outputs a signed correction field with values ​​that can be positive or negative. This correction field has the same spatial dimensions as the input soft mask, and the value at each pixel represents the suggested strength of expansion or contraction correction at that location. Positive values ​​correspond to expansion regions where the network determines the area should transition from background to foreground, while negative values ​​correspond to contraction regions where the network determines the area should transition from foreground to background. The absolute value reflects the confidence or strength of the correction. Since the parameters of the mask thinning network are shared throughout all thinning steps, the network must learn a general update strategy that depends only on the current mask shape and not on specific step indices. This design allows the network to capture common features of the mask state while significantly reducing the number of parameters to be trained. In terms of actual network structure selection, a lightweight U-shaped convolutional network can be adopted, which includes an encoder, a decoder, and skip connections to fuse contextual information at different scales. Instead of using non-negative activation functions such as Sigmoid or ReLU, the output layer uses linear activation or Tanh activation functions to ensure that the correction field can output positive and negative values.

[0160] S324: Multiply the signed correction field pixel by pixel with the active boundary indicator to obtain the restricted correction field.

[0161] By multiplying the signed correction field pixel-by-pixel with the active boundary indicator, a constrained correction field is obtained, achieving an organic coupling between spatial constraints and task-driven approaches: pixels in the active boundary region of the active boundary indicator have an indicator value of 1, and the original value of the correction field is retained after multiplication; pixels in the inactive region of the active boundary indicator, including high-confidence regions inside the foreground far from the boundary and regions outside the background, have an indicator value of 0, and the correction value at the corresponding position is forced to zero after multiplication. Through this multiplication gating mechanism, the correction signal output by the mask thinning network is strictly limited to functioning within a narrow band defined by the morphological boundary. No matter how large the correction value output by the network outside the boundary region, it cannot affect the mask state. This combination of geometric constraints and network learning allows the mask thinning network to focus all its representational capabilities on learning the optimal correction direction near the boundary without needing to learn how to suppress invalid updates outside the boundary region during training, significantly improving the network's training efficiency and generalization performance.

[0162] S325: Add the current soft mask to the constrained correction field scaled by the single-step update amplitude pixel by pixel to obtain the intermediate soft mask.

[0163] The current soft mask is pixel-by-pixel added to the restricted correction field scaled by the single-step update magnitude to obtain the intermediate soft mask for this state transition. Before addition, the restricted correction field needs to be multiplied by the preset single-step update magnitude in sub-step S31. This magnitude parameter controls the maximum amount of modification to the mask state by each step of the correction field, and its value range is usually a small positive number, so that the mask is only slightly adjusted in each iteration. The scaled correction value is added pixel-by-pixel to the corresponding pixel value of the current soft mask. For regions with positive correction values, the mask value increases, and the foreground region expands outward at that position; for regions with negative correction values, the mask value decreases, and the foreground region contracts inward at that position; for regions where the correction value is zeroed by the boundary indicator, the mask value remains unchanged. By using this pixel-by-pixel addition method, the current soft mask undergoes only gradual changes with limited boundaries and controllable amplitude in each refinement step. This avoids the boundary oscillations that may be caused by a large one-time update, and ensures the differentiability of the entire multi-step refinement process. This allows the gradient of the loss function of the final generated model to be smoothly backpropagated to the mask refinement network through this addition and scaling operation.

[0164] The above process couples the geometrically feasible region determined by morphological boundary detection with the task-driven correction field learned by the network through multiplicative gating. Controlled updates are then achieved through amplitude scaling and pixel-by-pixel accumulation, ultimately generating an intermediate soft mask that has undergone one-step refinement. This design ensures that each change to the mask is simultaneously regulated by both task-driven data flow and spatial constraints from morphology, providing a mechanism to guarantee the stable convergence and interpretability of the multi-step Markov state transition process.

[0165] Furthermore, the generation of the active boundary indicator in steps S321 and S322 includes the following sub-steps:

[0166] S3211: Using a square structuring element with a preset radius, perform a grayscale expansion operation on the current soft mask to obtain the expansion result.

[0167] The grayscale dilation operation uses the local neighborhood covered by the structuring element as a window, and takes the maximum value of all pixels within the window as the output. Its intuitive effect is to expand the boundary of the foreground region in the soft mask outward, so that the background pixels that were originally close to the boundary get a higher response value in the dilation result, thus forming an outer region that is slightly enlarged relative to the current mask.

[0168] S3212: Using a square structural element, perform a grayscale etching operation on the current soft mask to obtain the etching result.

[0169] A grayscale erosion operation is performed on the current soft mask using a square structuring element of the same radius to obtain the erosion result. The grayscale erosion operation takes the minimum value of all pixels in the local neighborhood covered by the structuring element as the output. Its effect is to shrink the boundary of the foreground region inward, so that the response value of the foreground pixels that were originally close to the boundary is reduced in the erosion result, thus forming an inner region that is slightly smaller than the current mask.

[0170] The difference between the dilation and erosion results corresponds precisely to the transition zone at the boundary between the foreground and background of the current mask. Their combined use provides a complete geometric description of the expandable and contractible spatial range of the mask. In specific implementations, grayscale dilation can be equivalently achieved through max pooling, while grayscale erosion can be achieved by first negativening the soft mask, then performing max pooling, and finally negativening again. This approach maintains the morphological operations within the differentiable computational graph of the automatic differentiation framework, providing a numerical computational basis for end-to-end training of the entire thinning process. The radius of the square structuring element directly determines the width of the extracted boundary band. A smaller radius results in a narrower activation range for the boundary indicator, leading to more conservative and accurate mask updates, but may limit the maximum adjustment range per step. A larger radius allows a wider boundary region to receive correction updates, suitable for scenarios with large initial mask deviations, but may introduce redundant updates far from the true boundary. In actual deployments, this radius can be determined as a hyperparameter through a search on the validation set.

[0171] S3221: Calculate the difference between the expansion result and the corrosion result to obtain the unsigned morphological gradient.

[0172] This morphological gradient reflects the boundary response strength of the current soft mask at each pixel location. The region with the largest response value is concentrated at the boundary between the current foreground and background, while the flat foreground interior region far from the boundary and the uniform background exterior region have similar values ​​due to dilation and erosion, and their difference approaches zero. This method of calculating the unsigned morphological gradient is consistent with the morphological edge detection method in classical image processing, but in this scheme it is embedded in a differentiable multi-step iterative framework, dynamically providing boundary region information that precisely matches the current mask shape for each round of refinement.

[0173] S3222: Normalize the unsigned morphological gradient by the sum of the maximum boundary response of the current sample and the preset stability constant to obtain the normalized gradient.

[0174] This normalization strategy uses the maximum boundary response of the current sample as the normalization benchmark, which is a sample-level adaptive normalization, rather than batch or global normalization. Its advantage lies in the fact that the boundary response of each sample is independently scaled according to the mask morphology of that sample, avoiding the normalization offset problem caused by significant differences in lesion size and boundary complexity between different samples. The introduction of a preset stability constant is used to prevent numerical overflow caused by the denominator approaching zero in extreme cases where the overall boundary response is weak or the mask degenerates into full foreground or full background, while also suppressing the risk of noise being improperly amplified in low-response regions.

[0175] S3223: Compare the normalized gradient with the preset boundary activation threshold, set the pixels with values ​​greater than the threshold to be active, and set the rest to be inactive, to obtain the active boundary indicator.

[0176] The normalized gradient is compared with a preset boundary activation threshold. Pixel-by-pixel, the normalized response at each location is checked to see if it exceeds the threshold. Pixels exceeding the threshold are set to an active state, indicating that the location belongs to the active boundary region of the current mask and is allowed to receive subsequent correction updates. The remaining pixels are set to an inactive state, and their corresponding correction values ​​will be zeroed in subsequent multiplication gating operations. The selection of this threshold determines the activation sparsity of the active boundary indicator. The higher the threshold, the narrower the activated boundary region, and the more conservative the mask update; the lower the threshold, the wider the activated region, and the larger the allowable adjustment range per step. In engineering practice, this threshold can be adjusted in conjunction with the structuring element radius to jointly control the strictness of the boundary-constrained update strategy. In an alternative implementation of soft boundary gating, a sigmoid function with a temperature coefficient can be used instead of a hard threshold comparison, creating a continuous transition band between the active and inactive regions, thereby further smoothing the gradient backpropagation process.

[0177] The active boundary indicator is dynamically generated in each refinement step based on the latest shape of the current soft mask, rather than being fixed after pre-calculation based on the initial mask. This dynamic generation mechanism ensures that the active boundary region is updated in real time along with the movement of the mask boundary: when the mask expands outward in a certain step, the active boundary region in the next step will also translate outward accordingly, allowing the mask boundary to move continuously and gradually; when the mask boundary approaches the task-optimal position, the correction amplitude naturally decreases, and the response intensity of the active boundary region also weakens, and the refinement process tends to converge. This dynamic characteristic of the active boundary indicator, together with the general update rule of the shared parameter network, constitutes the two core pillars of the differentiable Markov state transition: the former limits the geometrically feasible region of single-step change from the spatial dimension, and the latter provides the task-driven correction direction from the learning dimension. The two work together through multiplication gating and pixel-by-pixel accumulation operations, so that the mask only undergoes a gradual evolution with limited boundaries, controllable amplitude, and interpretable direction in each step, providing a mechanism guarantee for achieving a stable transformation from a diagnostic-oriented hard mask to a task-adaptive soft mask.

[0178] Furthermore, after all preset iterations of the multi-step differentiable Markov state transition are completed, the complete preservation and visualization of the mask evolution trajectory are achieved through the following sub-steps after step S34:

[0179] Step S35: Save the intermediate soft mask obtained from each execution of step S32 to obtain the intermediate mask sequence. The intermediate mask sequence, together with the initial diagnostic guidance mask and the task adaptive soft mask, constitute the mask evolution trajectory.

[0180] During each execution of a single state transition step S32, the output intermediate soft masks are saved one by one, forming a sequence of intermediate masks arranged chronologically according to the refinement steps. This sequence, together with the initial diagnostic guidance mask and the finally generated task-adaptive soft mask, forms a complete mask evolution trajectory. Each intermediate mask in the evolution trajectory is a continuous soft mask with values ​​ranging from 0 to 1, recording the spatial state of the mask boundary at that refinement step. Its value directly reflects the confidence level of each pixel belonging to the task-related region. Saving the intermediate mask sequence only involves temporary data storage and collection during the entire multi-step refinement process, without changing the state transition calculation flow. It has minimal impact on the network's inference efficiency and computational complexity, but provides detailed intermediate state records for subsequent visualization analysis and clinical review. In specific implementations, the intermediate mask sequence can be stored in memory or video memory. If the number of refinement steps is large or the mask space size is large, an interval saving strategy can also be adopted, extracting keyframes from the trajectory at fixed step intervals to balance the requirements of storage overhead and visualization continuity.

[0181] like Figure 4As shown, from the initial soft mask state to the final task-adaptive soft mask state, the mask contour changes of the same case slice in the continuous refinement steps are presented frame by frame with red outlines, demonstrating the gradual evolution of the mask boundary in multi-step state transitions. This shows that the present invention does not revert to the high-dimensional mask all at once, but gradually adjusts the boundary through a parameter-sharing mask refinement network and differentiable Markov state transitions, so that the mask changes have spatial continuity and process interpretability.

[0182] Step S36: Superimpose each mask in the mask evolution trajectory onto the source modality medical image in chronological order to generate a mask evolution visualization image sequence. The mask evolution visualization image sequence is used to show the spatial cue change process from the diagnostic guidance mask to the task adaptive soft mask.

[0183] The specific implementation of the overlay operation is as follows: using the source modal medical image as the underlying background image, the contour lines or semi-transparent filled areas of each mask in the evolution trajectory are rendered with a specific color and overlaid on the corresponding spatial positions of the source image. The mask overlay results at different time steps are arranged sequentially to form a series of images that dynamically display the changes in mask boundaries as the refinement steps progress. In practical applications, the contour of the initial diagnostic guidance mask can be displayed using a high-contrast color such as red, while the final refined soft mask can be displayed using cyan or green. The mask contours of intermediate steps can use a transition color between the two colors, so that the entire evolution sequence visually forms a gradient effect of a smooth transition from the initial diagnostic boundary to the final task-adaptive boundary. For continuous value regions in the soft mask, heatmaps or semi-transparent fills of different transparency levels can be used to represent the confidence level of pixels. The foreground internal area with clear boundaries is presented with a darker fill color, while the transition area with lower confidence near the boundary is presented with a lighter tone, thus intuitively displaying the complete evolution process of the mask from hard boundary to soft boundary, and from diagnostic guidance to task adaptation. This visualized image sequence can be output frame-by-frame as static frames, or synthesized into a dynamic demonstration sequence. Clinicians or researchers can review frame-by-frame changes in the spatial position of the mask boundary during each refinement step, verifying whether boundary adjustments are strictly limited to a reasonable range near the initial boundary, and whether abnormal spatial drift or excessive contraction and expansion have occurred. This provides an intuitive visual basis for evaluating the reliability and safety of the mask refinement method in practical medical image generation tasks. The preservation and visualization of the mask evolution trajectory endows this multi-step iterative refinement process, which might otherwise be considered a black box operation, with full interpretability and auditability, becoming an important bridge connecting algorithm output and clinical quality control.

[0184] Further, step S31 sets the total number of refinement steps and the single-step update magnitude, including: setting the total number of refinement steps and the initial single-step update magnitude, and determining the corresponding current step update magnitude for each refinement step. The current step update magnitude is calculated based on the initial single-step update magnitude and the current refinement step index according to a preset decay strategy. The preset decay strategy makes the current step update magnitude decrease as the refinement step index increases.

[0185] In the refinement parameter setting stage of step S31, in addition to mapping the initial diagnostic guide mask to a continuous interval of 0 to 1 as the initial state, it is also necessary to set the total number of refinement steps and the initial single-step update amplitude, and determine the corresponding current step update amplitude for each refinement step. The initial single-step update amplitude is the update step size at the starting point of the entire refinement process, and its value is usually a small positive number, ensuring that the modification amount of the mask by a single state transition is controlled within a fraction of a pixel value, thereby guaranteeing the smoothness of the mask boundary in multi-step evolution. Based on this, the current step update amplitude determined for each refinement step is not kept constant throughout the entire refinement process, but is dynamically calculated according to the initial single-step update amplitude and the current refinement step index, following a preset attenuation strategy. The core feature of this attenuation strategy is that the current step update amplitude gradually decreases as the refinement step index increases. The technical considerations behind this design are as follows: In the initial stage of multi-step state transitions, the deviation between the mask boundary shape and the final task-optimal boundary is usually large. At this time, a larger single-step update amplitude helps the mask boundary move quickly towards the task-related region, reducing the total number of steps required to reach convergence. However, as the refinement steps progress, the mask boundary gradually approaches the task-optimal position. If a large update amplitude is continued, the boundary may oscillate repeatedly around the optimal position, failing to converge accurately, or even overshooting the optimal boundary and entering a non-target region due to over-adjustment. By gradually reducing the single-step update amplitude during the refinement process, the mask can make large-scale directional adjustments in the early stages, while performing small-amplitude, high-precision local fine-tuning in the later stages. This effectively avoids boundary oscillation and over-adjustment while ensuring convergence speed. The specific implementation of the preset attenuation strategy can take several forms: for example, linear attenuation, where the current amplitude at each step is equal to the ratio of the initial amplitude multiplied by the total number of steps minus the current step index to the total number of steps; exponential attenuation, where the current amplitude at each step is equal to the initial amplitude multiplied by a certain attenuation factor between 0 and 1 raised to the power of the current step index; cosine annealing or piecewise constant attenuation strategies can also be used. In actual deployment, the selection of the attenuation strategy and the setting of the attenuation rate can be determined as hyperparameters on the validation set through grid search or heuristic tuning to adapt to the differentiated requirements of mask refinement accuracy and speed for different combinations of medical image modalities and different lesion types.

[0186] In step S325, the scaling is performed by updating the amplitude step by step, using the current step's update amplitude.

[0187] When performing the scaling operation by single-step update magnitude in step S325, the fixed initial single-step update magnitude preset in step S31 is no longer used. Instead, the current step update magnitude determined according to the above attenuation strategy is used to scale the restricted correction field. Specifically, in each state transition step, before the restricted correction field is added pixel by pixel to the current soft mask, it needs to be multiplied by the current step update magnitude corresponding to that step. This magnitude value has been attenuated as the thinning step index increases. In the first thinning step, the magnitude value used for scaling is the largest, and the modification of the current soft mask by the restricted correction field is the most significant. In the last thinning step, the magnitude value used for scaling has been attenuated to the minimum, and the modification of the mask is extremely fine, with only minor final calibration performed at the boundary positions. This design, which embeds the attenuation strategy into the single-step update amplitude scaling operation, creates a synergistic effect between amplitude attenuation and the natural convergence process of Markov state transitions. On the one hand, multi-step iterations themselves gradually narrow the range of mask boundary movement, as each update step is confined to the current narrow boundary band. As the boundary gradually stabilizes, the activation range of the active boundary indicator also gradually shrinks. On the other hand, amplitude attenuation further strengthens this convergence trend from the dimension of update step size. Even if the activation range of the boundary indicator has not yet significantly shrunk, the attenuation of single-step amplitude ensures that the adjustment amount in later steps gradually decreases. The combined effect of these two factors makes the convergence process of mask refinement smoother and more stable. It avoids prolonging the convergence time due to excessively small step sizes in the early stages, and also avoids repeated oscillations near the target region due to excessively large step sizes in the later stages. The resulting task-adaptive soft mask achieves higher accuracy and stability in both boundary position and confidence distribution.

[0188] After generating an adaptive soft mask for the task through multi-step differentiable Markov state transitions, the parameters of the mask thinning network need to be trained and optimized to enable it to output spatial cues that are truly beneficial to the downstream generation task. This training process is implemented through the following sub-steps S301 to S306, using the generation quality of the final target modality image as a supervision signal to guide the learning direction of the correction field in each thinning step.

[0189] Specifically, after generating the task-adaptive soft mask for medical cross-modal image synthesis in step S3, the following sub-steps are also included:

[0190] S301: The task-adaptive soft mask and the source modality medical image are input into the diffusion-based medical image generation model to obtain the target modality estimation image, and the denoising task loss is calculated based on the target modality estimation image. The diffusion-based medical image generation model is a neural network model that generates the target modality medical image based on the source modality medical image and the task-adaptive soft mask. The denoising task loss is calculated based on the target modality estimation image and the real target modality image, which is the target modality medical image spatially registered with the source modality medical image.

[0191] First, the task-adaptive soft mask generated in the preceding steps and the source modality medical image are jointly input into the diffusion-based medical image generation model. This model then generates a target modality estimation image based on the anatomical information of the source modality image and the spatial cues provided by the soft mask. The diffusion-based medical image generation model is a neural network model that uses the source modality medical image and the task-adaptive soft mask as joint conditions and the target modality medical image as the generation object. Internally, it typically includes a denoising network based on a U-shaped network structure. During training, it learns the mapping relationship from the source modality to the target modality through forward denoising and backward denoising processes. After obtaining the target modality estimation image, it is compared pixel-by-pixel with the real target modality image to calculate the denoising task loss. The real target modality image is the actually acquired target modality medical image spatially registered with the source modality medical image. For example, in a CT-to-PET generation task, the real target modality image is a PET scan image of the same subject and the same spatial location as the input CT scan. The loss for denoising tasks can be calculated using mean absolute error, mean squared error, or other loss functions suitable for image generation. Its value directly reflects the degree of difference between the target modal image generated under the guidance of the current task adaptive soft mask and the real target modal image. The smaller the difference, the more beneficial the spatial cues provided by the current soft mask are to the generation task.

[0192] As an optional implementation method, the configuration and mask condition injection method of the diffusion-based medical image generation model can be performed as follows:

[0193] The generative model can employ a residual shift-diffusion model. Training is performed at discrete time steps. For the target image Perform forward noise addition or residual shift to obtain ; Noise-reducing U-shaped network receives source image Noisy images Time step embedding and final mask It predicts target images, noise, residuals, or velocity parameterized targets. The task loss can be selected from absolute value loss (L1), squared error loss (L2), smoothing robust loss, or a combination of them with perceptual loss.

[0194] Input-level conditional fusion is a method that integrates inputs along the channel dimension. , and The concatenated images are then input into the first convolutional layer. The cross-attention fusion approach first encodes the mask at multiple scales, then uses image features as queries and mask features as keys and values ​​in several resolution layers of the denoising network, enabling task-adaptive mask and deeply generated features to fully interact. Both approaches can be used individually or in combination.

[0195] In order for the mask to become a true task cue rather than an additional label, training is allowed through Backpropagation is performed to all refinement steps. Training is allowed. through Backpropagation is performed to all refinement steps; when the gradient teacher phase is enabled, the gradients of the corresponding intermediate mask states should be preserved to construct a teacher signal to stop the gradient.

[0196] To ensure the mask serves as a true task cue rather than an additional label, the denoising task loss should be backpropagated through the final refined mask to all refinement steps during training. If memory is limited, gradient checkpointing, truncated backpropagation, or staged pre-training can be used. When enabling the gradient teacher phase, the gradients corresponding to intermediate mask states should be preserved to construct a teacher signal that stops the gradient.

[0197] S302: Calculate the gradient of the soft mask obtained in each step of the multi-step differentiable Markov state transition process in step S3 with respect to the denoising task loss, and perform the gradient stopping operation to obtain the gradient teacher signal corresponding to each refinement step.

[0198] The gradient cessation operation extracts the gradient value of the denoising task loss with respect to the intermediate soft mask as a supervision signal, but truncates the path of this gradient to continue propagating forward along the computation graph, preventing it from further being passed to other parameters of the generative model or upstream networks. The purpose of this is to ensure that the gradient teacher signal serves only as a fixed directional reference, informing the mask refinement network in which direction its output correction field should be adjusted at each step to reduce the final task loss, without interfering with the parameter updates of the generative model itself. This gradient teacher signal is essentially the steepest local descent direction of the task loss in the intermediate mask state space, capturing the optimal adjustment direction information from the current mask state with the goal of reducing the final generation error.

[0199] S303: Calculate the gradient teacher loss based on the gradient teacher signal and the signed correction field output by the mask thinning network in the corresponding step.

[0200] The gradient teacher loss measures the deviation between the actual output correction field of the mask thinning network and the ideal correction direction, indicated by the gradient teacher signal. Specifically, it is calculated by comparing the gradient teacher signal and the signed correction field pixel-by-pixel within the boundary region defined by the active boundary indicator, and obtaining the mean absolute error or mean square error between them. Since the active boundary indicator is only activated within the narrow boundary band, the gradient teacher loss only constrains the correction accuracy of the boundary region; the region outside the boundary is not included in the loss calculation. This design allows the mask thinning network to focus its learning objective highly on the correction quality near the boundary, rather than pixel-by-pixel fitting of the entire mask plane, thereby improving learning efficiency and convergence speed.

[0201] As an optional implementation, the stable training strategy of the graded teacher can be configured as follows:

[0202] In one training iteration, first complete The forward computation of mask thinning and diffusion denoising is performed step by step to obtain the final task loss. Then, for each... Calculate the gradient of the task loss and immediately stop further differentiation of the teacher tensor. When added to the teacher's grade, only Calculate the L1 residual in the active region.

[0203] The stopping gradient teacher signal is used to fix the teacher gradient obtained from the reverse of the final task loss as the supervision target, and to stop further differentiation along the teacher branch. This process enables the gradient teacher to provide only directional supervision, requiring the mask refinement network to output a correction field close to the negative task gradient in the active boundary region, so that the intermediate mask update serves to reduce the target mode generation error, rather than simply replicating the initial mask or regularization term.

[0204] Teacher gradients can be L2 normalized by sample or channel, and the norm can be clipped to a preset interval. When the task gradient is extremely small, the weight of teacher terms can be reduced to avoid numerical noise. For multi-step losses, equal weighting, weighting for later steps, or exponential decay weighting can be used.

[0205] Theoretically, if the task risk J satisfies the smoothness condition L near the refined trajectory, and the residual between the correction field and the negative task gradient is bounded, then a single-step update reduces the task risk to a controllable residual. Under the trajectory-constrained Polyak-Lojasiewicz condition and a bounded correction field, the multi-step task risk difference varies with the time-varying distance. The exponential contraction consists of an initial gap term and a lower bound term for the residuals. Therefore, reducing the gradient teacher residuals tightens the upper bound of task risk. This theory is used to explain the training mechanism and does not require the calculation of the above constants during actual runtime.

[0206] The Polyak-Lojasiewicz condition is a convergence condition in optimization theory, used to explain that gradient descent can achieve risk reduction when certain geometric properties of the function are satisfied; this condition is only used to explain training stability and does not require additional computation during deployment.

[0207] The mathematical definitions of the task loss and gradient teacher signal during the training process are as follows.

[0208] During training, the set of diffusion time steps {1,…, Randomly selected from} Noisy target samples are generated based on the forward process of the adopted generative model. The output of the denoising network U and the sample-level task loss can be expressed as:

[0209]

[0210]

[0211] Generative model parameters with fixed local optimization Write the expected task risk as a description of the mask. function Task-optimal mask under boundary constraints Belongs to feasible set and make Minimum. To enable each step of the correction field to directly learn the direction that reduces the final task loss, this invention constructs a teacher signal for stopping the gradient:

[0212]

[0213] like Figure 5 As shown, Figure 5 Part a in the image represents the source modality image evidence. Figure 5 The b part in the figure represents the current refinement state, and together the two determine the task prompt input near the current boundary; Figure 5 Part c in the diagram shows the residual distribution between the correction field and the stopping gradient teacher signal in the form of a heatmap, indicating that the residual is mainly confined within the boundary region defined by the active boundary indicator, which is used to constrain the output of the mask refinement network to approach the direction that reduces the generation loss. Figure 5 Part d in the figure shows the curves of gradient teacher loss and directional consistency as a function of the number of iterations during the training phase. It indicates that as training progresses, the teacher residual gradually decreases while the direction of the correction field tends to be consistent with the direction of the negative task gradient.

[0214] S304: Calculate the total variation regularization loss and the boundary distance regularization loss, and solve for the auxiliary gradients corresponding to the total variation regularization loss and the boundary distance regularization loss.

[0215] The total variational regularization loss is applied to the final task-adaptive soft mask. By calculating the smoothing norm of the differences between adjacent pixels in each spatial direction, it penalizes sharp fluctuations in local mask regions, thereby suppressing isolated salt-and-pepper noise and jagged boundaries introduced by unstable task gradients and enhancing the spatial continuity of the soft mask. The boundary distance regularization loss utilizes the morphological boundary information of the initial diagnostic guidance mask to construct a spatially weighted penalty term: First, morphological dilation and erosion operations are performed on the initial diagnostic guidance mask, and the difference between the two is calculated to obtain the initial boundary response. Pixels with response values ​​greater than zero constitute the initial boundary set. Then, the Euclidean distance from each pixel to this initial boundary set is calculated, and the distance value is input into a monotonically increasing function controlled by a preset temperature parameter to obtain the boundary distance weight. This weight has a smaller value near the initial boundary, allowing reasonable boundary adjustments driven by the task, and a larger value far from the initial boundary, imposing stronger constraints on large-scale spatial drift. Finally, this weight is multiplied pixel-by-pixel by the deviation of the task-adaptive soft mask from the initial diagnostic guidance mask and summed to obtain the boundary distance regularization loss. After obtaining the total variation regularization loss and the boundary distance regularization loss, the corresponding auxiliary gradients are calculated for the mask refinement network parameters. These two auxiliary gradients will be entered into the subsequent target consistency combination step together with the main task refinement gradient.

[0216] S305: Combine the auxiliary gradient with the main task refinement gradient corresponding to the gradient teacher loss to obtain the combined gradient.

[0217] The core requirement of goal-consistent combination is that the final gradient after combination must not conflict with the optimization direction of the main task refinement gradient; that is, the inner product of the combined gradient and the main task refinement gradient must be no less than zero. To achieve this constraint, firstly, the difference vector between the total variational regularization gradient and the boundary distance regularization gradient is calculated. Then, the inner product of this difference vector and the main task refinement gradient, as well as the inner product of the boundary distance regularization gradient and the main task refinement gradient, are calculated. The feasible interval of the total variational regularization weights is determined based on the signs of the two inner products. Within the feasible interval, the minimum norm solution of the auxiliary gradient combination formed by the total variational regularization weights and the boundary distance regularization weights is solved, and this solution is projected onto the boundary of the feasible interval to obtain the final auxiliary weights. If the feasible interval is empty, it means that any combination of auxiliary gradients in this training batch is contrary to the direction of the main task gradient. In this case, both auxiliary weights are set to zero, and only the main task refinement gradient is retained. Finally, the two auxiliary gradients are weighted and summed using the determined total variation regularization weights and boundary distance regularization weights, and then added to the main task refinement gradient to obtain a combined gradient that incorporates task-oriented supervision and spatial regularization constraints without canceling out the descent direction of the main task. The essence of this mechanism is to automatically determine whether the auxiliary regularization is consistent with the main task direction in each parameter update step. When consistent, it appropriately introduces constraints on smoothness and geometric rationality; when conflicting, it actively avoids conflict, ensuring that the auxiliary regularization always serves rather than opposes the core generative task optimization objective.

[0218] As an alternative implementation, the computation of the spatial regularization term and the engineering implementation of the gradient combination consistent with the objective can be performed as follows:

[0219] The total variation loss is computed on the final mask, and can be achieved using the smoothing norm of finite differences in each direction. Boundary distance weights can be computed before training based on the initial binary mask, or recalculated after each data augmentation. Temperature The larger the value, the wider the boundary buffer that allows for changes; The smaller the value, the faster the penalty for changes far from the initial boundary increases.

[0220] More specifically, the total variation term corresponds to the discrete spatial gradient definition in this invention, and the boundary distance term corresponds to the morphological boundary, boundary set, distance map and distance weight of the initial mask. The two terms respectively constrain local smoothness and spatial drift away from the initial boundary.

[0221]

[0222] The above auxiliary combination expression means that: first, the boundary distance auxiliary gradient is used as the baseline term, and then the total variation weights are adjusted along the direction of the difference between the two auxiliary gradients; therefore, the auxiliary combination should be understood as the following equation:

[0223] Where d is the difference vector between the total variation auxiliary gradient and the boundary distance auxiliary gradient; when the boundary distance weight is 1 minus the total variation weight, the auxiliary combination can be equivalently written as a form that adjusts along the d direction based on the boundary distance auxiliary gradient.

[0224]

[0225] The above closed-form weights should be understood as closed-form weights with consistent objectives: d represents the difference between the two auxiliary gradients, p represents the inner product of d and the main task gradient, and q represents the inner product of the boundary distance auxiliary gradient and the main task gradient; the minimum norm solution without main task constraints is then projected onto the one-dimensional feasible interval determined by p and q.

[0226] Here, p represents the inner product of d and the gradient of the main task, and q represents the inner product of the auxiliary gradient of the boundary distance and the gradient of the main task. If p is greater than 0, the lower bound of the feasible interval is the larger of 0 and negative q divided by p, and the upper bound is 1; if p is less than 0, the lower bound of the feasible interval is 0, and the upper bound is the smaller of 1 and negative q divided by p; if p equals 0 and q is not less than 0, then 0 to 1 is the feasible interval.

[0227] When d is not zero, the projection of the above unconstrained minimum norm weights onto the feasible interval is taken as the total variation weight, and the complementary value is used as the boundary distance weight. When d is zero and the constraints are satisfied, any feasible point is optimal, and equal weights can be used in engineering. When the constraints are not satisfied or the feasible interval is empty, the two types of auxiliary weights are reset to zero, and only the gradient of the main task is used to ensure that the regularization term does not cancel the descent direction of the denoising task.

[0228] The final refined network gradient consists of the main task refined gradient, the weighted total variation auxiliary gradient, and the weighted boundary distance auxiliary gradient. According to the objective consistency constraint, the inner product of this final gradient and the main task gradient must be at least as large as the square norm of the main task gradient itself. Therefore, the auxiliary regularization only enhances smoothness and geometric rationality, without overriding task-oriented supervision.

[0229]

[0230] in, This indicates the parameters used to update the mask refinement network. The final gradient; the above inequality indicates that the auxiliary regular gradient will not cancel out the main task refinement gradient.

[0231] During implementation, it is not necessary to save the complete parameter gradient vector; it can be obtained by accumulating the inner product and square norm layer by layer. L and U are then used to synthesize the inverse gradient with the obtained scalar weights. This method is suitable for large-scale networks and can use floating-point 32-bit cumulative inner product under mixed precision training.

[0232] S306: Update the parameters of the mask thinning network using combined gradients.

[0233] The update operation can be performed using standard stochastic gradient descent or its variant optimizer, and the updated mask refinement network parameters will be used in the next training iteration. Since all parameters of the mask refinement network are fully shared across multiple state transitions, and the main task refinement gradient information in the combined gradient is derived from the sum of the gradient teacher signals of all refinement steps, each parameter update simultaneously incorporates task feedback information from the entire evolution chain from the initial mask to the final soft mask. After sufficient training, the mask refinement network will be able to output a signed correction field in each refinement step that is highly consistent with the direction of reducing the final generation error, given only the initial diagnostic guidance mask and the source modality image, driving the mask to stably evolve from the diagnostic guidance state to the task adaptive state.

[0234] The construction of the spatial regularization term is consistent with the objective, and the closed-form solution process of the auxiliary gradient combination is as follows.

[0235] To suppress local noise and maintain the spatial continuity of the soft mask, a total variation fractal regularization is employed:

[0236]

[0237] To allow for variations close to the original boundary while suppressing drift over long distances, the morphological boundary of each pixel relative to the initial mask is first calculated. Euclidean distance Then construct monotonically increasing weights. .

[0238] The spatial pixel domain is used to define the effective computational range of the finite difference. In 2D slices, the effective pixel set can be formed by removing the last row or column along the height and width directions. In 3D volumetric data, this can be extended to the voxel neighborhood using the same idea. The discrete spatial gradient consists of the differences of the mask in adjacent row and column directions, and is used to measure the local undulations of the final refined soft mask. The role of total variation regularization is not to fix the mask boundaries, but to suppress isolated noise and jagged variations introduced by unstable task gradients.

[0239] Specifically, the spatial pixel domain and discrete spatial gradient in the total variation term can be defined as:

[0240]

[0241] in, and represents the number of pixels in the height and width directions of the mask, respectively; (i,j) represents the pixel coordinates; the discrete spatial gradient consists of the difference in the direction of adjacent rows and the difference in the direction of adjacent columns.

[0242]

[0243] in, Temperature parameters for the boundary tolerance width. Near the original boundary. The weights are relatively small, allowing for task-driven expansion or contraction; the weights are larger far from the original boundary, limiting large-scale distortion. Specifically, the boundary distance regularization first obtains the discrete boundary response based on the morphological gradient of the initial mask; this response can be obtained by subtracting the erosion result from the dilation result of the initial mask. The boundary set consists of pixels or voxels with morphological gradient responses greater than zero, representing the initial foreground-background boundary.

[0244]

[0245] in, This represents the morphological boundary response of the initial mask; Dilate(·) represents the dilation operation; Erode(·) represents the erosion operation; This represents the initial set of boundaries consisting of pixels with non-zero boundary responses.

[0246] For any pixel, the distance map represents the Euclidean distance from that pixel to the initial boundary set; the distance weight increases monotonically with this distance. Therefore, expansion or contraction near the initial boundary is only weakly penalized, while high-confidence regions inside the initial boundary or external background regions far from the initial boundary are more strongly constrained.

[0247]

[0248] in, Let (i,j) represent the Euclidean distance from pixel (i,j) to the initial boundary set; The boundary distance weight is represented by τ, which is a temperature parameter that controls the tolerance width of the boundary.

[0249] The above design ensures that changes near the boundary are considered reasonable boundary corrections that can be driven by the synthesis task, while large-scale drifts far from the boundary are more likely to destroy reliable spatial information in the initial mask. Therefore, the boundary distance regularization handles both outward expansion towards the background and inward contraction towards the foreground simultaneously, without needing to set different losses for expansion and contraction.

[0250] Since the two types of canonical gradients may conflict with each other, or even contradict the task gradient, this invention does not directly add them. Instead, it calculates the minimum norm combination of the auxiliary gradients and adds a linear constraint that does not oppose the main task gradient. Let Or a refined principal gradient obtained from the task chain. , ,but:

[0251]

[0252] When the constraint problem is feasible, the weights can be obtained through one-dimensional closed projection or small-scale quadratic programming; when it is not feasible, the auxiliary weights are reset to zero, retaining only the gradient of the main task. This ensures that while the auxiliary regularization improves smoothness and geometric rationality, it does not cover the descent direction of the main task. The generated model parameters are only based on... renew.

[0253] The closed-form weights are solved based on the objective-consistent auxiliary gradient combination. Let d represent the difference between the total variational auxiliary gradient and the boundary distance auxiliary gradient, p represent the inner product of d and the main task refinement gradient, and q represent the inner product of the boundary distance auxiliary gradient and the main task refinement gradient. Without main task constraints, the one-dimensional projection point corresponding to the minimum norm combination of auxiliary gradients is determined by the inner product of the boundary distance auxiliary gradient and d, and the square norm of d.

[0254]

[0255] Where d represents the difference between the total variational auxiliary gradient and the boundary distance auxiliary gradient; p represents the inner product of this difference vector and the main task refinement gradient; q represents the inner product of the boundary distance auxiliary gradient and the main task refinement gradient. This represents the minimum norm projection point when there is no master task and no adversarial constraints.

[0256] After adding the non-adversarial constraint of the main task, the feasible interval is determined by the signs of p and q: when p is positive, the lower bound is the larger of 0 and negative q divided by p, and the upper bound is 1; when p is negative, the lower bound is 0, and the upper bound is the smaller of 1 and negative q divided by p; when p is zero and q is non-negative, the entire interval from 0 to 1 is feasible. The total variation weights are obtained by truncating the unconstrained projection points to this interval, and the boundary distance weights are their complementary weights.

[0257]

[0258] Where [L,U] represents the feasible interval of the total variation weight under the non-adversarial constraints of the main task; This indicates that the scalar is projected onto the interval. The meanings of all characters in Formulas 1-28 are detailed in Table 1. Furthermore, Figure 2-7 The letters M, E, R, g, α, τ, θ, and φ in the formula symbol table correspond to the mask, boundary indicator, correction field, gradient, weight or step size, temperature parameter, generative model parameter, and refined network parameter, respectively.

[0259] Table 1

[0260]

[0261] If d is zero and q is non-negative, then any convex combination satisfies the constraints, and equal weights can be used as the implementation choice; if q is negative or the feasible interval is empty, then the auxiliary regular gradient is discarded in this batch, and only the main task gradient is retained to update the refined network.

[0262] This method constructs a complete training closed loop with the final generated task quality as the ultimate optimization objective, gradient teachers as intermediate supervision signals, and goal-consistent combination as a multi-objective coordination mechanism. This closed loop incorporates each step of mask refinement into the task-driven learning framework, rather than separating mask refinement from image generation as independent pre- and post-processing stages. This allows the mask evolution process to directly respond to the needs of the downstream generation task, achieving deep coupling between spatial cues and the generation task.

[0263] As an optional implementation, the complete training process for the mask thinning network and the diffusion-based medical image generation model can be performed using the following algorithm:

[0264] Step A1: Initialize the generative model Refine the model optimizer, learning rate scheduler, and hyperparameters , , , , .

[0265] Step A2: Read a batch ( , , This involves performing consistent data enhancement and normalization after registration.

[0266] Step A3: Loop =0 to 1. Calculation , calibration field and Save the intermediate state.

[0267] Step A4: Randomly select diffusion time steps ,generate Perform conditional denoising and calculation .

[0268] Step A5: Calculate the stopping gradient teacher signal for each intermediate mask and and calculate and .

[0269] Step A6: Obtain , and Solve for the objective consistency weights and form ;by , form .

[0270] Step A7: Update separately and It performs gradient cropping, exponential moving average, and learning rate adjustment; and evaluates image quality and task-specific metrics on the validation set.

[0271] Step A8: Repeat until the maximum number of training rounds is reached or the validation metrics no longer improve, then output the optimal checkpoint and corresponding hyperparameters.

[0272] Optionally, fix first The generative model is then trained to have basic image translation capabilities; subsequently, it is frozen or updated with a low learning rate. The network is trained and refined; finally, it is jointly fine-tuned. This phased process can improve the stability of early training, but it does not constitute a necessary limitation.

[0273] In multi-task training, the parameter updates of the mask refinement network need to respond simultaneously to the main supervision signal from the generating task and the auxiliary constraint signal from the spatial regularization term. However, the optimization directions of these two types of signals are not naturally consistent. If they are simply linearly superimposed, the auxiliary regularization gradient may outpace the main task refinement gradient in both value and direction, resulting in a smooth mask but degraded task adaptability. To solve this problem, this invention designs a goal-consistent combination mechanism, that is, the auxiliary gradient can only participate in parameter updates in the half-space that does not oppose the direction of the main task gradient.

[0274] Furthermore, step S305 involves combining the auxiliary gradient with the main task refinement gradient corresponding to the gradient teacher loss in a goal-consistent manner, including the following sub-steps:

[0275] S3051: Using the main task refined gradient, total variation regularized gradient, and boundary distance regularized gradient as inputs, calculate the difference vector between the total variation regularized gradient and the boundary distance regularized gradient.

[0276] The difference vector characterizes the relative geometric relationship between the two auxiliary gradients in the parameter space. Any convex combination of the two auxiliary gradients can be represented as the position reached by moving a certain step along the direction of the difference vector, with one of the auxiliary gradients as the reference. By introducing the difference vector, the problem of searching for the optimal combination of two auxiliary weights in a two-dimensional plane is transformed into a one-dimensional search problem along the direction of the difference vector, significantly reducing the solution complexity. In specific calculations, obtaining the difference vector only involves element-wise vector subtraction, and its computational cost is far lower than performing multi-objective quadratic programming in the parameter space.

[0277] S3052: Calculate the inner product of the difference vector and the main task refinement gradient, as well as the inner product of the boundary distance regularization gradient and the main task refinement gradient.

[0278] The sign and magnitude of the inner product have clear geometric meanings in gradient space: if the inner product of an auxiliary gradient and the main task's refinement gradient is positive, it indicates that the update direction of the auxiliary gradient has a positive projection component with the descent direction of the main task. Updating parameters along this direction will at least not harm the loss of the main task, and may even accelerate convergence; if the inner product is negative, it indicates that the direction of the auxiliary gradient is opposite to the descent direction of the main task. If it is included in the update without constraint, it will offset the optimization effect of the main task to some extent. By calculating these two inner products, sub-step S3052 provides the necessary geometric criteria for determining the subsequent feasible interval.

[0279] S3053: Determine the feasible interval of the total variational regularization weights based on the two inner products.

[0280] The determination of the feasible interval follows the non-adversarial principle, which requires that the inner product of the auxiliary combined gradient obtained by combining the total variational regularized gradient and the boundary distance regularized gradient with arbitrary weights, and the main task refinement gradient, is not less than zero. Based on the sign relationship between the difference vector and the inner product of the boundary distance regularized gradient and the main task gradient, the effective range of values ​​for the total variational regularized weight can be divided into several cases: when the inner product of the difference vector and the main task gradient is greater than zero, the total variational weight can take a larger value in the interval from zero to one, and its upper bound is determined by the ratio of the inner product of the boundary distance regularized gradient and the main task gradient to the inner product of the difference vector; when the inner product of the difference vector and the main task gradient is less than zero, the upper bound of the total variational weight is limited, and the range of values ​​is compressed to a narrower interval; when the inner product of the difference vector and the main task gradient is zero and the inner product of the boundary distance regularized gradient and the main task gradient is non-negative, the entire interval from zero to one for the total variational weight is a feasible interval. The determination of this feasible interval is entirely adaptively determined by the geometric relationship between gradients, without the need to manually set any thresholds or weight limits, thus exhibiting good task adaptability.

[0281] S3054: Solve for the minimum norm solution of the auxiliary gradient combination formed by the total variation regular weight and the boundary distance regular weight, and project it into the feasible interval to obtain the final auxiliary weight.

[0282] The minimum norm solution for the auxiliary gradient combination refers to selecting the weight configuration that minimizes the Euclidean or square norm of the combined auxiliary gradient among all feasible weight combinations satisfying the non-adversarial constraints. The rationale for choosing the minimum norm solution lies in introducing the smallest possible auxiliary correction amount while ensuring that the auxiliary gradient does not compromise the optimization of the main task. This minimizes the perturbation by incorporating the smoothness and geometric rationality constraints of space regularization, preventing the auxiliary gradient from overly dominating the parameter update direction. In the solution process, the theoretically optimal weight that minimizes the norm of the auxiliary gradient combination is first calculated under unconstrained conditions. This theoretically optimal weight can be analytically expressed as a function of the inner product of the boundary distance regularization gradient and the difference vector. Then, this theoretically optimal weight is projected onto the feasible interval determined in sub-step S3053. If the theoretically optimal weight is within the feasible interval, it is directly adopted; if it is to the left of the feasible interval, the lower bound of the interval is taken; and if it is to the right of the interval, the upper bound of the interval is taken. This closed-form solution and projection operation avoids the high computational cost of performing iterative optimization or quadratic programming in the parameter space, enabling the goal-consistent combination mechanism to be executed efficiently in each training batch without significantly increasing training time.

[0283] S3055: If the feasible interval is empty, then reset the final auxiliary weight to zero.

[0284] When, according to the judgment in sub-step S3053, no total variation regularization weights can make the inner product of the auxiliary combination gradient and the main task refinement gradient non-negative, the feasible interval is empty. This means that in the current training batch, regardless of the ratio of the total variation regularization gradient and the boundary distance regularization gradient, they will, to some extent, offset the descent direction of the main task. At this time, sub-step S3055 sets both the total variation regularization weights and the boundary distance regularization weights to zero, which is equivalent to completely discarding the auxiliary regularization gradient in the parameter update of this batch, and only retaining the main task refinement gradient for updating the parameters of the mask refinement network. This automatic backoff mechanism is a key safety guarantee for the goal-consistent combination strategy: it ensures that the auxiliary regularization will not cover or weaken the optimization direction of the main task under any circumstances, and can maintain the correct convergence direction of training even in extreme cases such as large task gradient noise and unstable auxiliary gradient direction in the early stage of training.

[0285] S3056: The total variational regularized gradient and the boundary distance regularized gradient are weighted and summed using the final auxiliary weights, and then added to the main task refinement gradient to obtain the combined gradient.

[0286] Using the final auxiliary weights determined in sub-steps S3054 or S3055, the total variational regularization gradient and the boundary distance regularization gradient are weighted and summed to obtain a weighted auxiliary gradient. This weighted auxiliary gradient is then element-wise added to the main task refinement gradient to form the final combined gradient used for parameter updates. This combined gradient incorporates information from three sources: the task-oriented update direction from the gradient teacher loss, the local smoothing constraint from the total variational regularization, and the spatial drift suppression constraint from the boundary distance regularization. The weights among these three sources are automatically adjusted by the goal consistency constraint, ensuring that the contribution of the auxiliary regularization always belongs to, rather than opposes, the main task optimization objective. Finally, this combined gradient is fed into the optimizer to complete one-step updates of the mask refinement network parameters.

[0287] like Figure 6 As shown, the blue arrows represent the main task refined gradients from the generation task or gradient teacher chain; the cyan and purple arrows represent the total variational regularized gradient and the boundary distance regularized gradient, respectively; the red arrows represent the combined auxiliary gradients after solving for the objective consistency constraint; and the light-colored filled area represents the feasible half-space where the inner product with the main task direction is non-negative. This geometric relationship illustrates that the auxiliary regularized gradients are only included in parameter updates when their combined direction does not cancel the descent direction of the main task. When the feasible interval is empty, the auxiliary weights are automatically set to zero, and only the main task refined gradients are retained.

[0288] This invention addresses the orientation conflict problem in multi-objective optimization in real time by using closed projection in gradient space, providing a mechanism to ensure stable training and task adaptability of mask refinement networks.

[0289] Further, step S304 calculates the boundary distance regularization loss, including the following sub-steps:

[0290] Step S3041: Perform morphological dilation and morphological erosion operations on the initial diagnostic guidance mask, and calculate the difference between the two to obtain the initial boundary response.

[0291] The initial diagnostic guidance mask is a binary or continuous value mask obtained in step S1, either manually labeled or automatically segmented. It reflects the boundary location of the lesion region that the doctor focuses on during diagnosis or segmentation, carrying important prior anatomical knowledge and clinical interpretation experience. By performing morphological dilation and erosion operations on this initial mask, a dilated mask and an eroded mask are obtained. The difference between the two is the initial boundary response. This response has a larger value at the boundary between the foreground and background of the initial mask, and its value approaches zero in the flat foreground region and the background region far from the boundary, thus accurately capturing the boundary location information of the initial diagnostic guidance mask. This boundary location information is the core basis for the geometric description of the initial mask, and subsequent steps will construct a spatially adaptive weighting system around this boundary location.

[0292] Step S3042: Construct an initial boundary set from the pixels that are greater than zero in the initial boundary response.

[0293] The boundary set is essentially a set of spatial coordinates containing all pixel positions located on the boundary of the initial diagnostic guidance mask. In the case of a binary mask, the boundary set encompasses all pixels traversed by the boundary line between the foreground and background; in the case of a continuous soft mask, the boundary set includes all transition region pixels with an initial boundary response greater than zero. This boundary set serves as the spatial reference for the entire boundary distance regularization loss, and the constraint strength of each subsequent pixel is determined by its distance from this boundary set. The construction of the boundary set is a one-time operation, calculated based on the initial diagnostic guidance mask before training begins and remaining unchanged throughout the training process. It does not need to be recalculated in each iteration, thus minimizing computational overhead.

[0294] Step S3043: Calculate the Euclidean distance from each pixel to the initial boundary set to obtain the distance map.

[0295] The distance map is a two-dimensional or three-dimensional matrix with the same spatial dimensions as the input image, where each location stores the geometric distance of that pixel to the nearest boundary point in the initial boundary set. Boundary points located inside the initial boundary set have a distance value of zero; pixels located in the vicinity of the boundary have smaller distance values, which increase linearly with the degree of deviation from the boundary; pixels located deep inside the foreground or far from the background have larger distance values, reflecting the significant spatial deviation of these pixels from the initial boundary. Euclidean distance can be calculated in the two-dimensional plane along the height and width directions respectively, or extended to the depth direction in three-dimensional volume data. Its computational complexity is linearly related to the image resolution and can be efficiently implemented using distance transformation algorithms. The distance map serves as a spatial reference for boundary distance regularization, precisely correlated with the penalty intensity of each pixel and its geometric distance to the initial boundary set.

[0296] Step S3044: Input the distance map into a monotonically increasing function controlled by a preset temperature parameter to obtain the boundary distance weights.

[0297] The output value of this monotonically increasing function increases monotonically with the increase of the input distance value, and its growth rate is controlled by a preset temperature parameter. The essential function of the temperature parameter is to control the boundary tolerance width: when the temperature parameter value is large, the function growth is relatively gentle, the weight values ​​corresponding to pixels near the initial boundary are low, and the weight growth remains moderate within a wide buffer region; when the temperature parameter value is small, the function growth is relatively steep, and the weights rise rapidly with increasing distance. In practical applications, this monotonically increasing function can adopt an exponential function, a square function, or other function forms that satisfy the monotonically increasing property. The boundary distance weight output value from the function is small near the initial boundary, allowing the mask to perform task-driven expansion or contraction adjustments within this region without significant penalty; as the pixel position gradually moves away from the initial boundary, the weight value increases monotonically, gradually strengthening the constraint on mask changes, forming strong constraints in the high-confidence region inside the boundary and the external background region, effectively suppressing large-scale spatial drift. This spatially adaptive weighted strategy handles both outward expansion to the background and inward contraction of the foreground boundary changes simultaneously, without requiring separate loss functions for expansion and contraction, and has a concise and unified form.

[0298] like Figure 3 As shown in part f, the boundary distance weights are lower near the initial diagnostic guide mask boundary, allowing for task-driven local boundary correction; and higher weights are applied in the foreground interior and background exterior regions far from the initial boundary, effectively suppressing large-scale spatial drift.

[0299] Step S3045: Multiply the boundary distance weights pixel by pixel by the deviation of the task adaptive soft mask relative to the initial diagnostic guide mask and sum them to obtain the boundary distance regularization loss.

[0300] The bias is calculated by subtracting the task-adaptive soft mask generated through multiple differentiable Markov state transitions from the initial diagnostic guidance mask at each pixel location. The absolute or squared value of the difference is taken as the bias for that pixel. The bias reflects the degree of change of the refined mask relative to the initial diagnostic guidance mask at that pixel location; a larger bias indicates that the location deviates further from the initial diagnostic annotation. Multiplying the boundary distance weights by this bias for each pixel is equivalent to spatially differentiating the bias for each pixel: in regions near the initial boundary, the weights are smaller, so even if the mask changes significantly in these regions, its contribution to the boundary distance regularization loss is relatively limited; in regions far from the initial boundary, the weights are larger, so even small shifts are amplified and have a larger penalty contribution. Summing the weighted biases of each pixel yields the scalar value of the boundary distance regularization loss for the entire mask. This loss term constrains the mask refinement network during training through backpropagation, encouraging the network to make task-driven adaptive adjustments near the boundary while suppressing invalid drifts that do not conform to clinical priors in regions far from the initial boundary.

[0301] Boundary distance regularization loss provides a spatial constraint framework based on the initial diagnostic boundary for the mask refinement process. This framework constructs a differentiated penalty weight system related to pixel position through a distance map, rather than applying a uniform constraint intensity to the entire mask plane. This effectively limits large-scale drift while reasonably adjusting degrees of freedom near the boundary. Boundary distance regularization complements total variation regularization: total variation regularization mainly suppresses mask noise fluctuations and jagged boundaries from the perspective of local gradients, while boundary distance regularization constrains the mask boundary from a global geometric perspective to prevent it from deviating significantly from the spatial position of the initial diagnostic annotation. Both are coordinated with the main task refinement gradient through a subsequent goal-consistent combination mechanism, jointly ensuring the stable convergence and output quality of the mask refinement network during training.

[0302] Further, in step S301, the task-adaptive soft mask and the source modality medical image are jointly input into the diffusion-based medical image generation model, including the following sub-steps:

[0303] Step S30111: Perform multi-scale encoding on the task-adaptive soft mask to obtain multi-scale mask features.

[0304] A task-adaptive soft mask is a two-dimensional or three-dimensional matrix with the same spatial dimensions as the source modality image. The continuous value of each pixel represents the confidence that the location belongs to a task-related region. Since mask conditions need to be injected into multiple resolution layers of the denoising network, and the feature maps of these resolution layers have different spatial dimensions, downsampling from the original resolution to fractions or even tens of fractions of the original size, multi-scale encoding of the mask is necessary to ensure strict spatial matching with the feature maps of each target resolution layer. The multi-scale encoding can be implemented using a lightweight encoding network that corresponds to the encoder structure of the denoising network, or by directly using intermediate features from different stages of the denoising network's encoding path as the multi-scale representation of the mask. Alternatively, it can be achieved by progressively downsampling the mask at the original resolution, corresponding one-to-one with the downsampling factor of each resolution layer in the denoising network, generating a hierarchical mask feature pyramid. Regardless of the implementation method, the core requirement of multi-scale encoding is to ensure that each target resolution layer has a mask feature map with the same spatial dimensions and matching semantic information, providing structured conditional input for subsequent cross-attention computation.

[0305] Step S30112: In the denoising network of the diffusion-based medical image generation model, select multiple resolution layers. On each selected resolution layer, use the image features of that layer as the query and the mask features corresponding to that layer as the key and value, and perform cross-attention calculation to obtain the mask conditional enhancement features of that layer.

[0306] The three input roles in cross-attention computation are assigned as follows: the original image features of the resolution layer are used as the query, and the corresponding mask features are used as the key and value. This role assignment is designed to allow the image features to act as the active inquirer, requesting the mask features to identify "which spatial locations require priority attention during the denoising stage of the current generation task." The mask features simultaneously act as both key and value, generating an attention weight distribution map based on the similarity between the key and the query. Then, the values ​​are weighted and aggregated according to the attention weights, selectively transferring task-related spatial information from the mask to the image features. The specific process of cross-attention computation is as follows: first, the query, key, and value are mapped to the embedding space using a learnable linear projection matrix; then, the dot product of the query and the transpose of the key is calculated and scaled and normalized using Softmax to obtain the attention weight matrix; finally, the attention weight matrix is ​​multiplied by the values ​​to obtain the mask conditional enhancement features for that resolution layer. This computational mechanism enables the network to dynamically determine how much spatial bias information from the mask to introduce at each spatial location based on the semantic matching degree between image features and mask features: where the image features and the task-related regions indicated by the mask highly overlap, the attention weight is larger, and the spatial cue information in the mask features is fully injected into the image features; where the image features and mask information are unrelated or weakly related, the attention weight is smaller, and the image features are basically preserved in their original form, thus achieving adaptive and non-uniform utilization of mask conditions.

[0307] Step S30113: Fuse the mask condition enhancement features of each selected resolution layer with the original image features of the corresponding layer to obtain the fused features used for denoising prediction.

[0308] The fusion operation can be performed using element-wise addition, channel-dimensional concatenation followed by a lightweight convolutional layer for information integration, or a learnable gating fusion mechanism. Element-wise addition is the simplest fusion method, treating the enhanced features as residual corrections to the original features, preserving the baseline information of the original features while superimposing the modulation signal of the mask conditions. Channel-dimensional concatenation followed by convolutional fusion gives the network greater flexibility to learn the interaction between the two features, especially suitable for situations where there are significant differences between mask features and image features at the semantic level. The fused features replace the original image features of that resolution layer and continue to participate in the computation in subsequent layers of the denoising network. Since the mask conditions are injected and fused separately at multiple resolution layers, rather than having a one-time effect only at the input layer, the spatial cue information of the task-adaptive soft mask can continue to play a role in the shallow encoding stage, the mid-level feature abstraction stage, and the deep semantic understanding stage of the denoising network. This allows the final generated target modality image to more accurately respond to the guidance of spatial cues in multiple aspects, such as the metabolic intensity distribution in the lesion area, tissue contrast performance, and preservation of anatomical structure. Compared to the input-level concatenation method, the cross-attention multi-resolution injection mechanism improves the depth and fineness of the task-adaptive soft mask's control over the generation process at the network architecture level, and is an important extension of this scheme in terms of spatial condition injection methods.

[0309] When introducing task-adaptive soft masks as spatial conditions into a diffusion-based medical image generation model, the simple channel-dimensional stitching method, while convenient, only fuses the mask and source modality image once at the input layer. The spatial cues provided by the mask may gradually become diluted as the denoising network deepens, making it difficult to sustain its guiding role in the network's deeper feature representations. To enhance the depth and accuracy of mask conditions in regulating the generation process, sub-steps S30111 to S30113 employ a cross-attention fusion mechanism, injecting the conditional information of the task-adaptive soft mask into multiple resolution levels of the denoising network. This transforms the mask from an additional channel in the input layer into a feature-level guiding signal that permeates multiple depths of the network.

[0310] In medical cross-modal image generation tasks, common image quality evaluation metrics such as mean absolute error or mean squared error typically calculate the prediction bias of each pixel uniformly across the entire image plane, failing to distinguish the differences in the importance of different spatial regions in clinical diagnosis. Taking CT to PET generation as an example, when evaluating the quality of generated PET images, clinicians are most concerned with whether the metabolic intensity within the tumor region is accurately reproduced, rather than the pixel accuracy of background air regions or normal tissue regions. To enable the task loss function to more directly reflect the generation quality of clinically relevant regions, the mean error of the standard uptake value of the tumor region is introduced as a task-specific regularization term or supplementary loss term on top of the basic loss function.

[0311] Further, step S301 calculates the denoising task loss between the estimated target modality image and the true target modality image, including the following sub-steps:

[0312] Step S30121a: Map the target modality estimation image and the real target modality image to the standard access value space through the standard access value transformation function to obtain the estimated standard access value map and the real standard access value map. The standard access value transformation function is used to convert the image intensity into standard access values.

[0313] Standardized uptake (SUP) is a widely used semi-quantitative indicator in PET imaging. It is typically calculated by dividing the radioactivity concentration of each voxel in the image by the ratio of the injection dose to body weight, thus eliminating inconsistencies in image intensity scale caused by differences in injection dose and body weight among different subjects. The role of the SUP transformation function is to map the image intensity values ​​output by the generative model to this clinically comparable standardized space. Through this mapping, the PET image intensities of different subjects and different scanning batches have uniform dimensions and numerical ranges, making the error indices calculated subsequently comparable and summable across different samples. For other target modalities, corresponding standardized transformation functions can also be used; for example, Z-score standardization or histogram matching standardization can be performed on MRI images to achieve similar scale normalization effects.

[0314] Step S30122a: Determine the set of voxels in the tumor region using the initial diagnostic guidance mask. The set of voxels in the tumor region is the set of foreground pixels in the initial diagnostic guidance mask.

[0315] The set of voxels representing the tumor region is composed of the spatial coordinates of all foreground pixels in the initial diagnostic guidance mask. Foreground pixels are those pixels in the mask with a value of 1 or those in the continuous value mask with a value higher than a certain threshold. The initial diagnostic guidance mask is a lesion region identifier generated by physician annotation or an automatic segmentation algorithm; the pixel locations it contains are confirmed as the lesion location in clinical diagnosis. In CT-to-PET conversion scenarios, this mask represents the outline of the lesion visible on the CT image; in MRI multi-sequence conversion scenarios, this mask may be obtained by merging sub-regions such as enhanced tumor, peritumoral edema, and necrotic core. The set of voxels representing the tumor region determined by this mask focuses subsequent error calculations from the entire image plane to the most clinically critical lesion region, eliminating the dilution effect of a large number of irrelevant background and normal tissue areas on the loss function value.

[0316] Step S30123a: Within the voxel set of the tumor region, calculate the mean absolute error between the estimated standard uptake map and the true standard uptake map to obtain the mean error of the standard uptake value.

[0317] The error is calculated by summing and averaging across voxels within the tumor region. Its value directly reflects the accuracy of the generative model in reproducing metabolic intensity in the lesion area: a smaller average error in the standard uptake values ​​indicates that the distribution of standard uptake values ​​in the generated PET image within the tumor region is closer to the real PET image, and the higher the usability of the generated results in clinical metabolic assessment. Conversely, a larger error means that even if the overall image structure is similar, the metabolic intensity in the core tumor region may deviate significantly, potentially affecting subsequent quantitative analysis and diagnostic decisions. By introducing this regionalized and standardized error term into the loss function, the optimization direction of the generative model is not only driven by global pixel accuracy but also directly constrained by the accuracy of metabolic intensity in the tumor region.

[0318] Step S30124a: The average error of the standard intake value is weighted and summed with the preset base loss function to obtain the denoising task loss. The preset base loss function is the average absolute error between the target modality estimation image and the real target modality image.

[0319] The preset base loss function typically uses the average absolute error between the estimated target modality image and the real target modality image across the entire image plane. This base loss is responsible for maintaining the structural similarity and pixel fidelity of the generated image globally, ensuring that the anatomical structure in non-lesion areas is not distorted or artifacts are generated. The average error of standard uptake values ​​serves as a task-specific supplementary loss term, combined with the base loss through preset weighting coefficients. These weighting coefficients control the relative importance of metabolic accuracy in the overall optimization objective of the tumor region: when the weighting coefficient is set higher, the training process will focus more on improving the accuracy of standard uptake values ​​in the tumor region, but may sacrifice pixel fidelity in the background region to some extent; when the weighting coefficient is set lower, the constraint on metabolic accuracy in the tumor region is relatively weakened. In actual deployment, these weighting coefficients can be adjusted as hyperparameters on the validation set according to the comprehensive quality index of the generated images. Through this weighted summation mechanism, the denoising task loss simultaneously considers two optimization dimensions: global image quality and local clinical accuracy. This allows the trained diffusion-based medical image generation model to generate PET images with metabolic intensity closer to the real value in the tumor lesion area, while maintaining the integrity and accuracy of the overall anatomical structure. Embedding clinical prior knowledge into the loss function in a quantifiable form is a further task-specific optimization of the generated task by the task-adaptive soft mask in the dimension of loss function, in addition to the spatial cue dimension.

[0320] In medical cross-modal image generation tasks, different imaging modalities exhibit fundamentally different display characteristics of lesion regions. Unlike PET images where the metabolic intensity of tumor regions can be standardized and quantified using standard uptake values, the signal intensity of different sequences in magnetic resonance imaging (MRI) is affected by various factors such as scanning parameters, field strength, and coil sensitivity, lacking a unified absolute quantification standard. Clinical interpretation of image intensity relies more on relative contrast between tissues than on absolute values. Therefore, in cross-modal generation tasks between T1-weighted MRI and T1CE or FLAIR MRI sequences, the assessment of tumor region generation quality requires a metric different from the standard uptake value error. By introducing the average pixel error of the tumor region onto the basic loss function, a task-specific loss term suitable for this modality is provided for multi-sequence MRI generation tasks.

[0321] Further, step S301 calculates the denoising task loss between the estimated target modality image and the true target modality image, including the following sub-steps:

[0322] Step S30121b: Determine the set of voxels in the tumor region using the initial diagnostic guidance mask. The set of voxels in the tumor region is the set of foreground pixels in the initial diagnostic guidance mask.

[0323] In multi-sequence MRI generation applications, the initial diagnostic guidance mask is typically obtained by merging annotations of various tumor subregions, such as enhanced tumor, peritumoral edema, and necrotic core. Therefore, its foreground pixel set covers the complete tumor region of clinical interest, including the main tumor area and surrounding tissue areas potentially affected by edema. This set is defined so that subsequent error calculations delineate clinically critical areas, allowing the loss function to exert targeted supervision on the generation quality of lesion-related areas, distinct from the background area. This prevents pixel errors in large areas of normal tissue from dominating the loss function and masking generation quality issues in the tumor area.

[0324] Step S30122b: Within the voxel set of the tumor region, calculate the pixel-wise absolute intensity difference between the estimated target modality image and the true target modality image.

[0325] This operation uses individual pixels as the unit of calculation, calculating the absolute value of the difference between the intensity values ​​of the generated image and the real image at each pixel location within the tumor region. This forms an error value set the same size as the voxel set of the tumor region. The pixel-by-pixel absolute intensity difference directly reflects the accuracy of the generative model in reproducing tissue signal intensity at each local location within the lesion region. Its spatial distribution contains rich error structure information: if the error is concentrated in a large area at the tumor edge, it indicates that the generative model does not adequately reproduce the contrast transition of the tumor boundary; if the error is uniformly distributed within the tumor, it may suggest that the generative model's ability to model the heterogeneity of tissues within the tumor needs improvement.

[0326] Step S30123b: Average the absolute intensity difference of each pixel within the voxel set of the tumor region to obtain the average pixel error.

[0327] This scalar value serves as a concise aggregate metric, summarizing the overall signal intensity reproduction level of the generative model within the tumor region. Unlike the average error of the standard uptake value, which depends on specific tracer kinetics normalization, the pixel average error is calculated directly based on the intensity of the original image and does not depend on any modality-specific normalization transformation function. Therefore, it is applicable to various non-quantitative imaging modalities such as magnetic resonance imaging. The smaller the pixel average error, the closer the signal intensity distribution of the generated target modality image within the tumor region is to the corresponding sequence image acquired in reality, and the higher the clinical usability and diagnostic reference value of the generated result in that region.

[0328] Step S30124b: The pixel average error is weighted and summed with the preset base loss function to obtain the denoising task loss. The preset base loss function is the average absolute error between the target modality estimation image and the real target modality image.

[0329] The preset base loss function is the average absolute error between the estimated target modality image and the real target modality image across the entire image plane. This base loss maintains the structural consistency and overall signal distribution authenticity of the generated image globally, ensuring that the signal features of normal brain tissue, ventricles, white matter, and gray matter outside the tumor region are also accurately generated. The pixel average error, as a task-specific supplementary loss term, is combined with the base loss using preset weighting coefficients. These weighting coefficients control the proportion of tumor region generation accuracy in the overall optimization objective. In actual training, this coefficient can be flexibly adjusted according to the accuracy requirements of different generation tasks: for generation tasks primarily aimed at assisting in tumor diagnosis or treatment assessment, a higher weighting coefficient can be set to strengthen the constraints on tumor region generation quality; for tasks primarily aimed at whole-brain structural completion or general image quality improvement, the weighting coefficient can be appropriately reduced to achieve a balance between tumor region accuracy and global structural consistency. Through this weighted summation mechanism, the denoising task loss enhances the supervision of local signal intensity in the tumor region while maintaining global pixel fidelity, enabling the trained model to more accurately reproduce the tissue contrast features of the target modality in the lesion region.

[0330] In this invention, the pixel average error and the aforementioned standard uptake value average error are applicable to different imaging modalities and application scenarios, respectively. Together, they constitute a complementary strategy for task-specific optimization of multimodal medical image generation at the loss function level: for quantitative imaging modalities such as PET, the standard uptake value average error is used to constrain the generation quality from the perspective of metabolic quantification accuracy; for imaging modalities such as MRI that emphasize tissue contrast, the pixel average error is used to constrain the generation quality from the perspective of signal intensity reproduction. This complementary design allows the spatial cueing function of the task-adaptive soft mask and the task-specific loss function supervision to work synergistically during training, jointly improving the task adaptability of cross-modal medical image generation from two dimensions: spatial condition guidance and optimization of target constraints.

[0331] In this invention, a mask refinement network and a diffusion-based medical image generation model constitute a dual-network collaborative architecture. The mask refinement network is responsible for transforming the initial diagnostic guidance mask into a task-adaptive soft mask, while the diffusion-based medical image generation model generates the target modality image based on this soft mask and the source modality image. These two networks are functionally interdependent but differ significantly in their training objectives: the generation model needs to learn the cross-modal mapping relationship from the source modality to the target modality, while the mask refinement network needs to learn how to adjust the mask boundaries to reduce the final generation error. If the two networks are jointly optimized end-to-end from the beginning of training, the task loss gradient received by the mask refinement network in the early stages, before the generation model has basic image translation capabilities, is often noisy and directionally unstable. This may lead to slow convergence or getting stuck in local optima, or even negatively interfering with the learning process of the generation model. To address this stability issue of coupled dual-network training, a three-stage progressive training strategy is adopted. By decoupling the training sequence of the two networks, different optimization objectives are focused on at different stages, ultimately achieving collaborative convergence of both.

[0332] Specifically, the training of the mask refinement network and the diffusion-based medical image generation model is performed sequentially in the following stages:

[0333] Phase 1: Fix the parameters of the mask refinement network, and train the diffusion medical image generation model using only the source modality medical images and the initial diagnostic guidance mask until the diffusion medical image generation model meets the first preset convergence condition.

[0334] The so-called fixed mask refinement network parameters mean that in this stage, the mask refinement network does not participate in any forward computation or backpropagation. The conditional input of the generative model directly uses the unrefined initial diagnostic guidance mask, or the refinement network parameters are initialized to random values ​​and then directly output an untrained task-adaptive soft mask. The core objective of this stage is to enable the generative model to first establish a basic mapping capability from the source modality to the target modality, that is, given a source modality image and an initial spatial cue, it can generate an image that is relatively close to the target modality in terms of anatomical structure and overall signal distribution. During training, the parameters of the generative model are updated through backpropagation of the denoising task loss, while the mask refinement network remains frozen. The termination condition for the first stage of training is that the diffusion-based medical image generation model meets the first preset convergence condition. This condition can be achieved by the peak signal-to-noise ratio or structural similarity index of the generated image on the validation set reaching a preset threshold, or by the training loss no longer significantly decreasing in several consecutive iterations. Once the generative model possesses a certain level of basic image translation capability, the error between its output target modality estimation image and the real target modality image is no longer dominated by the insufficient capability of the generative model itself, but begins to reflect the deviation between the initial diagnostic guidance mask and the task optimal space cues. At this point, the second stage can begin.

[0335] Second stage: Fix the parameters of the diffusion-type medical image generation model, or set its learning rate to be lower than the first preset threshold, and execute steps S301 to S306 to train the mask thinning network until the mask thinning network meets the second preset convergence condition.

[0336] The generative model parameters are frozen or fine-tuned only with a very low learning rate to provide a relatively stable and reliable task loss feedback environment for the training of the mask refinement network. At this point, the generative model has basic cross-modal generation capabilities, and the quality of its output target modality estimation image is limited to some extent by the quality of the input spatial cues. The mask refinement network generates a task-adaptive soft mask through multi-step differentiable Markov state transitions. This soft mask replaces the initial diagnostic guidance mask in the first stage as the spatial conditional input of the generative model. The generative model outputs the target modality estimation image and calculates the denoising task loss accordingly. Then, through a gradient teacher mechanism and a combination of auxiliary regularization and target consistency, the task loss is fed back to the parameter update process of the mask refinement network. Since the generative model is in a frozen or very low learning rate state at this time, the change in task loss is mainly caused by the adjustment of spatial cues by the mask refinement network, rather than by the fluctuation of the generative model's own parameters. Therefore, the mask refinement network can optimize on a relatively stable error landscape and quickly learn mask adjustment strategies that can reduce the final generation error. The second stage of training terminates when the mask refinement network meets the second preset convergence condition. This can be achieved by the gradient teacher loss no longer decreasing significantly on the validation set, or by the mask evolution trajectory changing less than a preset threshold over multiple consecutive steps. Once the mask refinement network has learned to stably output spatial cues beneficial to the generation task under the given initial diagnostic guidance mask, it can proceed to the third stage.

[0337] The third stage involves simultaneously updating the parameters of the mask refinement network and the diffusion-based medical image generation model with a non-zero learning rate, performing joint fine-tuning until the third preset convergence condition is met.

[0338] This stage removes restrictions on parameter updates for both networks, allowing the generative model to further adjust its parameters based on refined spatial cues to adapt to more precise task conditions. Simultaneously, the mask refinement network continues to optimize its mask adjustment strategy based on the new error landscape resulting from changes in the generative model's parameters. The two networks collaborate in this stage: the generative model gradually adapts to the spatial characteristics of the task-adaptive soft mask provided by the mask refinement network, while the mask refinement network further fine-tunes the boundary correction direction and magnitude based on the increasingly refined error feedback from the generative model. Since the first two stages have established good initial convergence points for both networks, the joint fine-tuning in the third stage only requires minor adjustments based on the existing foundation, avoiding training oscillations and convergence difficulties that might occur with direct end-to-end joint training from random initialization. The termination condition for the third stage training is the simultaneous fulfillment of a third preset convergence condition, which can be achieved by both the generative task loss and the gradient teacher loss stabilizing on the validation set, or by reaching the preset maximum number of training epochs.

[0339] Through the three-stage progressive training process described above, the mask refinement network and the diffusion-based medical image generation model are assigned different optimization priorities at different stages: the first stage allows the generation model to learn basic cross-modal translation without needing to focus on mask quality; the second stage allows the mask refinement network to focus on learning task-driven boundary adjustment strategies under the condition of stable feedback from the generation model; and the third stage allows the two networks to be collaboratively fine-tuned based on their initial convergence. This staged training strategy effectively decouples the mutual interference between the two networks in the early stages of training, making the entire dual-network architecture training process more stable and efficient. The resulting mask refinement network and generation model can work collaboratively during the inference stage, transforming the input initial diagnostic guidance mask and source modality medical image into the target modality medical image with high quality.

[0340] After calculating the gradient teacher signal corresponding to each refinement step in sub-step S302, this signal is directly used to supervise the signed correction field output by the mask refinement network in the corresponding step. However, the gradient teacher signal originates from the backpropagation of the denoising task loss to the intermediate soft mask, and its magnitude is affected by various factors, including the difficulty of the samples in the current training batch, the specific value of the denoising task loss function, the random selection of the sampling time step of the diffusion model, and the cumulative scaling effect of gradient propagation in the multi-step refinement chain. These factors may cause large fluctuations in the magnitude of the gradient teacher signal between different refinement steps and between different training batches. If gradient teacher signals with significantly different amplitudes are directly used as the supervision target, the mask refinement network may be dominated by signals with larger amplitudes during the learning process, ignoring signals with smaller amplitudes but equally important directions, thus affecting the stability and convergence speed of training. To eliminate the adverse effects of such amplitude fluctuations on the training process, sub-steps S3021 to S3023 perform normalization and norm clipping on the gradient teacher signal.

[0341] Furthermore, after obtaining the gradient teacher signals corresponding to each refinement step in step S302, the following sub-steps are also included:

[0342] S3021: For the gradient teacher signal corresponding to each refinement step, perform L2 normalization according to the preset normalization dimension to obtain the normalized gradient teacher signal.

[0343] The preset normalization dimension determines the spatial scope on which the normalization operation is performed: if normalization is performed by the sample dimension, the L2 norm is jointly calculated for the gradient values ​​of all channels and spatial locations of each training sample, and then the gradient map is scaled as a whole using this norm; if normalization is performed by the channel dimension, the L2 norm is calculated independently for each channel and then scaled; if normalization is performed by the spatial dimension, the gradient vector at each spatial location is normalized. In medical image processing scenarios, normalization by the sample dimension is usually chosen. Its effect is to transform the gradient teacher signal of each training sample into a unit norm direction vector, preserving the relative strength of gradients at different spatial locations, while eliminating the problem of inconsistent gradient magnitudes caused by differences in the absolute value of the loss function between different samples. After L2 normalization, the gradient teacher signal no longer carries information about the magnitude of the correction, but only retains the direction information of the correction, that is, informing the mask thinning network which direction each pixel in the boundary region should be adjusted in the current mask state. The magnitude of the correction is determined by both the single-step update of the magnitude parameter and the output of the mask refinement network itself, thereby decoupling the direction learning from the magnitude control and allowing the network to focus on learning high-quality correction directions.

[0344] S3022: Compare the norm of the normalized gradient teacher signal with a preset norm interval. If the norm exceeds the upper limit of the preset norm interval, then prune according to the upper limit. If the norm is lower than the lower limit of the preset norm interval, then prune according to the lower limit.

[0345] The norm of the normalized gradient teacher signal is compared with a preset norm interval, and the norm is pruned based on the comparison result. Although sub-step S3021 has normalized the gradient teacher signal to the unit norm, anomalies may still occur in some extreme cases: for example, when the gradient of the denoising task loss with respect to a certain intermediate soft mask approaches zero, the normalization operation may amplify numerical noise into a significant non-zero signal; or when gradient vanishing occurs due to the depth of the network, the normalized signal, although directional, has an excessively low signal-to-noise ratio. The preset norm interval is defined by two thresholds: a lower limit and an upper limit. The lower limit is used to filter weak signals with excessively low signal-to-noise ratios, and the upper limit is used to prevent abnormally amplified signals from excessively impacting training. The specific rules for the pruning operation are as follows: If the norm of the normalized gradient teacher signal exceeds the upper limit of the preset norm interval, the entire gradient graph is scaled proportionally so that its norm is exactly equal to the upper limit, thereby limiting the maximum influence of the signal on parameter updates; if the norm is lower than the lower limit of the preset norm interval, the entire gradient graph is scaled proportionally so that its norm is exactly equal to the lower limit, thereby ensuring that even if the original gradient signal is weak, it can still provide effective supervision to the network with a certain strength; if the norm is already within the preset interval, no adjustment is made, and the original normalized gradient teacher signal is used directly. This pruning operation ensures that the gradient teacher signals received in all refinement steps are within a reasonable and consistent range in amplitude, avoiding training imbalance caused by signals that are too strong or too weak in individual steps. The aforementioned preset norm interval is determined based on the statistical distribution of gradient norms in the training set, with its lower limit being 5% of the gradient norms of all batches and its upper limit being 95%.

[0346] S3023: The normalized gradient teacher signal after pruning is used as the final gradient teacher signal in this refinement step, and is used for the calculation of the subsequent gradient teacher loss.

[0347] The gradient teacher signal will be compared with the signed correction field output by the mask thinning network in the corresponding step in sub-step S303 to form the gradient teacher loss, thereby driving the mask thinning network parameters to update towards the correction field direction that can output a direction close to the negative task gradient. Through the above normalization and pruning preprocessing, the supervision signal received in each thinning step has been normalized and calibrated in both direction and amplitude, so that the mask thinning network can obtain balanced and stable training supervision among various thinning steps, unaffected by the difference in gradient amplitude or the fluctuation of loss of different samples in different steps, thereby accelerating convergence and improving the final mask thinning quality.

[0348] In the multi-step differentiable Markov state transition process, the mask refinement network outputs a signed correction field at each refinement step, while the gradient teacher signal provides an ideal reference for the correction direction of that step. Since different refinement steps are at different stages in the mask evolution process, their contribution to the final task adaptive soft mask quality also differs in terms of mode and importance. Therefore, the correction deviations of each step cannot be simply weighted and summed.

[0349] Further, step S303 calculates the gradient teacher loss, including the following sub-steps:

[0350] S3031: Obtain the gradient teacher signal and the signed correction field output by the mask thinning network at each thinning step, and calculate the single-step residual of each thinning step.

[0351] For each refinement step, the gradient teacher signal is a directional supervision signal obtained by calculating the gradient of the intermediate soft mask obtained in this step using the denoising task loss, followed by a stopping gradient operation and normalization. It indicates how the boundaries should be adjusted in the current mask state to most effectively reduce the final generation error. The signed correction field output by the mask refinement network in this step is the network's actual response to the same mask state. The single-step residual is calculated as the difference between the two, essentially measuring the deviation between the network's current output correction direction and the ideal correction direction. This residual is typically calculated within the boundary region defined by the active boundary indicator; correction values ​​outside the boundary region are gated to zero by multiplication and do not participate in residual accumulation. The single-step residual, as a local measure of the correction quality of each step, preserves the unique error information of each step, providing a basis for subsequent weighted aggregation.

[0352] S3032: Assign a preset step weight to each refinement step. The step weight either remains monotonically constant or decreases exponentially as the refinement step index increases.

[0353] In a multi-step Markov state transition process, different steps perform different evolutionary functions: early steps mainly complete the general directional migration from the initial diagnostic mask to the task-related region, with large correction amplitudes but undetermined boundary positions; later steps, based on the preceding steps, perform fine-tuning of boundary positions, gradually converging to the task-optimal state. To address this characteristic, two differentiated weight allocation strategies are pre-defined. The first strategy is that the step weights monotonically increase with the refinement step index, meaning later steps are assigned weights no less than earlier steps. In specific implementations, this can be achieved through linear increments, step increments, or concentrated weighting only in the last few steps. This strategy emphasizes the decisive impact of later fine-tuning on the final mask quality, because the correction accuracy of steps closer to the final output directly relates to the task adaptability of the task-adaptive soft mask; assigning them higher loss weights encourages the network to focus more on outputting high-precision correction directions at the end of the refinement process. The second strategy is that the step weights decay exponentially with the refinement step index, meaning earlier steps are assigned higher weights, which gradually decrease exponentially as the steps progress. This strategy emphasizes encouraging the network to quickly capture the correct correction trend early in the refinement process. The correction direction in early steps determines the basic trajectory of the entire evolution; if there is a significant deviation in the early direction, even refined subsequent steps cannot fully compensate for it. Simultaneously, the reduction in weights in later steps prevents the network from falling into local oscillations due to excessive pursuit of minute corrections near convergence. In engineering practice, the choice between the two strategies depends on the specific task characteristics: for tasks with large initial mask deviations and significant boundary shifts, the monotonic decay strategy helps ensure the accuracy of the final output; for tasks with relatively reasonable initial masks and only requiring local fine-tuning, the exponential decay strategy can accelerate early convergence and prevent overfitting in later stages.

[0354] S3033: The single-step residuals of each refinement step are weighted and summed according to the corresponding step weights to obtain the gradient teacher loss.

[0355] This loss value aggregates the correction direction deviation information from all refinement steps, and reflects the differentiated importance of different steps in the overall optimization through temporal weights. The weighted summed gradient teacher loss, as a scalar value, is used during training to feed back the correction deviation information from each step to the shared parameters of the mask refinement network through backpropagation, driving the network to improve the output quality of the correction field across all refinement steps. Since the network parameters are shared across all steps, this comprehensive feedback mechanism allows the network to learn a general correction strategy applicable to different evolution stages simultaneously, rather than learning a set of parameters independently for each step, thereby reducing the number of parameters while enhancing the model's generalization ability. The gradient teacher loss, together with the total variation regularization loss and the boundary distance regularization loss, constitute the complete training objective of the mask refinement network. Through a subsequent objective-consistent combination mechanism, the network parameters are updated collaboratively, ultimately enabling the mask refinement network to automatically generate an effective task-adaptive soft mask for downstream cross-modal generation tasks during the inference phase, based solely on the initial diagnostic guidance mask and the source modality image.

[0356] Furthermore, the source modal medical image is a T1-weighted magnetic resonance imaging image, and the initial diagnostic guidance mask is a tumor mask obtained by combining at least one annotation of enhanced tumor, peritumoral edema, and necrotic core.

[0357] In multi-sequence magnetic resonance imaging (MRI) cross-modal generation tasks, T1-weighted MRI images are often selected as the source modality due to their excellent ability to display anatomical structures. Contrast-enhanced T1-weighted MRI and fluid-attenuated inversion recovery (FIR) sequences are two target modalities with wide clinical applications but very different imaging characteristics. Contrast-enhanced T1-weighted MRI significantly increases the signal in areas where the blood-brain barrier is disrupted by injecting gadolinium-based contrast agents. Its image features mainly reflect the contrast agent uptake and accumulation in the lesion area, and it is clinically used to assess tumor activity and boundaries. Fluid-attenuated inversion recovery sequences, on the other hand, suppress the signal of free water, making areas with increased bound water content appear as high signals. Its image features are extremely sensitive to peritumoral edema and the extent of invasion, and it is widely used to assess the extent of tumor invasion and post-treatment changes. Although the generation tasks of these two target modalities share the same T1 source modality image and the same initial tumor mask, their spatial cueing requirements differ fundamentally: generating contrast-enhanced T1-weighted images requires spatial cueing to focus more on the tumor core and enhanced areas of blood-brain barrier disruption, while generating fluid-attenuated inversion recovery images requires spatial cueing to extend to the edema zone and surrounding infiltrative areas of the tumor. Directly using the same mask as fixed spatial cueing for both tasks will inevitably lead to a significant decrease in the generation quality of at least one task due to spatial cueing misalignment. This approach, by performing independent training processes for different target modalities under the same source modality image and the same initial diagnostic guidance mask, allows the mask refinement network to automatically learn differentiated boundary adjustment strategies that match the specific task requirements.

[0358] When the target modality is contrast-enhanced T1-weighted magnetic resonance imaging, the first training process is executed. The mask refinement network parameters obtained in the first training process enable the task-adaptive soft mask to highlight the morphological regions related to the contrast-enhanced appearance.

[0359] In the first training process for contrast-enhanced T1-weighted magnetic resonance imaging (MRI), the training system uses T1-weighted images as the source modality and contrast-enhanced T1-weighted images as the target modality for supervised training. Although the initial diagnostic guidance mask is obtained by merging multiple annotations such as enhanced tumor, peritumoral edema, and necrotic core, covering a relatively broad lesion range, in the first training process, the mask refinement network receives feedback from the loss of the contrast-enhanced T1 generation task through a gradient teacher mechanism, gradually learning that the contribution of contrast agent uptake information in the enhanced tumor core region and its edges to the generation quality is more significant. As training progresses, the signed correction field output by the mask refinement network in multi-step state transitions will tend to shrink the boundaries of the initial mask towards the interior or edges of the enhanced region, so that the final task-adaptive soft mask highlights morphological regions highly related to the appearance of contrast enhancement, such as the boundaries of the solid components of the enhanced tumor and active areas of contrast agent accumulation, while moderately suppressing attention allocation to areas that do not produce significant contrast enhancement, such as edema and necrotic core. This learning process is entirely driven by the loss function of the generation task, without the need for manually defining adjustment rules for each target modality.

[0360] When the target modality is a liquid attenuation inversion recovery sequence image, a second training process is performed. The masking refinement network parameters obtained in the second training process enable the task-adaptive soft mask to highlight morphological regions related to edema-sensitive areas and the entire tumor region.

[0361] In the second training process targeting liquid-attenuated inversion recovery (LIFR) sequence images, the training system uses the same T1-weighted image as the source modality and the liquid-attenuated inversion recovery image as the target modality, employing the exact same initial diagnostic guidance mask as in the first training process. However, the difference in the target modality leads to fundamental changes in the spatial distribution and gradient direction of the denoising task loss. The liquid-attenuated inversion recovery sequence generation task has high requirements for signal reproduction in the peritumoral edema region and infiltration extent, and the generation loss is more sensitive to changes in the mask boundary position in these regions. The gradient teacher signal received by the mask refinement network in the second training process guides the network to evolve in different directions, gradually learning to extend the boundary of the initial mask outward to the outer edge of the edema zone. This allows the final generated task-adaptive soft mask to highlight the morphological regions related to the edema-sensitive area and the entire tumor region, helping the generation model to more accurately reproduce the spatial distribution characteristics of the edema signal.

[0362] In this training process, the source modality medical images and initial diagnostic guidance masks are the same in both the first and second training processes, but the target modality medical images are different. Although the first and second training processes share the same source modality medical images and initial diagnostic guidance masks, the denoising task losses calculated in the two training processes differ significantly in spatial distribution and numerical characteristics due to the different target modality medical images. These differences are passed to the mask refinement network via a gradient teacher mechanism, driving the network with the same architecture to converge to two distinct sets of parameters. These two sets of parameters encode mask boundary adjustment knowledge for contrast-enhanced T1 generation and liquid attenuation inversion recovery generation tasks, respectively. This allows for flexible invocation of appropriate model parameters based on clinical needs during the actual inference phase, automatically generating differentiated spatial cues highly adapted to specific target modality generation tasks from the same identical T1 source image and initial tumor mask. This multi-task adaptation scheme, which shares the preprocessing process and network architecture but differentiates only in the training supervision signals, fully leverages the task adaptability of the differentiable Markov mask refinement framework, providing a unified and flexible technical foundation for clinical completion and auxiliary diagnosis of multi-sequence magnetic resonance imaging.

[0363] As the core computational unit in the multi-step differentiable Markov state transition process, the mask refinement network needs to output a signed correction field corresponding to the spatial morphology of the current soft mask in each refinement step. The design of this network needs to strike a balance between computational efficiency, receptive field coverage, multi-scale feature extraction capability, and boundary localization accuracy to adapt to the refinement requirements of lesion masks of different sizes and shapes. Therefore, this invention employs a lightweight U-shaped convolutional network with an encoder-decoder structure as the implementation scheme for the mask refinement network.

[0364] Furthermore, step S2 involves constructing a parameter-shared mask refinement network, including the following sub-steps:

[0365] S21: Construct input mapping convolutional blocks to map the input soft mask to a high-dimensional feature space.

[0366] The input soft mask is a single-channel 2D or 3D matrix, where each pixel's value is between 0 and 1, representing the confidence that the current location belongs to the foreground region. Single-channel input carries low-dimensional information; if directly fed into subsequent complex network structures, the network struggles to extract rich spatial structural and boundary morphological features. Input mapping convolutional blocks typically consist of one or two concatenated convolutional layers, each containing several learnable convolutional kernels. Through convolution operations, the single-channel soft mask is mapped to a high-dimensional feature space with more channels. This mapping process can be understood as transforming the original scalar confidence map into multiple feature maps. Each feature map captures the local morphological features of the input mask from different filter response perspectives; for example, one feature map might respond to the mask's boundary position, another to the foreground interior region, and still others might be sensitive to changes in the mask's curvature. As the network's entry point, the input mapping convolutional block's output feature map retains the complete spatial resolution of the input soft mask, providing an information-rich high-dimensional representation for multi-scale feature extraction in subsequent downsampling blocks.

[0367] S22: Construct at least two downsampling blocks, and downsample the output of the input mapping convolutional block step by step to extract multi-scale features.

[0368] Each downsampling block typically consists of two parts: a convolutional layer and a downsampling operation. The convolutional layer uses several convolutional kernels to perform feature transformation and nonlinear mapping on the input feature map, extracting local spatial features at that resolution level. The downsampling operation reduces the spatial size of the feature map to half its original size using convolution or pooling operations with a stride of 2, while increasing the number of channels accordingly to reduce spatial redundancy while retaining more semantic information. Through the successive concatenation of at least two downsampling blocks, the spatial size of the network's feature map gradually decreases, while the receptive field gradually expands. At shallower downsampling layers, the spatial resolution of the feature map is higher, and the receptive field is smaller. The network mainly focuses on the local details of the mask, such as the local orientation of the boundary and small-scale concavity and convexity variations. At deeper downsampling layers, the spatial resolution of the feature map is lower, and the receptive field is larger. The network can capture the global morphological features of the mask, such as the overall outline, the approximate location and size of lesions, etc. This multi-scale feature extraction capability, from local details to global morphology, enables the network to make correction decisions by comprehensively considering both fine-grained and coarse-grained information of the mask. It avoids neglecting overall morphological constraints by focusing only on local information, and also avoids losing boundary positioning accuracy by relying solely on global information.

[0369] S23: Construct a bottleneck block and process the last-level downsampled features to obtain the bottleneck features.

[0370] The bottleneck block, located at the boundary between the encoder and decoder, receives the feature map with the smallest spatial size and the most channels. It represents the layer with the largest receptive field and the highest level of semantic abstraction in the entire network. Typically composed of two or more convolutional layers, the bottleneck block does not include downsampling operations. Its role is to deeply integrate and semantically abstract the multi-scale features extracted during the encoding stage in the most compact feature space, condensing information from different receptive fields into a compact bottleneck feature representation. This bottleneck feature simultaneously contains core semantic information about both the local boundaries and global morphology of the mask, serving as the starting point for the subsequent decoding stage to progressively restore spatial resolution.

[0371] S24: Construct upsampling blocks with the same number of downsampling blocks, perform upsampling of bottleneck features at each level, and fuse them with the features of the corresponding downsampling blocks through skip connections in each level of upsampling.

[0372] Each upsampling block consists of an upsampling operation and a convolutional layer. The upsampling operation doubles the spatial size of the feature map through transposed convolution or interpolation-plus-convolution, gradually restoring it to the same spatial resolution as the corresponding encoding layer. After upsampling, skip connections are used to concatenate the input features of the upsampling block with the output features of the corresponding downsampling block in the encoding stage along the channel dimension or add them element-wise. This fuses the local detail features captured at this resolution level in the encoding stage with the global semantic features gradually restored in the decoding stage. The skip connections compensate for the fine spatial details lost due to the reduced spatial resolution during downsampling, ensuring that the feature map in the decoding stage has both global semantic guidance from the bottleneck layer and retains the local boundary accuracy of the corresponding encoding layer. By restoring the spatial resolution step by step through the same number of upsampling blocks as the downsampling blocks, the final feature map is restored to the same spatial size as the input soft mask. However, the feature vector at each pixel position has fused multi-scale contextual information from local to global, providing rich feature support for subsequent correction field prediction.

[0373] S25: Construct the output convolutional layer to generate a signed correction field based on the output of the last upsampled block.

[0374] The output convolutional layer typically consists of a single convolutional layer with the number of kernels equal to the number of output channels. For 2D image tasks, this is usually one output channel, while for multi-channel masking tasks, multiple output channels can be set. This convolutional layer takes the fused feature map output from the last upsampling block as input and maps the multi-channel feature vector at each pixel location to a scalar correction value through convolution operations. Unlike the output layer of a conventional segmentation network, this output convolutional layer does not use the Sigmoid or Softmax activation functions because the output range of these non-negative activation functions is non-negative, and they can only generate non-negative correction values, unable to express negative correction in the contraction direction. The output convolutional layer can use a linear activation function to directly map the feature vector to the real number domain, allowing each pixel in the correction field to take positive, negative, or zero values. A positive value indicates that the location needs to expand outward, a negative value indicates that the location needs to contract inward, and a zero value indicates that the location does not need adjustment. In engineering practice, the Tanh activation function can also be used to limit the output to the range of negative one to positive one, working in conjunction with the single-step update amplitude parameter to control the correction range of each step.

[0375] The aforementioned mask refinement network presents a U-shaped encoder-decoder topology, with its input and output sharing the same spatial dimensions. Intermediate layers utilize downsampling and upsampling for multi-scale feature extraction and fusion, while skip connections compensate for spatial detail loss. This network is compact with relatively few parameters, making it suitable for repeated use in multi-step iterations without significantly increasing computational burden. Its multi-scale feature extraction capability allows it to adapt to the refinement needs of lesion masks of varying sizes and morphological complexities. Since all refinement steps share the same set of parameters, the network must learn a general correction strategy applicable to various mask states during training, rather than memorizing fixed output patterns for specific steps or mask shapes. This ensures the Markov property of state transitions at the network structure level, ensuring that the output of the correction field depends only on the spatial morphology of the current soft mask, rather than the step index or historical states.

[0376] Following the adaptive soft mask for generating continuous values ​​through multi-step differentiable Markov state transitions, this invention provides a binarized output path for the soft mask and its application in image generation to further meet the spatial cueing requirements of different application scenarios.

[0377] Furthermore, after generating the task-adaptive soft mask for medical cross-modal image synthesis in step S3, the process also includes:

[0378] Step S41: Compare the task-adaptive soft mask with the preset binarization threshold, set pixels greater than or equal to the threshold as foreground, and pixels less than the threshold as background, to obtain the binarized task-adaptive mask.

[0379] The task-adaptive soft mask generated in step S3 is compared pixel-by-pixel with a preset binarization threshold. Pixels in the mask with values ​​greater than or equal to the threshold are identified as foreground and labeled as foreground, while pixels with values ​​less than the threshold are identified as background and labeled as background. This transforms the continuous-value soft mask into a binary task-adaptive mask containing only foreground and background states. The practical significance of this transformation is that, although the continuous-value soft mask finely characterizes the spatial range that needs to be considered when inferring the target modality from the source modality through the confidence of each pixel, and can provide information-rich soft spatial cues for diffusion-based generative models, in some practical deployment scenarios, the specific implementation of clinical workflows or generative models may prefer to accept explicit binary regions as conditional inputs. For example, it may be necessary to align spatial cues with existing image delineation standards, present key regions as outlines in the reporting system, or adapt to third-party generative model interfaces that only support binary mask inputs. The selection of the binarization threshold determines the precise range of task-relevant regions extracted from the soft mask. This threshold can be determined by evaluating the quality of generated images on a validation set based on the specific task. Typically, 0.5 is used as the default confidence threshold, but it can also be adjusted according to different preferences for sensitivity and specificity: a higher threshold results in a more conservative binarization mask, retaining only pixel regions that the network is highly confident are task-relevant; a lower threshold results in a wider coverage area, incorporating more edge and transition regions. Through this simple threshold comparison operation, the task-adaptive boundary information contained in the soft mask is condensed into a clear binary outline, facilitating integration with downstream clinical review processes or computationally limited inference environments.

[0380] Step S42: Input the binarization task adaptive mask and the source modal medical image into the diffusion-type medical image generation model to generate the target modal medical image.

[0381] The binarization task-adaptive mask is used as a spatial condition, input along with the source modality medical image into a diffusion-based medical image generation model to generate the final target modality medical image. Compared to directly using continuous-value soft masks as conditions, the significant advantage of using a binarized mask as a conditional input is that it provides the generation model with a clear, either-or spatial bias signal. This allows the generation model to employ differentiated generation strategies within and outside the region indicated by the binarized mask. For example, within the foreground region indicated by the mask, the generation model can allocate more network capacity and attention resources to reproduce the contrast enhancement features or metabolic distribution of lesions; within the background region outside the mask, the generation model primarily relies on the anatomical structure information of the source modality image to reconstruct normal tissue signals, unaffected by the conditional signal in the foreground region. This explicit spatial bisection can simplify the conditional modeling difficulty of the generation model in some scenarios, enabling the network to more directly learn the differentiated generation patterns between the foreground and background. Meanwhile, continuous-value soft masks and binarized masks are not mutually exclusive choices. In practical applications, they can be flexibly selected according to task requirements: when fine-grained spatial modulation of lesion boundaries is required, continuous-value soft masks should be used first to fully unleash the expressive power of task-adaptive soft masks; when a clear lesion outline that can be superimposed on an image report is required, or when compatibility with existing binarized mask processing pipelines is needed, the binarized path can be used. Both paths share the same mask refinement network trained through multi-step differentiable Markov state transitions, and only bifurcate at the inference post-processing stage. There is no need to train an additional independent binarized mask generation model, maintaining the simplicity of the system and the flexibility of deployment.

[0382] Furthermore, the source modal medical image is a computed tomography (CT) image, the target modal medical image is a positron emission tomography (PET) image, and the initial diagnostic guidance mask is a lesion annotation mask in the CT image.

[0383] In the cross-modal generation task of computed tomography (CT) images to positron emission tomography (PET) images, the source modality CT image reflects the anatomical density distribution of human tissues through the X-ray attenuation coefficient, providing high spatial resolution for displaying morphological structures such as bones, soft tissues, and lesion contours. The target modality PET image reflects tissue metabolic activity by detecting the distribution of radioactive tracers in the body. The commonly used tracer, fluorodeoxyglucose, exhibits abnormally high uptake in malignant tumor cells, making the lesion area appear as a metabolically active hotspot in PET images. While the two modalities are naturally complementary in terms of information dimensions, they do not have a one-to-one spatial relationship. There is often a spatial misalignment between the morphological range of a lesion visible in a CT image and its metabolically active range. For example, the lesion's periphery may show morphological changes on CT but no obvious metabolic abnormalities, or the surrounding tissues adjacent to the lesion may appear morphologically normal on CT but have already shown metabolic infiltration. Furthermore, some lesions may contain necrotic or cystic areas, appearing as low-density areas on CT but as metabolic defects on PET. This spatial distribution of metabolic heterogeneity does not correspond simply to the morphological boundaries on CT. Therefore, in the CT-to-PET cross-modal generation task, the initial diagnostic guidance mask is the lesion annotation mask in the computed tomography image. Its boundaries are usually drawn by radiologists based on the morphological features of the CT image, reflecting the spatial extent of the lesion at the anatomical level. If this morphological boundary is directly used as the spatial cue for generating the PET metabolic image, the model will be forced to uniformly infer metabolic distribution within the morphological boundary, unable to autonomously identify metabolically active and metabolically inert sub-regions within the morphological range, and unable to capture surrounding tissues outside the morphological boundary that have undergone metabolic changes. This results in a structural deviation between the metabolic distribution in the generated PET image and the actual situation.

[0384] Accordingly, in step S3, a task-adaptive soft mask is used to indicate morphological regions in the source modal computed tomography image that are useful for inferring metabolic activity in positron emission tomography.

[0385] The task-adaptive soft mask generated in step S3 is designed to address the spatial inconsistency between the aforementioned morphological boundaries and the metabolically active range. Each pixel in the task-adaptive soft mask is no longer a binary decision, but a continuous value between 0 and 1. This continuous value can be interpreted as the amount of morphological information or confidence provided by that location when inferring the PET metabolic intensity at the corresponding location from the source modality CT image. Under this mechanism, the mask refinement network progressively learns which morphological features in the CT image are valuable for inferring PET metabolic activity through multi-step differentiable Markov state transitions, thereby automatically adjusting the mask boundaries and internal confidence distribution. For example, for areas on CT images where the lesion edges appear spiculated or irregularly enhanced, the network might identify them as potentially metabolically active locations and assign them a higher confidence level after refinement. For areas on CT that are clearly liquefied necrosis or calcification, the network might identify them as metabolically inert areas and assign them a lower confidence level after refinement. For morphologically normal surrounding tissues adjacent to lesions on CT, if there are microinfiltrations that are difficult to directly display on CT images, the network, during training, receives feedback from the PET generation loss regarding the correction direction for this area through a gradient teacher. This might appropriately expand the mask boundary outward and assign a moderate confidence level, thus prompting the generation model to pay some attention to metabolic inference in this area. This adaptive adjustment process driven by task loss does not require manual definition of the mapping rules between CT features and PET metabolism. It is entirely learned automatically through backpropagation from the cross-modal correlation statistics in the data. This allows the final task-adaptive soft mask to accurately indicate the morphological regions in the source modality CT image that are most informative for inferring PET metabolic activity, rather than mechanically reusing the morphological boundaries of diagnostic segmentation. This function directly embodies the core inventive idea of ​​this method, which transforms diagnostic-guided hard masks into generative task-guided soft space prompts. It provides key technical support for improving the accuracy of metabolic image generation in the clinically valuable application scenario of cross-modal generation from CT to PET.

[0386] The following verification scheme based on specific application scenarios illustrates the effectiveness of this method.

[0387] Using computed tomography (CT) as the source modality and fluorodeoxyglucose positron emission tomography (FDG-PET) as the target modality, a CT lesion mask serves as the initial condition, and a final soft mask is used to prompt the model to focus on morphological regions in the CT image related to inference of metabolic activity. The hardware can utilize a server with a graphics processing unit (GPU); one optional implementation configuration uses an Intel Xeon Gold 5418Y processor and an NVIDIA RTX 5880 Ada Generation GPU, with a diffusion step count set to 4. Both the hardware and the number of steps are replaceable. CT refers to computed tomography, FDG-PET refers to fluorodeoxyglucose positron emission tomography, and GPU refers to a graphics processing unit.

[0388] Evaluation metrics include structural similarity (SSIM), peak signal-to-noise ratio (PSNR), Fréchet Inception distance (FID), and learned perceptual patch similarity (LPIPS). For tumor regions, this can be achieved using an initial tumor mask. The mean absolute error is calculated after converting the actual and generated PET strengths to standard uptake values ​​(SUVs): The average error of the SUV (SME) is then calculated by averaging the test samples.

[0389] Here, the set of voxels in the tumor region represents the voxels inside the initial tumor mask in the sample; the intensity of the i-th voxel in the real target image and the intensity of the i-th voxel in the generated target image are respectively processed by the SUV transformation function to obtain comparable metabolic uptake values. The SUV error measures the average deviation between the real metabolic intensity and the generated metabolic intensity within the tumor region of a single sample, while SME is the average of this error at the test set level.

[0390]

[0391] in, This represents the set of voxels inside the initial tumor mask in the sample; This represents the intensity of the real PET image at the i-th voxel; This represents the intensity of the generated PET image at the i-th voxel; This represents a transformation function that converts image intensity to standard intake values.

[0392] The aforementioned regional metrics complement general image quality metrics: Structural Similarity (SSIM) and Peak Signal-to-Noise Ratio (PSNR) emphasize structural and pixel fidelity; Fréchet Inception Distance (FID) and Learned Perceptual Patch Similarity (LPIPS) emphasize distributional realism and perceptual consistency; and Standardized Uptake Value (SUV) and SUV Mean Error (SME) emphasize task-relevant fidelity in tumor metabolic regions.

[0393] Four types of comparisons can be set up: the original generated model, the original mask input splicing, the refined mask input splicing, and the refined mask cross-attention model, and the comparisons are made under the same data partitioning and training budget. This embodiment only specifies the reproducible verification process and does not presuppose or fabricate numerical improvements.

[0394] like Figure 7 As shown, Figure 7 Parts a to d in the figure represent the input CT image, the initial spatial cue, the task-adaptive spatial cue after multi-step refinement, and the target PET reference image, respectively, demonstrating the correspondence between the input conditions and the reference target during inference; Figure 7 Part e presents the verification metrics for the recommended report in the form of radar charts or bar graphs, including dimensions such as structural similarity, peak signal-to-noise ratio, perceptual difference, and regional error, used to compare the impact of initial mask cues and refined mask cues on the quality of target mode generation. The values ​​in the figure are normalized illustrations used to illustrate the evaluation dimensions and quality control methods, rather than limiting the specific experimental results of this invention.

[0395] As an optional implementation, this method can also be applied to the synthesis and validation of multi-sequence magnetic resonance imaging (MRI). In this scenario, using T1 as the source modality and T1CE and FLAIR as target modalities respectively, the enhanced tumor, peritumoral edema, and necrotic / non-enhanced core are merged to obtain an initial tumor mask. For T1 to T1CE, the refined mask tends to highlight T1 morphological regions related to contrast enhancement appearance; for T1 to FLAIR, the refined mask tends to highlight edema-sensitive and whole-tumor-related clues. MRI refers to magnetic resonance imaging, T1CE refers to enhanced T1-weighted magnetic resonance imaging, and FLAIR refers to fluid attenuation inversion recovery sequence.

[0396] In addition to general image quality metrics, in tumor regions The average absolute difference between the real magnetic resonance imaging (MRI) and the generated MRI is calculated, and the average pixel mean error (PME) is obtained by averaging over the test samples. This metric corresponds to the MRI task-specific region error in this invention and is used to evaluate the generation fidelity of tumor-related regions.

[0397] Among them, the pixel mean error (PME) is obtained by averaging the absolute intensity differences of each pixel in the tumor region of the test sample, and is used to measure the generation fidelity of the tumor-related region.

[0398]

[0399] Where PE represents the pixel error of the tumor region in a single sample; the average pixel error PME is obtained by averaging the PE of all test samples.

[0400] Visualize the initial mask, intermediate masks at each step, and the final mask to check if changes are concentrated in the cumulative activity boundary region; pixel differences outside the statistical region should be zero or below the numerical tolerance. The gradient teacher, total variation regularization, boundary distance regularization, and target consistency weight constraints can also be ablated separately to verify the effects of each component.

[0401] As an optional implementation, the deployment and mask trajectory output during the inference phase can be performed as follows:

[0402] The inference phase does not require a target modality image. The system receives and Execute according to the parameters during training. Further refinement, The input to the generative model completes either backdiffusion or deterministic sampling. It can simultaneously output the generated image, the final soft mask, the binarized mask, and intermediate trajectories, facilitating doctors' examination of changes in spatial cues.

[0403] Electronic devices include processors, memory, and communication interfaces. When the program in memory is executed by the processor, it performs data reading, boundary calculation, mask refinement, diffusion-based target mode generation, and result output. Training and inference programs and model parameters can be stored on non-transitory computer-readable media.

[0404] As an optional implementation method, the selection of key parameters and training quality control can be performed as follows:

[0405] On the validation set , , , , The gradient teacher weights and regularization weights are used for line search or grid search. It is recommended to monitor the generated task metrics, total mask variation, average update norm per step, and the angle between the auxiliary gradient and the principal gradient simultaneously. If conflicts between the auxiliary gradient and the principal gradient occur in multiple consecutive batches, the regularization base weights can be reduced or the auxiliary gradient can be discarded according to the objective consistency constraint.

[0406] Accordingly, please refer to Figure 8 A second aspect of this invention provides a differentiable Markov mask thinning system for medical cross-modal image generation, which performs medical image processing based on the aforementioned differentiable Markov mask thinning method for medical cross-modal image generation, including:

[0407] Data acquisition module 1 is used to acquire source modal medical images and initial diagnostic guidance masks spatially registered with the source modal medical images. The initial diagnostic guidance mask is a binary or continuous value mask that indicates the lesion area.

[0408] Network construction module 2 is used to construct a parameter-sharing mask refinement network. The mask refinement network is used to output a signed correction field based on the input soft mask. In the signed correction field, positive values ​​indicate foreground expansion and negative values ​​indicate foreground contraction.

[0409] State transition module 3 is used to perform multi-step differentiable Markov state transitions with the initial diagnostic guidance mask as the initial state. Each state transition is based on the activity boundary indicator determined by the current soft mask, which restricts the signed correction field output by the mask refinement network to the boundary region to update the current soft mask, until a task-adaptive soft mask for medical cross-modal image synthesis is generated.

[0410] Accordingly, a third aspect of the present invention provides an electronic device, comprising: at least one processor; and a memory connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, the instructions being executed by the at least one processor to cause the at least one processor to perform the above-described differentiable Markov mask thinning method for medical cross-modal image generation.

[0411] Accordingly, a fourth aspect of the present invention provides a computer-readable storage medium having computer instructions stored thereon that, when executed by a processor, implement the above-described differentiable Markov mask thinning method for medical cross-modal image generation.

[0412] The embodiments of this invention aim to protect a differentiable Markov mask thinning method and system for medical cross-modal image generation, which has the following effects:

[0413] 1. By modeling the refinement process of the initial diagnostic guide mask as a multi-step differentiable Markov state transition, and using an active boundary indicator based on morphological gradients at each step to strictly limit the mask update to the narrow band region of the current foreground and background boundary, the mask changes only occur gradually in a controllable manner near the original boundary. This allows for task-driven outward expansion or inward contraction while ensuring that the pixel states of the high-confidence regions inside the boundary and the external background regions far from the boundary are not arbitrarily modified. Thus, the unconstrained spatial drift problem in one-time high-dimensional regression is transformed into a stable asymptotic process within the feasible set of the boundary. This significantly improves the spatial rationality of the refinement results while maintaining the geometric interpretability of the mask.

[0414] 2. By introducing a gradient teacher signal that stops the gradient during the training phase, the denoising task loss of the final output of the diffusion-based medical image generation model is backpropagated step by step to each intermediate state of the mask thinning network. This allows the signed correction field of each thinning step to directly learn the direction to reduce the final generation error, rather than simply approximating a fixed intermediate target or regularization term. As a result, the macroscopic cross-modal image generation quality target is decomposed into local correction tasks that can be executed in each step, shortening the optimization path between the task supervision signal and the mask correction field. This enables the final generated task-adaptive soft mask to truly serve to improve the generation accuracy of the target modality medical image.

[0415] 3. When training the mask refinement network, instead of simply linearly superimposing the total variation regularization gradient, boundary distance regularization gradient, and main task refinement gradient, we solve for the minimum norm combination of auxiliary gradients that does not oppose the main task direction constraint, forming a combined gradient consistent with the descent direction of the main task. At the same time, we introduce monotonically increasing weights based on the Euclidean distance from the pixel to the initial mask boundary in the boundary distance regularization, so that changes near the original boundary are only weakly penalized, while large-scale drifts far from the boundary are strongly constrained. This suppresses local mask noise and long-distance distortion while avoiding the auxiliary regularization from covering the optimization direction of the main task, achieving a synergistic improvement in mask smoothness and task adaptability.

[0416] Those skilled in the art will understand that embodiments of this application can be provided as methods, systems, or computer program products. Therefore, this application can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, this application can take the form of a computer program product embodied on one or more computer-usable storage media (including but not limited to disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.

[0417] This application is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart... Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.

[0418] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.

[0419] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.

[0420] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention and not to limit it. Although the present invention has been described in detail with reference to the above embodiments, those skilled in the art should understand that modifications or equivalent substitutions can still be made to the specific implementation of the present invention. Any modifications or equivalent substitutions that do not depart from the spirit and scope of the present invention should be covered within the scope of protection of the claims of the present invention.

Claims

1. A differentiable Markov mask thinning method for cross-modal medical image generation, characterized in that, Includes the following steps: S1: Acquire a source modal medical image and an initial diagnostic guidance mask spatially registered with the source modal medical image, wherein the initial diagnostic guidance mask is a binary or continuous value mask indicating the lesion region; S2: Construct a parameter-sharing mask thinning network, which is a convolutional network with an encoder-decoder structure, including an input mapping convolutional block, multiple downsampling blocks, a bottleneck block, multiple upsampling blocks, and an output convolutional layer connected in sequence. The upsampling blocks are fused with the features of the corresponding downsampling blocks through skip connections. The output convolutional layer is used to output a signed correction field. Positive values ​​in the signed correction field indicate foreground expansion, and negative values ​​indicate foreground contraction. S3: Using the initial diagnostic guidance mask as the initial state, perform multi-step differentiable Markov state transitions. Each state transition is based on the activity boundary indicator determined by the current soft mask. The signed correction field output by the mask refinement network is restricted to the boundary region to update the current soft mask until a task-adaptive soft mask for medical cross-modal image synthesis is generated. The execution of multi-step differentiable Markov state transitions in step S3 includes the following sub-steps: S31: Map the initial diagnostic guidance mask to the range [0,1] as the current soft mask, and set the total number of refinement steps and the single-step update amplitude; S32: Perform a single state transition step to update the current soft mask and obtain an intermediate soft mask; S33: Cut the intermediate soft mask to the range [0,1] and use it as the new current soft mask; S34: Repeat steps S32 to S33 until the total number of refinement steps is completed, and obtain the task-adaptive soft mask; The single state transition step described in step S32 includes the following sub-steps: S321: Perform grayscale dilation and grayscale erosion operations on the current soft mask to obtain the outer boundary band and the inner boundary band; S322: Merge the outer boundary band with the inner boundary band, and obtain the active boundary indicator after normalization and thresholding. S323: Input the current soft mask into the mask thinning network to obtain the signed correction field; S324: Multiply the signed correction field with the active boundary indicator pixel by pixel to obtain the restricted correction field; S325: Add the current soft mask to the constrained correction field scaled according to the single-step update amplitude pixel by pixel to obtain the intermediate soft mask.

2. The differentiable Markov mask thinning method for medical cross-modal image generation according to claim 1, characterized in that, Following step S34, the following sub-steps are also included: Step S35: Save the intermediate soft mask obtained from each execution of step S32 to obtain the intermediate mask sequence. The intermediate mask sequence, together with the initial diagnostic guidance mask and the task adaptive soft mask, constitute the mask evolution trajectory. Step S36: Superimpose each mask in the mask evolution trajectory onto the source modality medical image in chronological order to generate a mask evolution visualization image sequence. The mask evolution visualization image sequence is used to demonstrate the spatial cue change process from the diagnostic guidance mask to the task adaptive soft mask.

3. The differentiable Markov mask thinning method for medical cross-modal image generation according to claim 1, characterized in that, After generating the task-adaptive soft mask for medical cross-modal image synthesis as described in step S3, the following sub-steps are also included: S301: Input the task-adaptive soft mask and the source modality medical image into the diffusion-based medical image generation model to obtain the target modality estimation image, and calculate the denoising task loss based on the target modality estimation image; The diffusion-based medical image generation model is a neural network model that generates a target modality medical image based on the source modality medical image and the task-adaptive soft mask. The denoising task loss is calculated based on the target modality estimation image and the real target modality image, wherein the real target modality image is the target modality medical image spatially registered with the source modality medical image; S302: Calculate the gradient of the soft mask obtained in each step of the multi-step differentiable Markov state transition process in step S3 with respect to the denoising task loss, and perform a gradient stop operation to obtain the gradient teacher signal corresponding to each refinement step. S303: Calculate the gradient teacher loss based on the gradient teacher signal and the signed correction field output by the mask thinning network in the corresponding step; S304: Calculate the total variation regularization loss and the boundary distance regularization loss, and solve for the auxiliary gradients corresponding to the total variation regularization loss and the boundary distance regularization loss; S305: Combine the auxiliary gradient with the main task refinement gradient corresponding to the gradient teacher loss to obtain the combined gradient; S306: Update the parameters of the mask thinning network using the combined gradient.

4. The differentiable Markov mask thinning method for medical cross-modal image generation according to claim 3, characterized in that, Step S305, which involves combining the auxiliary gradient with the main task refinement gradient corresponding to the gradient teacher loss, in a goal-consistent manner, includes the following sub-steps: S3051: Using the main task refined gradient, total variation regularized gradient, and boundary distance regularized gradient as inputs, calculate the difference vector between the total variation regularized gradient and the boundary distance regularized gradient; S3052: Calculate the inner product of the difference vector and the main task refinement gradient, and the inner product of the boundary distance regularization gradient and the main task refinement gradient; S3053: Determine the feasible interval of the total variational regularization weights based on the two inner products; S3054: Solve for the minimum norm solution of the auxiliary gradient combination formed by the total variation regularized weights and the boundary distance regularized weights, and project it into the feasible interval to obtain the final auxiliary weights; S3055: If the feasible interval is empty, then reset the final auxiliary power to zero; S3056: The total variational regularized gradient and the boundary distance regularized gradient are weighted and summed using the final auxiliary weights, and then added to the main task refinement gradient to obtain the combined gradient.

5. The differentiable Markov mask thinning method for medical cross-modal image generation according to claim 3, characterized in that, Step S304 calculates the boundary distance regularization loss, which includes the following sub-steps: Step S3041: Perform morphological dilation and morphological erosion operations on the initial diagnostic guidance mask, and calculate the difference between the two to obtain the initial boundary response; Step S3042: Construct an initial boundary set from the pixels that are greater than zero in the initial boundary response; Step S3043: Calculate the Euclidean distance from each pixel to the initial boundary set to obtain a distance map; Step S3044: Input the distance map into a monotonically increasing function controlled by a preset temperature parameter to obtain the boundary distance weights; Step S3045: Multiply the boundary distance weight by the deviation of the task adaptive soft mask relative to the initial diagnostic guide mask pixel by pixel and sum them to obtain the boundary distance regularization loss.

6. The differentiable Markov mask thinning method for medical cross-modal image generation according to claim 3, characterized in that, Step S301, which involves inputting the task-adaptive soft mask and the source modality medical image into the diffusion-based medical image generation model, includes the following sub-steps: Step S30111: Perform multi-scale encoding on the task adaptive soft mask to obtain multi-scale mask features; Step S30112: In the denoising network of the diffusion-type medical image generation model, multiple resolution layers are selected. In each selected resolution layer, the image features of that layer are used as queries, and the mask features corresponding to that layer are used as keys and values. Cross-attention calculation is performed to obtain the mask conditional enhancement features of that layer. Step S30113: Fuse the mask condition enhancement features of each selected resolution layer with the original image features of the corresponding layer to obtain the fused features used for denoising prediction.

7. The differentiable Markov mask thinning method for medical cross-modal image generation according to claim 3, characterized in that, The training of the mask thinning network and the diffusion-based medical image generation model is performed sequentially in the following stages: First stage: Fix the parameters of the mask refinement network, and train the diffusion medical image generation model using only the source modal medical images and the initial diagnostic guidance mask until the diffusion medical image generation model meets the first preset convergence condition; Second stage: Fix the parameters of the diffusion-type medical image generation model, or set its learning rate to be lower than the first preset threshold, and execute steps S301 to S306 to train the mask thinning network until the mask thinning network meets the second preset convergence condition. The third stage involves simultaneously updating the parameters of the mask thinning network and the diffusion-based medical image generation model with a non-zero learning rate, performing joint fine-tuning until the third preset convergence condition is met.

8. A differentiable Markov mask thinning system for medical cross-modal image generation, characterized in that, Medical image processing based on the differentiable Markov mask thinning method for medical cross-modal image generation as described in any one of claims 1-7 includes: The data acquisition module is used to acquire source modal medical images and an initial diagnostic guidance mask spatially registered with the source modal medical images. The initial diagnostic guidance mask is a binary or continuous value mask that indicates the lesion area. The network construction module is used to construct a parameter-sharing mask refinement network. The mask refinement network is used to output a signed correction field based on the input soft mask. In the signed correction field, positive values ​​indicate foreground expansion and negative values ​​indicate foreground contraction. The state transition module is used to perform multi-step differentiable Markov state transitions with the initial diagnostic guidance mask as the initial state. Each state transition is based on the activity boundary indicator determined by the current soft mask, which restricts the signed correction field output by the mask refinement network to the boundary region to update the current soft mask, until a task-adaptive soft mask for medical cross-modal image synthesis is generated.

Citation Information

Patent Citations

  • Fine-grained image classification method based on interpretable learning

    CN121837706A

  • Optical flow estimation method based on dynamic mask cross-modal distillation

    CN121904098A