Method and system for optic cup and disc segmentation in fundus images based on deep learning

By combining the tasks of contour detection and distance map estimation based on deep learning, the U-shaped network solves the problem of long manual calculation of cup-disc ratio and risk of misjudgment in glaucoma diagnosis, and achieves more accurate and efficient segmentation of optic cup and optic disc, improving The ability of early screening and diagnosis of glaucoma.

CN118229682BActive Publication Date: 2024-09-27CHANGCHUN UNIV OF SCI & TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202410642149.3
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2024-05-23
Publication Date
2024-09-27
Estimated Expiration
2044-05-23

AI Technical Summary

Technical Problem

At present, in glaucoma diagnosis, doctors need to manually calculate the cup-to-disk ratio of the optic cup and the optic disc, which results in a large workload, long time consumption, and the risk of misjudgment, making it difficult to effectively screen and diagnose early.

Method used

A deep learning-based optic cup and optic disc segmentation method in fundus images is adopted. By constructing a U-shaped network and combining the tasks of contour detection and distance map estimation, the accuracy and efficiency of the model's segmentation of the optic cup and optic disc are improved.

Benefits of technology

It achieves more accurate and faster glaucoma diagnosis, reduces the workload of doctors, improves the reliability and efficiency of diagnosis, and provides a more convenient diagnostic method.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118229682B
    Figure CN118229682B
Patent Text Reader

Abstract

The present invention belongs to the technical field of image analysis of ophthalmic diseases, and specifically relates to a method and system for optic cup and optic disc segmentation of fundus images based on deep learning. Step 1: Acquire fundus color images to form a data set, and perform image enhancement on the data in the data set, and divide the enhanced data set into a training set and a verification set; Step 2: Construct a U-shaped network, and the U-shaped network includes a compression encoder path and three scalable decoder paths; Step 3: Input the training set of step 1 into the U-shaped network constructed in step 2, and train the U-shaped network; Step 4: Verify the U-shaped network trained in step 3 using the verification set of step 1, and use the verified U-shaped network to achieve optic cup and optic disc segmentation of fundus images. The present invention is used to solve the problem that the distance map estimation task in the current glaucoma diagnosis causes the model to be misclassified.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention belongs to the technical field of ophthalmic disease image analysis, and specifically relates to a method and system for segmenting optic cup and optic disc of fundus images based on deep learning. Background Art

[0002] According to the epidemiological survey of glaucoma in China, the number of people suffering from glaucoma in the world exceeded 80 million in 2020, and the blindness rate of glaucoma is close to 1 / 3, second only to cataracts. Glaucoma has developed into the world's second largest irreversible chronic eye disease causing blindness. Since 2015, the number of people suffering from glaucoma in China has steadily increased, with an average increase of 300,000 to 400,000 per year. It is estimated that the number of patients will reach 23 million by 2030. Therefore, how to detect and treat glaucoma as early as possible has become an important task for ophthalmologists and researchers.

[0003] Early screening and clinical diagnosis of glaucoma are mainly evaluated by experienced ophthalmologists through indicators such as the ratio of the diameter of the optic cup to the optic disc in the fundus image, namely the cup-to-disc ratio. The cup-to-disc ratio is an important parameter for glaucoma detection. Generally speaking, the larger the cup-to-disc ratio, the greater the probability of glaucoma. However, the current calculation of the cup-to-disc ratio in clinical practice is performed manually by doctors. This method has problems such as a large workload for doctors, a long evaluation time, and the risk of clinical misjudgment. In order to solve these difficulties, a method for optic cup and disc segmentation of fundus images based on a U-shaped network is proposed. This method introduces the position information of the optic disc into the optic cup segmentation, and introduces the contour detection task and the distance map estimation task into the segmentation network. The two auxiliary tasks can help the model better retain the shape and boundary information of the target area in the image, which has certain practicality and promotion value, and can provide ophthalmologists with more accurate and faster diagnostic methods. Summary of the invention

[0004] The present invention provides a method and system for segmenting the optic cup and disc of fundus images based on deep learning, which are used to solve the problem that the distance map estimation task in the current glaucoma diagnosis causes the model to be misclassified.

[0005] The present invention is achieved through the following technical solutions:

[0006] A method for segmenting optic cup and optic disc of fundus images based on deep learning, the method comprising the following steps:

[0007] Step 1: Obtain fundus color images to form a data set, perform image enhancement on the data in the data set, and divide the enhanced data set into a training set and a validation set;

[0008] Step 2: construct a U-shaped network, wherein the U-shaped network includes a compression encoder path and three scalable decoder paths;

[0009] Step 3: Input the training set of step 1 into the U-shaped network constructed in step 2 to train the U-shaped network;

[0010] Step 4: Verify the U-shaped network trained in step 3 using the verification set in step 1, and use the verified U-shaped network to achieve optic cup and optic disc segmentation of fundus images.

[0011] Furthermore, the step 1 is specifically:

[0012] Step 1.1: Import the required libraries;

[0013] Step 1.2: Create a DatasetImageMaskContourDist(Dataset), define __init__, accept two parameters: file_names and distance_type, which represent the file name and the string, which includes the distance type to be loaded; define __len__, which returns the length of the dataset; define __getitem__, use load_image, load_mask, load_contour, and load_distance functions to load image, mask, contour, and distance data; finally, return a tuple containing the image file name, image, mask, contour, and distance;

[0014] Step 1.3: Define the load_image(path) function, call Image.open(path) to open the image file at the specified path and load it as a PIL image object; the transforms.Compose() function defines the image transformation operation and finally returns the image;

[0015] Step 1.4: Define the load_mask(path) function;

[0016] Step 1.5: Define the load_contour(path) function, the same as step 1.4;

[0017] Step 1.6: Define the load_distance(path, distance_type) function.

[0018] Furthermore, the step 2 is specifically as follows:

[0019] Step 2.1: Define the __init__() function;

[0020] Step 2.2: Call the super().__init__() function, assign the passed num_classes parameter to the instance variable self.num_classes to represent the number of task categories, and use assert to ensure that the lengths of the down_filter_factors and up_filter_factors lists are equal; then call the self.module method, create a module object, pass in input_channels and down_filter_sizes[0] and add them to the self.down list;

[0021] Step 2.3: Use a for loop to create the convolutional layers in the downsampling path;

[0022] Step 2.4: Create a maximum pooling layer object pool; MaxPool2d performs the maximum pooling operation;

[0023] Step 2.5: First add a None to the self.downsamplers list, then copy the pool pooling layer to match the number of convolutional layers in the downsampling path; assign pool_bottom to the last element of self.downsamplers; self.upsamplers1, self.upsamplers2, self.upsamplers3, these lists are used to store the upsampling layers in the upsampling path; the elements in each list are the same upsampling layers, used to match the number of convolutional layers in the upsampling path; the last element is assigned to upsample_bottom1, upsample_bottom2 and upsample_bottom3 for upsampling of the bottom part;

[0024] Step 2.6: If the add_output variable is of type True, an output layer is added to the UNet network; the final convolutional layers self.conv_final1, self.conv_final2, and self.conv_final3 are used to generate the output of the model;

[0025] Step 2.7: Use the forward propagation method forward(self, x) to receive an input tensor x, process it and return the output;

[0026] Step 2.8: Set up three sets of for loops. Each set of for loops traverses from the bottom of the upsampling path upwards. In the first set of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers1 contains the upsampling layer of the first set of upsampling paths, and self.up contains the convolutional layer of the upsampling path.

[0027] In the second set of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers2 contains the upsampling layers of the second set of upsampling paths, and self.up contains the convolutional layers of the upsampling paths;

[0028] In the third group of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers3 contains the upsampling layers of the third group of upsampling paths, and self.up contains the convolutional layers of the upsampling paths;

[0029] Step 2.9: Use self.add_output to check whether output is needed;

[0030] Step 2.10: Define a class named LossPsiNet; the class initialization method __init__ accepts a parameter weights, which defaults to [1, 1, 1]; during the initialization process, create three loss function objects: self.criterion1 and self.criterion2 are instances of the LossMulti class, and the num_classes parameter is set to 2; self.criterion3 is the mean square error loss function nn.MSELoss() in PyTorch; in the class's __call__ method, accept six parameters outputs1, outputs2, outputs3, targets1, targets2, targets3, which represent the output of the model and the corresponding target value respectively; return the final weighted loss value criterion.

[0031] Furthermore, the step 2.8 is specifically as follows:

[0032] Step 2.8.1: Set up a for loop to traverse from the bottom of the upsampling path upwards; in each iteration, it traverses three lists at the same time: xs[:-1], self.upsamplers1, self.up, which contain the feature maps of the downsampling path except the last layer, the upsampling layer, and the convolution layer respectively; x_skip is the feature map of the downsampling path, which is connected to the input of the current upsampling layer; apply the current upsampling layer upsample to x_out1 to increase the spatial resolution of the feature map; then use the torch.cat function to concatenate the upsampled feature map x_out1 with the feature map x_skip of the downsampling path in the channel dimension; finally, pass the concatenated feature map to the current upsampling convolution layer up to generate a new x_out1 feature map, which will be used for the next iteration until the top of the upsampling path;

[0033] Step 2.8.2: Set up a second for loop, similar to the loop in step 2.8, but it iterates over another set of upsampling path layers; xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers2 contains another set of upsampling layers of the upsampling path, and self.up still contains the convolutional layers of the upsampling path;

[0034] Step 2.8.3: Set up the third for loop, similar to the loops in steps 2.8 and 2.9, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers3 contains another set of upsampling layers of the upsampling path, and self.up still contains the convolutional layers of the upsampling path.

[0035] Furthermore, the step 3 is specifically as follows:

[0036] Step 3.1: Define the training model function. First, check model_type through the conditional statement. If it is, perform the following operations, otherwise skip; the specific execution is to first call optimizer.zero_grad() to clear the previous parameter gradients, and then set the gradient calculation to on through torch.set_grad_enabled(True) to ensure that the model parameter gradients can be calculated. Then use the model model to forward propagate the input data inputs to obtain the model output outputs; extract the third output from outputs, and remove the dimension of size 1 in its dimension through squeeze(dim=1) to obtain output; calculate the loss value loss, use the previously defined criterion, pass in the three outputs of the model, and the three target values ​​in the target value list; then call loss.backward() and optimizer.step() to calculate the gradient of the loss to the model parameters and update the model parameters according to the gradient; finally, return the calculated loss value loss;

[0037] Step 3.2: Create and parse command line arguments through create_train_arg_parser().parse_args() and store them in args; set the CUDA_SELECT variable. If the value of args.cuda_no is cpu or GPU is not available, use the CPU to run; set the path and related configuration of the log file, and record blank lines to distinguish different log records; get the list of file names of the training set and the validation set, and randomly shuffle the file names of the training set; use the torch.device() function to specify the device on which the model runs, call the build_model(args.model_type) function to build the model, and select the corresponding model according to the model type in the command line parameter;

[0038] Step 3.3: If args.use_pretrained is true, load the pretrained model; create trainLoader, devLoader, and displayLoader; initialize the optimizer optimizer; define the loss function criterion;

[0039] Step 3.4: Use the range() function to generate an iteration range, starting from int(epoch_start)+1 and ending at int(epoch_start)+1+args.num_epochs-1. At each epoch of the loop iteration, the progress bar will be updated to show the current progress.

[0040] Step 3.5: Calculate the global step number global_step; Initialize running_loss to 0.0; Use enumerate(trainLoader) to traverse the training data loader, obtain each small batch of data, and train it; In the loop of each small batch of data: Set the model to training mode, then move the data to the specified device, call the train_model function to train the model, pass in the model, target value, model type, loss function and optimizer, and calculate the loss of the small batch of data, and then use writer.add_scalar() to write the loss value to the TensorBoard log; Multiply the loss of the small batch of data by the size of the input data and accumulate it in running_loss; Calculate the average loss of each epoch epoch_loss;

[0041] Step 3.6: Whenever the value of epoch is divisible by 1, first call the evaluate() function to evaluate the validation set, calculate the validation set loss dev_loss and the evaluation time dev_time; then use writer.add_scalar() to write the validation set loss to the TensorBoard log; then call the visualize() function to visualize the display data set so that the output of the model can be viewed in TensorBoard; print the current global loss and validation set loss information; otherwise, only print the current global loss; use logging.info() to record the training loss of each epoch; whenever the value of epoch is divisible by 5, do the following:

[0042] Use the torch.save() function to save the parameters of the current model to the specified file path.

[0043] Furthermore, the step 4 is specifically as follows:

[0044] Step 4.1: Create and parse command line arguments through create_validation_arg_parser().parse_args() and store them in args; construct the path val_path of the validation dataset; define the model file path model_file, define the save path save_path, and define the model type model_type;

[0045] Step 4.2: Get the CUDA device number cuda_no; construct the CUDA device selection string CUDA_SELECT according to cuda_no. If cuda_no is "cuda:0", CUDA_SELECT is "cuda:0"; if cuda_no is "cuda:1", CUDA_SELECT is "cuda:1", and so on; use the torch.cuda.is_available() function to check whether the current system supports CUDA. If it does, select the CUDA device; otherwise, select the CPU device;

[0046] According to the selected device, set it as the default device used; use the glob.glob() function to get all file names that match the specified file extension according to the given path val_path, and store the results in the list val_file_names; create a verification data loader valLoader, use the DataLoader class, the dataset is constructed by the DatasetImageMaskContourDist class, pass in the verification data file name list val_file_names and the distance type "dist_contour";

[0047] Step 4.3: Use the os.path.exists(save_path) function to check whether the specified save path save_path exists; if the save path does not exist, use the os.mkdir(save_path) function to create the path; call the build_model(model_type) function to build the model, and choose to build the corresponding model according to the specified model type model_type; move the built model to the specified device, using the model.to(device) function; use the torch.load() function to load the pre-trained model parameters from the specified file path and apply the loaded parameters to the model; call the model.eval() method to set the model to evaluation mode;

[0048] Step 4.4: Use enumerate(tqdm(valLoader)) to traverse each batch of data in the verification data loader valLoader; input the input data inputs into the model for inference to obtain the three outputs outputs1, outputs2, and outputs3 of the model; take the output data of the model from the device and convert it into a NumPy array; generate the corresponding mask image res according to the output of the model; find the index of the category with the maximum probability through the np.argmax() function, and then set the pixel value to the corresponding category according to the index; construct the save path output_path of the mask image, name it "mask_" + the original image file name, and save the mask image to the specified save path; finally, use OpenCV's cv2.imwrite() function to save the mask image as an image file.

[0049] Furthermore, the tool functions used in the U-shaped network are specifically:

[0050] Define a function evaluate to evaluate model performance;

[0051] Define a function visualize to visualize the model output;

[0052] Use model.eval() to set the model to evaluation mode, use the torch.no_grad() context manager, use the enumerate function to traverse each iteration in the data loader data_loader, and get the iteration number iter and data data, input data inputs and target data targets; use the model to infer the input data to get the output data outputs; convert the tensor output by the model to a NumPy array and assign it to the output_mask variable, find the index of the maximum value on the first dimension of the output_mask array, convert it to a floating point type, assign it to the output_final variable, convert the output_final array to a tensor, and add a dimension to the second dimension; check whether the model is in training mode, call the save_image function, save the target data and model prediction results of the training set and add them to the visualization tool, using the label "Target_train" and "Prediction_train"; if not in training mode, call the save_image function to save the target data and model prediction structure of the validation set and add them to the visualization tool, using the labels "Target" and "Prediction" for identification; after processing the first iteration, jump out of the loop and visualize only one batch of data;

[0053] Create a training parameter parser function create_train_arg_parser();

[0054] Create a parameter parser object create_validation_arg_parser() function for parsing validation parameters, including: --model_type selects the model type to be used; --val_path specifies the path of the validation dataset; --model_file specifies the model file path to be loaded; --save_path specifies the save path of the validation results; --cuda_no specifies the CUDA device number to be used, the default is 0; finally, return the created parameter parser object.

[0055] A deep learning-based fundus image optic cup and optic disc segmentation system, the system uses the above-mentioned deep learning-based fundus image optic cup and optic disc segmentation method, the system includes

[0056] A data acquisition module acquires fundus color images to form a data set, performs image enhancement on the data set, and divides the enhanced data set into a training set and a validation set;

[0057] A U-shaped network construction module, constructing a U-shaped network, wherein the U-shaped network includes a compression encoder path and three scalable decoder paths;

[0058] The network training module inputs the training set into the constructed U-shaped network to train the U-shaped network;

[0059] The network verification module verifies the trained U-shaped network using the verification set, and uses the verified U-shaped network to achieve optic cup and optic disc segmentation of fundus images.

[0060] A computer device comprises a memory, a processor and a computer program stored in the memory and executable on the processor, wherein when the processor executes the computer program, the above method is implemented.

[0061] A computer-readable storage medium stores a computer program, which is executed by a processor to implement the method as described above.

[0062] The beneficial effects of the present invention are:

[0063] The present invention uses the contrast-limited adaptive histogram equalization (CLAHE) method to process the original image. Then, the target area to be segmented in the fundus image (including the optic cup and the optic disc) is used as the region of interest and is cropped in advance. Then, the cropped data set is amplified and a random horizontal inversion operation is performed. The processed image is segmented into optic cup and optic disc using an improved U-shaped network. The network includes an identical encoder and three different decoders. Each decoder block trains different tasks, including target area (mask) segmentation, contour extraction, and distance map estimation tasks. The algorithm in this paper is model-verified on the Drishti-GS1 dataset, and its performance is compared with traditional U-Net, M-Net and other methods. The results show that this model has good segmentation performance for optic cup and optic disc, providing doctors with a more convenient and efficient way to diagnose glaucoma. BRIEF DESCRIPTION OF THE DRAWINGS

[0064] Figure 1 It is a schematic diagram of an image after the original image is processed by the present invention, wherein a) is the original image, b) is the image after CLAHE, and c) is the image of the region of interest.

[0065] Figure 2 The figure is a flow chart of the method of the present invention.

[0066] Figure 3 is the final segmentation result of an embodiment of the present invention, wherein a) is the original image, b) is the ROI image, c) is the optic disc segmentation result, d) is the original image, e) is the introduced optic disc position, and f) is the optic cup segmentation result. DETAILED DESCRIPTION

[0067] In the following description, specific details such as specific system structures, technologies, etc. are provided for the purpose of illustration rather than limitation, so as to provide a thorough understanding of the embodiments of the present application. However, it should be clear to those skilled in the art that the present application may also be implemented in other embodiments without these specific details. In other cases, detailed descriptions of well-known systems, devices, circuits, and methods are omitted to prevent unnecessary details from obstructing the description of the present application.

[0068] It should be understood that when used in this specification and the appended claims, the term "comprising" indicates the presence of described features, integers, steps, operations, elements and / or components, but does not exclude the presence or addition of one or more other features, integers, steps, operations, elements, components and / or groups thereof.

[0069] It should also be understood that the terms used in this application specification are only for the purpose of describing specific embodiments and are not intended to limit the application. As used in this application specification and the appended claims, the singular forms "a", "an" and "the" are intended to include plural forms unless the context clearly indicates otherwise.

[0070] The following is attached to this application specification Figure 1-3 , the technical solutions in the embodiments of the present application are clearly and completely described. Obviously, the described embodiments are only part of the embodiments of the present application, not all of the embodiments. Based on the embodiments in the present application, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present application.

[0071] In the following description, many specific details are set forth to facilitate a full understanding of the present application, but the present application may also be implemented in other ways different from those described herein, and those skilled in the art may make similar generalizations without violating the connotation of the present application. Therefore, the present application is not limited to the specific embodiments disclosed below.

[0072] Embodiment 1

[0073] This embodiment provides a method for segmenting the optic cup and optic disc of a fundus image based on deep learning. The method for segmenting the optic cup and optic disc of a fundus image includes the following steps:

[0074] Step 1: Obtain fundus color images to form a data set, and perform image enhancement on the data in the data set. Figure 1 As shown, the enhanced data set is divided into a training set and a validation set;

[0075] Obtain fundus color ultrasound images of the Drishti-GS1 dataset and the Origa dataset. In order to make the results clearer, the contrast of the input fundus images was improved by contrast-limited adaptive histogram equalization (CLAHE), thereby obtaining better visual effects. Then, before fine target region segmentation, the region of interest (including the optic cup and optic disc) was cropped in advance, and the enhanced image was cropped out of the optic disc area using the ground truth image. The cropped ROI image size is 256×256. For the cropped dataset, data augmentation was performed, and the purpose of training set data augmentation was achieved by random horizontal flipping.

[0076] Step 2: construct a U-shaped network, wherein the U-shaped network includes a compression encoder path and three scalable decoder paths;

[0077] Step 3: Input the training set of step 1 into the U-shaped network constructed in step 2 to train the U-shaped network;

[0078] Step 4: Verify the U-shaped network trained in step 3 using the verification set in step 1, and use the verified U-shaped network to achieve optic cup and optic disc segmentation of fundus images.

[0079] like Figure 2 As shown, the segmentation of the optic cup and optic disc of the fundus image using the improved U-shaped network includes the following steps:

[0080] First, the region of interest is extracted from the retinal fundus image, that is, the area where the optic cup and optic disc are located is extracted to improve the accuracy of the segmentation result. Then the extracted ROI image is input into the optic disc segmentation network to obtain the result of optic disc segmentation. Then the optic disc segmentation result is operated with the ROI image to obtain a special ROI containing the optic disc location information, which is then sent to the optic cup segmentation network to finally obtain the optic cup segmentation result. In summary, the optic cup segmentation network contains the prior knowledge that the optic cup is located inside the optic disc, thereby imposing certain positive restrictions on the effect of optic cup segmentation.

[0081] Furthermore, the step 1 is specifically:

[0082] Step 1.1: Import the required libraries;

[0083] The step 1.1 specifically includes torch, numpy, cv2, PIL, torch.utils.data, torchvision.transforms and scipy.io;

[0084] Step 1.2: Create a DatasetImageMaskContourDist(Dataset), define __init__, accept two parameters: file_names and distance_type, which represent the file name and the string, which includes the distance type to be loaded; define __len__, which returns the length of the dataset; define __getitem__, use load_image, load_mask, load_contour, and load_distance functions to load image, mask, contour, and distance data; finally, return a tuple containing the image file name, image, mask, contour, and distance;

[0085] Step 1.3: Define the load_image(path) function, call Image.open(path) to open the image file at the specified path and load it as a PIL image object; the transforms.Compose() function defines the image transformation operation and finally returns the image;

[0086] Specifically, the step 1.3 is as follows: transforms.Resize([256,256]) adjusts the image to a size of 256x256 pixels; transforms.ToTensor() converts the image to a PyTorch Tensor format; transforms.Normalize(...) normalizes the image;

[0087] Step 1.4: Define the load_mask(path) function;

[0088] Specifically, step 1.4 is as follows: use cv2.imread to load "mask"; use the path.replace operation to convert the path of the image file to the corresponding mask file path, and also replace ".jpg" with "_ODsegSoftmap.png", load the image in grayscale mode, and convert it into a single-channel mask image; use the cv2.resize function to adjust the size of "mask" to 256*256; set the pixel value of mask==255 to 1; use the NumPy function np.expand_dims() to insert a new dimension in front of the dimension of the array mask; use the torch.from_numpy() function to convert the NumPy array to a PyTorch tensor, and use .long() to convert the data type of the tensor to a 64-bit integer; use mask.repeat(2,1,1) to copy the mask tensor to match the same number of channels as the image data, and finally return "mask";

[0089] Step 1.5: Define the load_contour(path) function, the same as step 1.4;

[0090] Step 1.6: Define the load_distance(path, distance_type) function.

[0091] Specifically, step 1.6 includes: if distance_type is "dist_mask", construct the path of the mask distance image; use SciPy's io.loadmat function to load the distance image data, where "mask_dist" is the distance data field in the mat file; if distance_type is "dist_contour", construct the path of the contour distance image; use SciPy's io.loadmat function to load the distance image data, where "distance_transform" is the distance data field in the mat file; the mat file is the data processed in advance by matlab, the contour map uses the bwperim statement to extract the contour of the mask, and the distance map is the result of the mask image through the Euclidean distance transformation; then use dist.shape[1] and dist. shape[0] gets the width and height of the dist tensor, then subtracts 256 and divides by 2 to find the left and top cropping boundaries and retain the center part; crops a sub-image of size 256x256 pixels from the variable dist and stores it in the variable cropped_image, uses OpenCV's cv2.resize function to resize the image to a size of 256x256 pixels and uses linear interpolation; converts the NumPy array to a PyTorch tensor; if distance_type is "dist_signed": the function constructs the path to the signed distance image; uses SciPy's io.loadmat function to load the distance image data, where "dist_norm" is the distance data field in the mat file; finally, the load_distance function returns the processed distance image data.

[0092] Furthermore, the step 2 is specifically as follows:

[0093] Step 2.1: Define the __init__() function, set the input_channels parameter to 3, the filters_base parameter to 32, the down_filter_factors parameter to 1, 2, 4, 8, 16, the up_filter_factors parameter to 1, 2, 4, 8, 16, the bottom_s parameter to 4, the num_classes parameter to 1, and add_output to True;

[0094] Step 2.2: Call the super().__init__() function, assign the passed num_classes parameter to the instance variable self.num_classes to represent the number of task categories, use assert to ensure that the lengths of the down_filter_factors and up_filter_factors lists are equal to maintain network structure consistency; use assert to ensure that the last elements of the down_filter_factors and up_filter_factors lists are equal; multiply filters_base by each element in down_filter_factors and up_filter_factors to calculate down_filter_sizes and up_filter_sizes; create two empty nn.ModuleList objects to store the encoder and decoder modules; then call the self.module method, create a module object, pass in input_channels and down_filter_sizes[0] and add them to the self.down list;

[0095] Step 2.3: Use a for loop to create the convolutional layers in the downsampling path; the number of input channels of each downsampling layer is the number of output channels of the previous layer; then use a for loop to create the convolutional layers in the upsampling path; the number of input channels of each upsampling layer is the sum of the number of output channels of the previous downsampling path and the current layer;

[0096] Step 2.4: Create a maximum pooling layer object pool; MaxPool2d performs the maximum pooling operation; the parameter (2, 2) specifies the size of the pooling window as 2x2 and the stride as 2; create another maximum pooling layer object pool_bottom; set a variable bottom_s to specify the size and stride of the pooling kernel; create three upsampling layer objects, namely upsample1, upsample2, and upsample3. The Upsample() function performs the upsampling operation, and the scale_factor is assigned to 2. Create three upsampling layer objects upsample_bottom1, upsample_bottom2, and upsample_bottom3, all of which use the variable bottom_s as the scaling factor;

[0097] Step 2.5: First add a None to the self.downsamplers list, then copy the pool pooling layer to match the number of convolutional layers in the downsampling path; assign pool_bottom to the last element of self.downsamplers; self.upsamplers1, self.upsamplers2, self.upsamplers3, these lists are used to store the upsampling layers in the upsampling path; the elements in each list are the same upsampling layers, used to match the number of convolutional layers in the upsampling path; the last element is assigned to upsample_bottom1, upsample_bottom2 and upsample_bottom3 for upsampling of the bottom part;

[0098] Step 2.6: If the add_output variable is of type True, an output layer is added to the UNet network; the final convolutional layers, self.conv_final1, self.conv_final2, and self.conv_final3, are used to generate the output of the model; each convolutional layer is created using nn.Conv2d, and the final number of output channels is determined by num_classes. Depending on the value of add_output, multiple output layers may be created, corresponding to different tasks;

[0099] Step 2.7: Use the forward propagation method forward(self, x) to receive an input tensor x, then process it and return the output; create an empty list xs to store the output of each layer; set up a for loop to traverse the elements in the two lists self.downsamplers and self.down, and use the zip function to pair the elements in the corresponding positions in the two lists one by one; determine the input x_in based on whether the current layer has a downsampler; if downsample is None, assign the input x directly to x_in; otherwise, use the output of the last element in the list xs after downsample as x_in; pass the input x_in to the current layer down for processing to obtain the output feature map x_out; add the output x_out of the current layer to the list xs so that it can be used by subsequent layers; assign the last element in the list xs (that is, the output of the latest layer) to x_out; copy x_out to three different variables x_out1, x_out2 and x_out3 for subsequent upsampling paths;

[0100] Step 2.8: Set up three sets of for loops, each set of for loops traverses from the bottom of the upsampling path upwards. In the first set of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers1 contains the upsampling layer of the first set of upsampling paths, and self.up contains the convolutional layer of the upsampling path;

[0101] In the second set of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers2 contains the upsampling layers of the second set of upsampling paths, and self.up contains the convolutional layers of the upsampling paths;

[0102] In the third group of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers3 contains the upsampling layers of the third group of upsampling paths, and self.up contains the convolutional layers of the upsampling paths;

[0103] Step 2.9: Use self.add_output to check if output is needed; pass x_out1 to a final convolutional layer self.conv_final1 to generate the first output of the model; if self.num_classes is greater than 1, it means that the task is a multi-category classification problem, and use the softmax function to convert x_out1 to log probability for use in the output of multi-category classification problems. Similar operations are also applied to x_out2 and x_out3, performing convolution and output conversion as needed; the difference is that x_out3 uses F.sigmoid in the last line for binary classification problems to map the output to the range [0, 1]; finally, the function returns a list of three outputs [x_out1, x_out2, x_out3], each of which has been processed accordingly to suit specific task types and requirements;

[0104] Step 2.10: Define a class named LossPsiNet, which is mainly used to calculate the weighted sum of multiple loss functions; the class initialization method __init__ accepts a parameter weights, which defaults to [1, 1, 1]; this parameter is used to set the weight of the loss function; during the initialization process, three loss function objects are created: self.criterion1 and self.criterion2 are instances of the LossMulti class, and the num_classes parameter is set to 2; self.criterion3 is the mean square error loss function nn.MSELoss() in PyTorch; in the class's __call__ method, six parameters outputs1, outputs2, outputs3, targets1, targets2, targets3 are accepted, representing the output of the model and the corresponding target value respectively; in the __call__ method, the results of the three loss functions are weighted and summed, and the weights are determined by self.weights; the final weighted loss value criterion is returned.

[0105] Furthermore, the step 2.8 is specifically as follows:

[0106] Step 2.8.1: Set up a for loop to traverse from the bottom of the upsampling path upwards; in each iteration, it traverses three lists at the same time: xs[:-1], self.upsamplers1, self.up, which contain the feature map of the downsampling path except the last layer, the upsampling layer, and the convolution layer respectively; x_skip is the feature map of the downsampling path, which is connected to the input of the current upsampling layer; apply the current upsampling layer upsample to x_out1 to increase the spatial resolution of the feature map; then use the torch.cat function to concatenate the upsampled feature map x_out1 with the feature map x_skip of the downsampling path in the channel dimension; finally, pass the concatenated feature map to the current upsampling convolution layer up to generate a new x_out1 feature map, which will be used for the next iteration until the top of the upsampling path;

[0107] Step 2.8.2: Set up a second for loop, similar to the loop in step 2.8, but it iterates over another set of upsampling paths; xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers2 contains another set of upsampling layers of the upsampling path, and self.up still contains the convolutional layers of the upsampling path;

[0108] Step 2.8.3: Set up the third for loop, similar to the loops in steps 2.8 and 2.9, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers3 contains another set of upsampling layers of the upsampling path, and self.up still contains the convolutional layers of the upsampling path.

[0109] Furthermore, the step 3 is specifically as follows:

[0110] Step 3.1: Define the training model function, including parameters such as model, target, model type, loss function, and optimizer; first, check model_type through the conditional statement, if it is, perform the following operations, otherwise skip; the specific execution is to first call optimizer.zero_grad() to clear the previous parameter gradients, and then set the gradient calculation to on through torch.set_grad_enabled(True) to ensure that the model parameter gradients can be calculated, and then use the model model to forward propagate the input data inputs to obtain the model output outputs; extract the third output from outputs, and remove the dimension of size 1 in its dimension through squeeze(dim=1) to obtain output; calculate the loss value loss, use the previously defined criterion, pass in the three outputs of the model, and the three target values ​​in the target value list; then call loss.backward() and optimizer.step() to calculate the gradient of loss to model parameters and update the model parameters according to the gradient; finally, return the calculated loss value loss;

[0111] Step 3.2: Create and parse command line arguments through create_train_arg_parser().parse_args() and store them in args; set the CUDA_SELECT variable to choose whether to use the GPU to run the model; here, select the GPU number according to the value of args.cuda_no. If the value of args.cuda_no is cpu or the GPU is not available, use the CPU to run; set the path and related configuration of the log file, configure the format, level and other information of the log file through logging.basicConfig(), and record blank lines to distinguish different log records; get the list of file names of the training set and the validation set, and randomly shuffle the file names of the training set for subsequent data loading; use the torch.device() function to specify the device on which the model runs, call the build_model(args.model_type) function to build the model, and select the corresponding model according to the model type in the command line parameter;

[0112] Step 3.3: If args.use_pretrained is true, load the pretrained model; print out the file name of the pretrained model being loaded, and parse the training epoch according to the file name so that you can start from the correct epoch in subsequent training; create trainLoader, devLoader, and displayLoader, which are DataLoaders for training data, validation data, and display data, respectively; the data loader uses the DatasetImageMaskContourDist class to customize the way the dataset is loaded, and specifies the corresponding batch size; initialize the optimizer optimizer, use the Adam optimizer, and pass the model parameters and learning rate as parameters to the optimizer; define the loss function criterion, here call the define_loss function to select the corresponding loss function according to the model;

[0113] Step 3.4: Use the range() function to generate an iteration range, starting from int(epoch_start)+1 to int(epoch_start)+1+args.num_epochs-1; epoch_start is the epoch of the previously loaded pre-trained model, which is converted to an integer by int(epoch_start)+1 and added by 1 to get the next epoch to start; then use the tqdm() function to wrap this range to implement a progress bar that can display the training progress in the command line interface; at each epoch of the loop iteration, the progress bar will be updated to show the current progress;

[0114] Step 3.5: Calculate the global step number global_step by multiplying the current epoch number by the length of the training data loader; this value is used to record the number of steps for each parameter update during training for subsequent analysis and visualization; initialize running_loss to 0.0 to accumulate the total loss of each epoch; use enumerate(trainLoader) to traverse the training data loader, obtain each mini-batch of data, and train it; in each mini-batch loop: set the model to training mode, move the data to the specified device, call the train_model function for model training, pass in the model, target value, model type, loss function, and optimizer, and calculate the loss of the mini-batch data, and then use writer.add_scalar() to write the loss value to the TensorBoard log for subsequent visualization analysis; multiply the loss of the mini-batch data by the size of the input data and accumulate it in running_loss to calculate the average loss of each epoch; calculate the average loss epoch_loss of each epoch, which will be obtained by dividing running_loss by the total number of samples in the training dataset;

[0115] Step 3.6: Whenever the value of epoch is divisible by 1, that is, at the end of each epoch, do the following: first call the evaluate() function to evaluate the validation set, calculate the loss dev_loss of the validation set and the time dev_time used for evaluation; then use writer.add_scalar() to write the validation set loss to the TensorBoard log; then call the visualize() function to visualize the display data set so that the output of the model can be viewed in TensorBoard; print the current global loss and validation set loss information; otherwise (if the value of epoch is not divisible by 1), only print the current global loss; use logging.info() to record the training loss of each epoch; whenever the value of epoch is divisible by 5, do the following:

[0116] Use the torch.save() function to save the parameters of the current model to the specified file path so that you can load the model and continue training when needed.

[0117] Furthermore, the step 4 is specifically as follows:

[0118] Step 4.1: Create and parse command line arguments through create_validation_arg_parser().parse_args() and store them in args; construct the path val_path of the validation data set. Here, the os.path.join() function is used to connect the test image folder path and the file extension *.jpg for subsequent use in loading validation data; define the model file path model_file, using args.model_file, define the save path save_path, which is used to save the model's output results or other related information, and define the model type model_type;

[0119] Step 4.2: Get the CUDA device number cuda_no; construct the CUDA device selection string CUDA_SELECT according to cuda_no to select which CUDA device to run the model on. If cuda_no is "cuda:0", CUDA_SELECT is "cuda:0"; if cuda_no is "cuda:1", CUDA_SELECT is "cuda:1", and so on; use the torch.cuda.is_available() function to check whether the current system supports CUDA. If supported, select the CUDA device; otherwise, select the CPU device;

[0120] According to the selected device, set it as the default device used; use the glob.glob() function to get all file names that match the specified file extension according to the given path val_path, and store the results in the list val_file_names; create a verification data loader valLoader, use the DataLoader class, the dataset is constructed by the DatasetImageMaskContourDist class, pass in the verification data file name list val_file_names and the distance type "dist_contour";

[0121] Step 4.3: Use the os.path.exists(save_path) function to check whether the specified save path save_path exists; if the save path does not exist, use the os.mkdir(save_path) function to create the path so that the model output or other related information can be saved later; call the build_model(model_type) function to build the model, and choose to build the corresponding model according to the specified model type model_type; move the built model to the specified device, using the model.to(device) function; use the torch.load() function to load the pre-trained model parameters from the specified file path and apply the loaded parameters to the model; call the model.eval() method to set the model to evaluation mode;

[0122] Step 4.4: Use enumerate(tqdm(valLoader)) to traverse each batch of data in the verification data loader valLoader; each batch of data includes the image file name img_file_name, the model input inputs, and three target values ​​targets1, targets2, and targets3; move the input data inputs to the specified device; input the input data inputs into the model for inference to obtain the three outputs outputs1, outputs2, and outputs3 of the model; take the output data of the model out of the device and convert it into a NumPy array for subsequent processing; generate the corresponding mask image res according to the output of the model; find the index of the category with the maximum probability through the np.argmax() function, and then set the pixel value to the corresponding category according to the index; construct the save path output_path of the mask image, name it "mask_" + the original image file name, and save the mask image to the specified save path; finally, use OpenCV's cv2.imwrite() function to save the mask image as an image file.

[0123] Furthermore, the tool functions used in the U-shaped network are specifically:

[0124] Define a function evaluate for evaluating model performance. model.eval() sets the model to evaluation mode, creates an empty list losses to store the loss value of each iteration, records the current time, and calculates the total time of the evaluation. Then, use the torch.no_grad() context manager to disable gradient calculation to reduce memory consumption and speed up calculation. Use the enumerate function to traverse each iteration in the data loader data_loader, obtain the iteration number iter and data data at the same time, unpack the data to obtain the input data inputs and target data targets. Move the input data and target data to the specified device, and then use the model to infer the input data to obtain the output result outputs. Use the binary cross entropy loss function nn.BCEWithLogitsLoss() to compare the model output outputs[0] with the target data targets and calculate the loss value. Add the loss value of the current iteration to the loss list, and then use the writer to write the average loss value of the validation set to TensorBoard for subsequent analysis and comparison. Finally, return the average loss value of the validation set and the total time of the evaluation.

[0125] Define a function visualize to visualize the model output, define save_image to save the image and add it to TensorBoard, the function accepts image data image, label tag and validation set batch size val_batch_size as parameters; then normalize the image data so that its pixel value range is between 0 and 1; then use the torchvision.utils.make_grid function to convert the image data into a grid for visualization, use writer to add the image grid to TensorBoard, identify it with label tag, and specify the current number of training rounds epoch;

[0126] Use model.eval() to set the model to evaluation mode, use the torch.no_grad() context manager, use the enumerate function to traverse each iteration in the data loader data_loader, and get the iteration number iter and data data, input data inputs and target data targets; move the input data and target data to the specified device, and use the model to infer the input data to get the output data outputs; convert the tensor output by the model to a NumPy array and assign it to the output_mask variable, find the index of the maximum value on the first dimension of the output_mask array, convert it to a floating point type, assign it to the output_final variable, convert the output_final array to a tensor, and add a dimension to the second dimension; check whether the model is in training mode, call the save_image function, save the target data and model prediction results of the training set and add them to the visualization tool, using the label "Target_train" and "Prediction_train"; if not in training mode, call the save_image function to save the target data and model prediction structure of the validation set and add them to the visualization tool, using the labels "Target" and "Prediction" for identification; after processing the first iteration, jump out of the loop and visualize only one batch of data;

[0127] Create a training parameter parser function create_train_arg_parser(), which contains a series of parameters for training settings, including: --train_path, specifies the path of the training dataset; --val_path, specifies the path of the validation dataset; --model_type, selects the model type to be used; --object_type, specifies the type of dataset; --distance_type, selects the distance transformation type, the default is 'dist_contour', and the options include 'dist_mask', 'dist_contour', 'dist_signed'; --batch_size, specifies the size of the training batch; --val_batch_size, specifies the size of the validation batch; --num_epochs, specifies the number of training rounds; --cuda_no, specifies the CUDA device number to be used; --use_pretrained, specifies whether to load pre-trained model parameters; --pretrained_model_path, if use_pretrained is set to True, specifies the path of the pre-trained model; --save_path, specifies the path to save the trained model;

[0128] Create a parameter parser object create_validation_arg_parser() function for parsing validation parameters, which includes a series of parameters for validation settings, including: --model_type selects the model type to be used; --val_path specifies the path of the validation dataset; --model_file specifies the model file path to be loaded; --save_path specifies the save path of the validation results; --cuda_no specifies the CUDA device number to be used, the default is 0; finally, the created parameter parser object is returned.

[0129] The technical scheme and technical effects of the present invention are further described below in conjunction with specific experimental data. Figure 3 Shown is the final segmentation result.

[0130] It can be seen that the optic cup and optic disc regions segmented by the present invention are relatively smooth and regular, with a small difference from the true value, and can perform relatively complete segmentation of the two target regions of the optic cup and optic disc, and the boundary information and shape information of the target region are also effectively retained.

[0131] Embodiment 2

[0132] This embodiment provides a fundus image optic cup and optic disc segmentation system based on deep learning. The system uses the fundus image optic cup and optic disc segmentation method based on deep learning as described in Example 1. The system includes

[0133] A data acquisition module acquires fundus color images to form a data set, performs image enhancement on the data set, and divides the enhanced data set into a training set and a validation set;

[0134] A U-shaped network construction module, constructing a U-shaped network, wherein the U-shaped network includes a compression encoder path and three scalable decoder paths;

[0135] The network training module inputs the training set into the constructed U-shaped network to train the U-shaped network;

[0136] The network verification module verifies the trained U-shaped network using the verification set, and uses the verified U-shaped network to achieve optic cup and optic disc segmentation of fundus images.

[0137] Embodiment 3

[0138] An embodiment of the present invention provides an electronic device, which includes a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the memory is used to store software programs and modules, and the processor executes various functional applications and data processing by running the software programs and modules stored in the memory. The memory and the processor are connected via a bus. Specifically, the processor implements any step in the first embodiment above by running the computer program stored in the memory.

[0139] It should be understood that in the embodiments of the present invention, the processor referred to may be a central processing unit (CPU), and the processor may also be other general-purpose processors, digital signal processors (DSP), application-specific integrated circuits (ASIC), field-programmable gate arrays (FPGA) or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc. A general-purpose processor may be a microprocessor or the processor may also be any conventional processor, etc.

[0140] The memory may include a read-only memory, a flash memory, and a random access memory, and provides instructions and data to the processor. A part or all of the memory may also include a nonvolatile random access memory.

[0141] It should be understood that if the above-mentioned integrated module / unit is implemented in the form of a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on such an understanding, the present invention implements all or part of the processes in the above-mentioned embodiment method, and can also be completed by instructing the relevant hardware through a computer program. The above-mentioned computer program can be stored in a computer-readable storage medium, and the computer program can implement the steps of the above-mentioned various method embodiments when executed by the processor. Among them, the above-mentioned computer program includes computer program code, and the above-mentioned computer program code can be in source code form, object code form, executable file or some intermediate form. The above-mentioned computer-readable medium may include: any entity or device capable of carrying the above-mentioned computer program code, recording medium, U disk, mobile hard disk, magnetic disk, optical disk, computer memory, read-only memory (ROM), random access memory (RAM), electric carrier signal, telecommunication signal and software distribution medium. It should be noted that the content contained in the above-mentioned computer-readable storage medium can be appropriately increased or decreased according to the requirements of legislation and patent practice in the jurisdiction.

[0142] The above description of the disclosed embodiments enables one skilled in the art to implement or use the present invention. Various modifications to these embodiments will be apparent to one skilled in the art, and the general principles defined herein may be implemented in other embodiments without departing from the spirit or scope of the present invention. Therefore, the present invention will not be limited to the embodiments shown herein, but rather to the widest scope consistent with the principles and novel features disclosed herein.

[0143] Those skilled in the art can clearly understand that, for the convenience and simplicity of description, only the division of the above-mentioned functional units and modules is used as an example for illustration. In practical applications, the above-mentioned function allocation can be completed by different functional units and modules as needed, that is, the internal structure of the above-mentioned device can be divided into different functional units or modules to complete all or part of the functions described above. The functional units and modules in the embodiment can be integrated in a processing unit, or each unit can exist physically separately, or two or more units can be integrated in one unit. The above-mentioned integrated unit can be implemented in the form of hardware or in the form of software functional units. In addition, the specific names of the functional units and modules are only for the convenience of distinguishing each other, and are not used to limit the scope of protection of the present invention. The specific working process of the units and modules in the above-mentioned system can refer to the corresponding process in the aforementioned method embodiment, which will not be repeated here.

[0144] It should be noted that the methods and detailed examples provided in the above embodiments can be combined with the devices and equipment provided in the embodiments, and references can be made to each other, and no further details will be given.

[0145] Those skilled in the art will appreciate that the units and algorithm steps of each example described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, or a combination of computer software and electronic hardware. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution. Professional and technical personnel can use different methods to implement the described functions for each specific application, but such implementation should not be considered to be beyond the scope of the present invention.

[0146] In the embodiments provided by the present invention, it should be understood that the disclosed apparatus / terminal equipment and method can be implemented in other ways. For example, the apparatus / equipment embodiments described above are only illustrative, for example, the division of the above modules or units is only a logical function division, and in actual implementation, other division methods can be used, for example, multiple units or components can be combined or integrated into another system, or some features can be ignored or not executed.

[0147] The above embodiments are only used to illustrate the technical solutions of the present invention, rather than to limit the same. Although the present invention has been described in detail with reference to the above embodiments, those skilled in the art should understand that the technical solutions described in the above embodiments may still be modified, or some of the technical features may be replaced by equivalents. Such modifications or replacements do not deviate the essence of the corresponding technical solutions from the spirit and scope of the technical solutions of the embodiments of the present invention, and should be included in the protection scope of the present invention.

Claims

1. A method for segmenting optic cup and optic disc of fundus images based on deep learning, characterized in that: The method for segmenting the optic cup and optic disc of fundus images comprises the following steps: Step 1: Obtain fundus color images to form a data set, perform image enhancement on the data in the data set, and divide the enhanced data set into a training set and a validation set; Step 2: construct a U-shaped network, wherein the U-shaped network includes a compression encoder path and three scalable decoder paths; Step 3: Input the training set of step 1 into the U-shaped network constructed in step 2 to train the U-shaped network; Step 4: Verify the U-shaped network trained in step 3 using the verification set in step 1, and use the verified U-shaped network to achieve optic cup and optic disc segmentation of fundus images; The step 4 is specifically as follows: Step 4.1: Create and parse command line arguments through create_validation_arg_parser().parse_args() and store them in args; construct the path val_path of the validation dataset; define the model file path model_file, define the save path save_path, and define the model type model_type; Step 4.2: Get the CUDA device number cuda_no; construct the CUDA device selection string CUDA_SELECT according to cuda_no. If cuda_no is "cuda:0", CUDA_SELECT is "cuda:0"; if cuda_no is "cuda:1", CUDA_SELECT is "cuda:1", and so on; use the torch.cuda.is_available() function to check whether the current system supports CUDA. If it does, select the CUDA device; otherwise, select the CPU device; According to the selected device, set it as the default device used; use the glob.glob() function to get all file names that match the specified file extension according to the given path val_path, and store the results in the list val_file_names; create a verification data loader valLoader, use the DataLoader class, the dataset is constructed by the DatasetImageMaskContourDist class, pass in the verification data file name list val_file_names and the distance type "dist_contour"; Step 4.3: Use the os.path.exists(save_path) function to check whether the specified save path save_path exists; if the save path does not exist, use the os.mkdir(save_path) function to create the path; call the build_model(model_type) function to build the model, and choose to build the corresponding model according to the specified model type model_type; move the built model to the specified device, using the model.to(device) function; use the torch.load() function to load the pre-trained model parameters from the specified file path and apply the loaded parameters to the model; call the model.eval() method to set the model to evaluation mode; Step 4.4: Use enumerate(tqdm(valLoader)) to traverse each batch of data in the verification data loader valLoader; input the input data inputs into the model for inference to obtain the three outputs outputs1, outputs2, and outputs3 of the model; take the output data of the model from the device and convert it into a NumPy array; generate the corresponding mask image res according to the output of the model; find the index of the category with the maximum probability through the np.argmax() function, and then set the pixel value to the corresponding category according to the index; construct the save path output_path of the mask image, name it "mask_" + the original image file name, and save the mask image to the specified save path; finally, use OpenCV's cv2.imwrite() function to save the mask image as an image file.

2. The method for segmenting the optic cup and disc of fundus images according to claim 1, characterized in that: The step 1 specifically comprises: Step 1.1: Import the required libraries; Step 1.2: Create a DatasetImageMaskContourDist(Dataset), define __init__, accept two parameters: file_names and distance_type, which represent the file name and the string, which includes the distance type to be loaded; define __len__, which returns the length of the dataset; define __getitem__, use load_image, load_mask, load_contour, and load_distance functions to load image, mask, contour, and distance data; finally, return a tuple containing the image file name, image, mask, contour, and distance; Step 1.3: Define the load_image(path) function, call Image.open(path) to open the image file at the specified path and load it as a PIL image object; the transforms.Compose() function defines the image transformation operation and finally returns the image; Step 1.4: Define the load_mask(path) function; Step 1.5: Define the load_contour(path) function, the same as step 1.4; Step 1.6: Define the load_distance(path,distance_type) function.

3. The method for segmenting the optic cup and disc of fundus images according to claim 2, characterized in that: The step 2 is specifically as follows: Step 2.1: Define the __init__() function; Step 2.2: Call the super().__init__() function, assign the passed num_classes parameter to the instance variable self.num_classes to represent the number of task categories, and use assert to ensure that the lengths of the down_filter_factors and up_filter_factors lists are equal; then call the self.module method, create a module object, pass in input_channels and down_filter_sizes[0] and add them to the self.down list; Step 2.3: Use a for loop to create the convolutional layers in the downsampling path; Step 2.4: Create a maximum pooling layer object pool; MaxPool2d performs the maximum pooling operation; Step 2.5: First add a None to the self.downsamplers list, and then copy the pool pooling layer to match the number of convolutional layers in the downsampling path; assign pool_bottom to the last element of self.downsamplers; self.upsamplers1, self.upsamplers2, self.upsamplers3, these lists are used to store the upsampling layers in the upsampling path; the elements in each list are the same upsampling layers, used to match the number of convolutional layers in the upsampling path; the last element is assigned to upsample_bottom1, upsample_bottom2 and upsample_bottom3 for upsampling of the bottom part; Step 2.6: If the add_output variable is of type True, an output layer is added to the UNet network; the final convolutional layers self.conv_final1, self.conv_final2, and self.conv_final3 are used to generate the output of the model; Step 2.7: Use the forward propagation method forward(self,x) to receive an input tensor x, process it and return the output; Step 2.8: Set up three sets of for loops. Each set of for loops traverses from the bottom of the upsampling path upwards. In the first set of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers1 contains the upsampling layer of the first set of upsampling paths, and self.up contains the convolutional layer of the upsampling path. In the second group of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers2 contains the upsampling layers of the second group of upsampling paths, and self.up contains the convolutional layers of the upsampling paths; In the third group of for loops, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers3 contains the upsampling layers of the third group of upsampling paths, and self.up contains the convolutional layers of the upsampling paths; Step 2.9: Use self.add_output to check whether output is needed; Step 2.10: Define a class named LossPsiNet; the class initialization method __init__ accepts a parameter weights, which defaults to [1,1,1]; during the initialization process, create three loss function objects: self.criterion1 and self.criterion2 are instances of the LossMulti class, and the num_classes parameter is set to 2; self.criterion3 is the mean square error loss function nn.MSELoss() in PyTorch; in the class's __call__ method, accept six parameters outputs1, outputs2, outputs3, targets1, targets2, targets3, which represent the output of the model and the corresponding target value respectively; return the final weighted loss value criterion.

4. The method for segmenting the optic cup and disc of fundus images according to claim 3, characterized in that: The step 2.8 is specifically as follows: Step 2.8.1: Set up a for loop to traverse from the bottom of the upsampling path upwards; in each iteration, it traverses three lists at the same time: xs[:-1], self.upsamplers1, self.up, which contain the feature maps of the downsampling path except the last layer, the upsampling layer, and the convolution layer respectively; x_skip is the feature map of the downsampling path, which is connected to the input of the current upsampling layer; apply the current upsampling layer upsample to x_out1 to increase the spatial resolution of the feature map; then use the torch.cat function to concatenate the upsampled feature map x_out1 with the feature map x_skip of the downsampling path in the channel dimension; finally, pass the concatenated feature map to the current upsampling convolution layer up to generate a new x_out1 feature map, which will be used for the next iteration until the top of the upsampling path; Step 2.8.2: Set up a second for loop, similar to the loop in step 2.8, but it iterates over another set of upsampling path layers; xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers2 contains another set of upsampling layers of the upsampling path, and self.up still contains the convolutional layers of the upsampling path; Step 2.8.3: Set up the third for loop, similar to the loops in steps 2.8 and 2.9, xs[:-1] contains the feature maps of the downsampling path except the last layer, self.upsamplers3 contains another set of upsampling layers of the upsampling path, and self.up still contains the convolutional layers of the upsampling path.

5. The method for segmenting the optic cup and disc of fundus images according to claim 4, characterized in that: The step 3 is specifically as follows: Step 3.1: Define the training model function. First, check model_type through the conditional statement. If it is, perform the following operations, otherwise skip; the specific execution is to first call optimizer.zero_grad() to clear the previous parameter gradients, and then set the gradient calculation to on through torch.set_grad_enabled(True) to ensure that the model parameter gradients can be calculated. Then use the model model to forward propagate the input data inputs to obtain the model output outputs; extract the third output from outputs, and remove the dimension of size 1 in its dimension through squeeze(dim=1) to obtain output; calculate the loss value loss, use the previously defined criterion, pass in the three outputs of the model, and the three target values ​​in the target value list; then call loss.backward() and optimizer.step() to calculate the gradient of the loss to the model parameters and update the model parameters according to the gradient; finally, return the calculated loss value loss; Step 3.2: Create and parse command line arguments through create_train_arg_parser().parse_args() and store them in args; set the CUDA_SELECT variable. If the value of args.cuda_no is cpu or GPU is not available, use the CPU to run; set the path and related configuration of the log file, and record blank lines to distinguish different log records; get the list of file names of the training set and the validation set, and randomly shuffle the file names of the training set; use the torch.device() function to specify the device on which the model runs, call the build_model(args.model_type) function to build the model, and select the corresponding model according to the model type in the command line parameter; Step 3.3: If args.use_pretrained is true, load the pretrained model; create trainLoader, devLoader, and displayLoader; initialize the optimizer optimizer; define the loss function criterion; Step 3.4: Use the range() function to generate an iteration range, starting from int(epoch_start)+1 and ending at int(epoch_start)+1+args.num_epochs-1. At each epoch of the loop iteration, the progress bar will be updated to show the current progress. Step 3.5: Calculate the global step number global_step; Initialize running_loss to 0.0; Use enumerate(trainLoader) to traverse the training data loader, obtain each small batch of data, and train it; In the loop of each small batch of data: Set the model to training mode, then move the data to the specified device, call the train_model function for model training, pass in the model, target value, model type, loss function and optimizer, and calculate the loss of the small batch of data, and then use writer.add_scalar() to write the loss value to the TensorBoard log; Multiply the loss of the small batch of data by the size of the input data and accumulate it in running_loss; Calculate the average loss epoch_loss of each epoch; Step 3.6: Whenever the value of epoch is divisible by 1, first call the evaluate() function to evaluate the validation set, calculate the validation set loss dev_loss and the evaluation time dev_time; then use writer.add_scalar() to write the validation set loss to the TensorBoard log; then call the visualize() function to visualize the display data set so that the output of the model can be viewed in TensorBoard; print the current global loss and validation set loss information; Otherwise, only the current global loss is printed; Use logging.info() to record the training loss for each epoch; whenever the epoch value is divisible by 5, do the following: Use the torch.save() function to save the parameters of the current model to the specified file path.

6. The method for segmenting the optic cup and disc of fundus images according to claim 2, characterized in that: The tool functions used in the U-type network are specifically: Define a function evaluate to evaluate model performance; Define a function visualize to visualize the model output; Use model.eval() to set the model to evaluation mode, use the torch.no_grad() context manager, use the enumerate function to traverse each iteration in the data loader data_loader, and get the iteration number iter and data data, input data inputs and target data targets; use the model to infer the input data to get the output data outputs; convert the tensor output by the model to a NumPy array and assign it to the output_mask variable, find the index of the maximum value on the first dimension of the output_mask array, convert it to a floating point type, and assign it to output_final Variable, convert the output_final array to a tensor and add a dimension to the second dimension; check if the model is in training mode, call the save_image function, save the target data and model prediction results of the training set and add them to the visualization tool, using the labels "Target_train" and "Prediction_train" for identification; if it is not in training mode, call the save_image function, save the target data and model prediction structure of the validation set and add them to the visualization tool, using the labels "Target" and "Prediction" for identification; after processing the first iteration, jump out of the loop and visualize only one batch of data; Create a training parameter parser function create_train_arg_parser(); Create a parameter parser object create_validation_arg_parser() function for parsing validation parameters, including: --model_type selects the model type to be used; --val_path specifies the path of the validation dataset; --model_file specifies the model file path to be loaded; --save_path specifies the save path of the validation results; --cuda_no specifies the CUDA device number to be used, the default is 0; finally, return the created parameter parser object.

7. A fundus image optic cup and optic disc segmentation system based on deep learning, characterized in that: The system uses the deep learning-based fundus image optic cup and optic disc segmentation method as described in any one of claims 1 to 6, and the system includes A data acquisition module acquires fundus color images to form a data set, performs image enhancement on the data set, and divides the enhanced data set into a training set and a validation set; A U-shaped network construction module, constructing a U-shaped network, wherein the U-shaped network includes a compression encoder path and three scalable decoder paths; The network training module inputs the training set into the constructed U-shaped network to train the U-shaped network; The network verification module verifies the trained U-shaped network using the verification set, and uses the verified U-shaped network to achieve optic cup and optic disc segmentation of fundus images.

8. A computer device, characterized in that: The method comprises a memory, a processor and a computer program stored in the memory and executable on the processor, wherein when the processor executes the computer program, the method according to any one of claims 1 to 6 is implemented.

9. A computer-readable storage medium having a computer program stored thereon, characterized in that: The program is executed by a processor to implement the method according to any one of claims 1 to 6.