Water level monitoring method based on deep learning

Through deep learning technology, an automated water level line monitoring method is built, which solves the inaccuracy problem caused by relying on manual labor in traditional water level line monitoring, and realizes efficient and accurate water level line detection, supporting water resource management and disaster prevention.

CN118887374APending Publication Date: 2024-11-01WEIHAI INST OF IND TECH SHANDONG UNIV +1
View PDF 0 Cites 6 Cited by

Patent Information

Application Number
CN202411023294.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-07-29
Publication Date
2024-11-01

AI Technical Summary

Technical Problem

Traditional water level monitoring methods rely on manual observation, which is time-consuming and subjective, resulting in inaccurate monitoring data and difficult to meet the needs of modern water resource management.

Method used

Using deep learning-based water level line monitoring method, the construction and optimization of image preprocessing, data augmentation, feature extraction and recognition model construction and optimization, image distortion correction and inverse perspective transformation, combined with U-Net++ and VGGBlock models, the BCEDiceLoss loss function is used, and the Gradient descent algorithm trains the model to realize automated water level line detection.

Benefits of technology

It improves the accuracy and automation of water level monitoring, reduces the need for manual monitoring, and supports water resource security management and disaster prevention.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118887374A_ABST
    Figure CN118887374A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of deep learning, and particularly provides a water level monitoring method based on deep learning. The method comprises the steps of image preprocessing and data enhancement; constructing a feature extraction and recognition model; adopting BCEDiceLoss as a loss function, and optimizing the feature extraction and recognition model to obtain an optimized feature extraction and recognition model; carrying out image distortion correction and inverse perspective transformation; training the feature extraction and recognition model; and water level detection and feature extraction and identification model evaluation. According to the method, the deep learning model is used for analyzing and recognizing the water level line images, complex and effective features can be automatically learned from a large number of water level line images, the accuracy and automation degree of water level monitoring are improved, the requirement for manual monitoring is reduced, and guarantee management and disaster prevention of water resources are effectively supported.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of deep learning technology, and in particular to a water level monitoring method based on deep learning. Background Art

[0002] Accurate recognition of water level images is a key link in hydrological monitoring and management, and it is also one of the major challenges in the field of water level monitoring. For a long time, hydraulic engineers and researchers have been exploring effective water level monitoring methods. However, traditional water level monitoring mainly relies on manual observation, which is not only time-consuming and subjective, but may lead to inaccurate monitoring data and even serious misjudgment. Therefore, the efficiency and accuracy of manual monitoring alone cannot meet the needs of modern water resources management.

[0003] At present, although there are some water level automatic recognition methods based on traditional image processing technology, these methods often require professionals to design and extract features, which is cumbersome and time-consuming, and these methods are usually separated in feature extraction and classification recognition. In addition, due to the reliance on manually extracted features, these methods do not perform well in terms of water level recognition accuracy, model generalization ability and robustness. Summary of the invention

[0004] In view of this, the present invention provides a water level monitoring method based on deep learning, which is used to improve the accuracy and automation of water level monitoring, reduce the need for manual monitoring, and effectively support water resource security management and disaster prevention.

[0005] In a first aspect, the present invention provides a water level monitoring method based on deep learning, the method comprising:

[0006] Step 1: Image preprocessing and data enhancement: Preprocess the water body images captured by the field camera to optimize the image quality; apply data enhancement technology to the training set by random rotation, flipping and scaling to obtain the first processed image;

[0007] Step 2: Build a feature extraction and recognition model: By combining the advanced deep learning model U-Net++ and the VGGBlock convolutional block, a feature extraction and recognition model is obtained;

[0008] Step 3: Use BCEDiceLoss as the loss function to optimize the feature extraction and recognition model to obtain the optimized feature extraction and recognition model;

[0009] Step 4, image distortion correction and inverse perspective transformation: using inverse perspective transformation and distortion correction technology, the image after the first processing is subjected to distortion correction and inverse perspective transformation to obtain the image after the second processing;

[0010] Step 5, training the feature extraction and recognition model: through an iterative training process, using a gradient descent algorithm, the feature extraction and recognition model is trained using the image after the second processing to obtain a trained feature extraction and recognition model;

[0011] Step 6: Water level detection and feature extraction and recognition model evaluation: Use the trained feature extraction and recognition model to perform water level detection, and perform performance evaluation on the feature extraction and recognition model under the evaluation index.

[0012] Optionally, step 1 includes:

[0013] Step 11: Image cropping and adjustment: First, the size of the original image is cropped from 1024×768 pixels to a central area of ​​500×500 pixels; then the cropped image is adjusted to a standard size of 256×256 pixels. The expressions for cropping and adjusting ResizedImage are:

[0014] ResizedImage=Resize(Crop(1024,768),256,256);

[0015] Resize(·) means adjusting the cropped image to a standard size for subsequent processing or analysis; Crop(·) means cropping the redundant parts of the image and retaining only the most important area, that is, the area of ​​interest or the target area;

[0016] Step 12: Perform adaptive grayscale histogram equalization on the cropped and adjusted image; the expression of adaptive grayscale histogram equalization is:

[0017]

[0018] Among them, r k Represents the gray level of the original image, p ′ (r k ) represents the new gray level of the equalized image;

[0019] Step 13, adjust brightness and contrast: set the brightness adjustment factor of the original image to 10, and the contrast adjustment factor to 1.2; the brightness and contrast of the original image are expressed as I orig , image I after adjusting brightness and contrast adj Expressed as: I adj =1.2×I orig +10;

[0020] The expression of grayscale linear transformation is:

[0021] Iout=a·Iin+b;

[0022] Among them, Iin represents the gray value of the input original image, and Iout represents the gray value of the output image; parameter a controls the slope of the transformation and affects the contrast of the image, and parameter b represents the Y-axis intercept and affects the brightness of the image;

[0023] Step 14: Image noise reduction: Apply a Gaussian filter with a standard deviation of 1.5 to remove noise from the image; the Gaussian filter G(x,y,1.5) is used for noise reduction. The image after noise reduction is expressed as: denoise =I orig *G(x,y,1.5);

[0024] Assume f(x,y) is the original image and g(x,y) is the image after Gaussian filtering. The expression of Gaussian filtering is:

[0025]

[0026] Among them, w(s,t) represents the weight of the Gaussian filter; a and b are used to define the size of the Gaussian filter;

[0027] w(s,t) is calculated from Gaussian distribution and its expression is:

[0028]

[0029] Among them, σ represents the standard deviation of the Gaussian filter and controls the smoothness of the filter;

[0030] Step 15: Data enhancement: The image is rotated 30 degrees clockwise and counterclockwise, flipped horizontally, flipped vertically, and scaled 0.8 to 1.2 times. The enhanced image I aug The expression is:

[0031] I aug =T(I orig );

[0032] Where T represents the image transformation operation.

[0033] Optionally, the step 2 includes:

[0034] Step 21. Construct VGGBlock convolution block: Initialize VGGBlock convolution block. First, define input channel in_channels, middle channel middle_channels and output channel out_channels. Input channel is used to define the number of image channels input to VGGBlock, which is 3 for RGB image. Middle channel is used to define the number of channels between two convolution operations. It is an internal parameter used to transfer features between convolution layers. Output channel is used to define the number of channels output by VGGBlock, which determines the number of channels of the image after passing through VGGBlock.

[0035] Initialize the ReLU activation function and batch normalization layer. The ReLU activation function is initialized using nn.ReLU(inplace=True) to add nonlinearity. The inplace=True parameter will modify the input data in place. The batch normalization layer initializes the intermediate layer and the output layer nn.BatchNorm2d layers, corresponding to the number of intermediate channels and output channels respectively.

[0036] Step 22, VGGBlock forward propagation:

[0037] (a) The first convolution operation: The first convolution layer uses nn.Conv2d(in_channels, middle_channels, kernel_size = 3, padding = 1) to initialize the convolution layer, with a kernel size of 3×3 and an edge padding of 1 to keep the image size unchanged; batch normalization and ReLU activation: After applying batch normalization nn.BatchNorm2d(middle_channels), the ReLU activation function nn.ReLU(inplace = True) is used to activate the intermediate features;

[0038] For the convolutional layer, the expression is:

[0039] O = ReLU(BN(W*I+b));

[0040] Where: O represents the output feature map Output Feature Map; I represents the input feature map Input Feature Map; W represents the convolution kernel Kernel; * represents the convolution operation; b represents the bias term (Bias); BN represents the batch normalization operation; ReLU represents the activation function, which is defined as ReLU(x)=max(0,x);

[0041] (b) Second convolution operation: The second convolution layer uses nn.Conv2d(middle_channels, out_channels, kernel_size=3, padding=1), keeping the convolution kernel size and edge padding unchanged; batch normalization and ReLU activation: apply batch normalization nn.BatchNorm2d(out_channels), and use ReLU activation function nn.ReLU(inplace=True) to activate output features;

[0042] The batch normalization operation expression is:

[0043]

[0044] Where: x represents the output of the convolutional layer; μ represents the mean value within the batch; σ 2 represents the variance within the batch; ∈ represents a positive parameter; γ and β represent learned parameters for rescaling and offsetting the normalized values;

[0045] Final output: The output after the last ReLU activation is regarded as the final output of the VGGBlock convolution block and is used in subsequent network layers or as a feature map;

[0046] Step 23: Build the U-Net++ network structure:

[0047] (c) Network initialization: define the number of filters at different levels as [32, 64, 128, 256, 512], which will determine the feature extraction capability of each level; initialize the encoder layer conv_{i,0} and the decoder layer conv_{i,j} of U-Net++ to ensure feature extraction and processing;

[0048] (d) Encoder path, the input image I first passes through the first encoder level conv_{0,0}, which is the starting point of feature extraction; next, for the output of each encoder level, the maximum pooling operation MaxPool is performed to reduce the dimension of the feature map and increase the level of abstraction; this continues until the last encoder level conv_{4,0}, each level can capture different levels of image features;

[0049] (e) Decoder path: First, the output of the deepest encoder is upsampled to increase the dimension of the feature map. The upsampled features are concatenated with the features of the corresponding encoder level through skip connections to preserve spatial information. The fused features are processed through the convolutional layers of the decoder to gradually reconstruct the feature map. This process is repeated in different decoder levels to gradually reconstruct high-resolution feature maps.

[0050] (f) Output layer: At the end of the network, the final output of the decoder is passed through a convolutional layer to convert the number of channels of the feature map into the number of target categories; a softmax or sigmoid activation function is used to assign a probability or classification to each pixel;

[0051] (g) Deep supervision. When deep supervision is enabled, the intermediate layers of the network will produce additional outputs. The auxiliary outputs help the network focus on deeper features during training. By calculating the loss of the auxiliary outputs and combining it with the main loss function, the model representation can learn complex features.

[0052] Optionally, step 3 includes:

[0053] The goal of BCEDiceLoss loss function optimization is to minimize BCEDiceLoss to balance the classification accuracy of a single pixel and the continuity of the entire prediction area; its specific calculation includes:

[0054] Binary cross entropy loss BCE, its expression is:

[0055]

[0056] where y i represents the true label, y i预测 represents the predicted probability;

[0057] Dice loss is used to evaluate the spatial overlap between the predicted region and the true label, and its expression is:

[0058]

[0059] Here, smooth is a smoothing term used to avoid division by zero errors.

[0060] The expression of the combined loss function BCEDiceLoss is:

[0061] BCEDiceLoss=α·BCE+(1-α)·Dice;

[0062] The parameter α is used to weigh the importance of BCE loss and Dice loss.

[0063] Optionally, step 4 includes:

[0064] Step 41: Image distortion correction:

[0065] Load the camera calibration image, and obtain the checkerboard image used for camera calibration by loading the camera calibration image; use the Glob library to obtain the file path of the camera calibration image;

[0066] Find the corners of the chessboard, use the camera calibration image, and use OpenCV's cv2.findChessboardCorners function to find the corners of the chessboard;

[0067] Calibrate the camera and remove image distortion. Use the corner points of the chessboard and the corresponding real coordinate points to calibrate the camera. Calculate the camera matrix and distortion coefficients of the camera through the cv2.calibrateCamera function, and then use the cv2.undistort function to correct the image distortion. The distortion coefficients are expressed in polynomial form to represent the camera distortion, which includes radial distortion k1, k2, k3 and tangential distortion p1, p2. The expression of the camera matrix K is:

[0068]

[0069] Among them, f x and f y is the focal length, (c x ,c y ) are the pixel coordinates of the optical center;

[0070] Step 42: Image reverse perspective:

[0071] Select the key points of the inverse perspective transformation. The inverse perspective transformation requires four non-collinear points, which are expressed as P = {(x1, y1), (x2, y2), (x3, y3), (x4, y4)}. The four non-collinear points are selected on the original image to form the basis of the inverse perspective transformation and define the perspective area of ​​the image;

[0072] Calculate the inverse perspective transformation matrix. The calculation of the inverse perspective transformation matrix is ​​based on the four key points in the selected original image and the four corresponding vertices of the target image. The inverse perspective transformation matrix is ​​obtained by solving a system of linear equations, using the relationship between the four points in the original image and the corresponding vertices of the target image. The four points P in the original image original ={(x1,y1),(x2,y2),(x3,y3),(x4,y4)}, the corresponding four vertices P in the target image target ={(u1,v1),(u2,v2),(u3,v3),(u4,v4)}, the inverse perspective transformation matrix M is calculated by the cv2.getPerspectiveTransform function, which is a 3x3 matrix; the inverse perspective transformation matrix M is obtained by solving the following linear equations:

[0073]

[0074] Among them, the M matrix represents the mapping relationship between the points in the original image and the corresponding points in the target image, thereby realizing the inverse perspective transformation;

[0075] Perform inverse perspective transformation. The inverse perspective transformation function cv2.warpPerspective transforms the original image according to the calculated inverse perspective transformation matrix M. Given the original image I original And the inverse perspective transformation matrix M, perform the inverse perspective transformation to obtain the transformed image I transformed , whose expression is:

[0076] I transformed =cv2.warpPerspective(I original ,M,target_size);

[0077] Where target_size represents the target image size of the desired output; the inverse perspective transformation function uses the inverse perspective transformation matrix M to transform the original image I original Map to a new perspective or geometry to generate a transformed image I transformed ;

[0078] Image processing and synthesis: After the inverse perspective transformation, the transformed image and the original image are processed and synthesized to obtain the final image after correcting the perspective distortion; the image is segmented and merged using the mask and the inverse mask; the mask is a matrix of the same size as the image, which is used to identify the area that needs to be inversely transformed; the inverse mask is the complement of the mask, which is used to retain the area that has not been transformed; the image after inverse perspective transformation is separated from the original image through the bit operation function, and merged in the appropriate area to obtain the final processed image; its expression is:

[0079] masked_dst=cv2.bitwise_and(I transformed ,mask);

[0080] masked_img=cv2.bitwise_and(I original ,inverse_mask);

[0081] final_img=cv2.add(masked_dst, masked_img);

[0082] Among them, I transformed I represents the image after inverse perspective transformation; originalRepresents the original image; mask represents the mask of the inverse perspective transformed area; inverse_mask represents the inverse mask of the untransformed area; masked_dst represents the area after the inverse perspective transformed image is applied with the mask; masked_img represents the area after the inverse mask is applied to the original image; final_img represents the final image that merges the transformed area and the untransformed area.

[0083] Optionally, step 5 includes:

[0084] Step 51, initialize the training configuration: set the training cycle epochs, which indicates the number of times the network will traverse the entire data set during training; set the batch size batch_size, which indicates the number of samples used for one training, affecting gradient estimation and memory usage;

[0085] Step 52, optimizer selection and configuration: select optimizer to determine the weight of the updated network; set the learning rate lr to control the step size of the weight adjustment; set momentum for SGD, which helps to accelerate the optimization of SGD in the relevant direction and suppress oscillation; weight decay weight_decay is a regularization term used to prevent overfitting;

[0086] Step 53, training loop:

[0087] Forward propagation: input data passes through the network and calculates the output of each layer; loss calculation: use the loss function to calculate the difference between the predicted result and the true label; backward propagation: calculate the gradient of the loss function with respect to the network weight; gradient descent: update the network weight according to the calculated gradient; the update rule is defined by the optimizer; its expression is:

[0088]

[0089] Among them, w new and w old are the weights before and after the update, η is the learning rate, is the gradient of the loss function L with respect to the weight;

[0090] Model evaluation: Use the validation dataset to check model performance and monitor overfitting;

[0091] Step 54, learning rate adjustment: The learning rate scheduler is CosineAnnealingLR, which adjusts the learning rate according to the cosine function so that it first decreases and then increases in each cycle. Its expression is:

[0092]

[0093] Among them, η tis the learning rate at time t, η min and η max are the minimum and maximum values ​​of the learning rate, T cur is the current iteration number, T max is the maximum number of iterations in a cycle.

[0094] Optionally, in step 61, saving and loading model parameters, after training is completed, the model parameters are saved to disk; usually the model with the best performance on the validation set is selected for saving; in the prediction stage, the trained model parameters are loaded from disk to ensure that an optimized model is used;

[0095] Step 62, test set prediction, using the loaded model to predict the water level images in the test set; the model outputs the predicted water level position and related features for each test image;

[0096] Step 63: Performance evaluation: comprehensively evaluate the performance of the model on the test set through evaluation indicators to quantify the application effect of the model in real scenarios.

[0097] Step 64: Analyze the results of the model prediction to obtain the analysis results of the model;

[0098] Step 65: Improvement suggestions: Improve the model and data processing flow based on the performance evaluation and analysis results.

[0099] In a second aspect, an embodiment of the present invention provides a computer-readable storage medium, wherein the computer-readable storage medium includes a stored program, wherein when the program is running, the electronic device where the computer-readable storage medium is located is controlled to execute the water level monitoring method based on deep learning in the first aspect or any possible implementation of the first aspect.

[0100] In the third aspect, an embodiment of the present invention provides an electronic device, comprising: one or more processors; a memory; and one or more computer programs, wherein the one or more computer programs are stored in the memory, and the one or more computer programs include instructions, which, when executed by the electronic device, enable the device to execute the water level monitoring method based on deep learning in the first aspect or any possible implementation of the first aspect.

[0101] In the technical solution provided by the present invention, the method includes image preprocessing and data enhancement: preprocessing the water body image taken by the field camera to optimize the image quality; applying the data enhancement technology to the training set by random rotation, flipping and scaling to obtain the image after the first processing; constructing a feature extraction and recognition model: combining the advanced deep learning model U-Net++ and the VGGBlock convolution block to obtain the feature extraction and recognition model; using BCEDiceLoss as the loss function to optimize the feature extraction and recognition model to obtain the optimized feature extraction and recognition model; image distortion correction and inverse perspective transformation: using the inverse perspective transformation and distortion correction technology to perform distortion correction and inverse perspective transformation on the image after the first processing to obtain the image after the second processing; training the feature extraction and recognition model: through an iterative training process, using the gradient descent algorithm, using the image after the second processing to train the feature extraction and recognition model, to obtain the trained feature extraction and recognition model; water level detection and feature extraction and recognition model evaluation: using the trained feature extraction and recognition model to perform water level detection, and performing performance evaluation on the feature extraction and recognition model under the evaluation index. This method uses a deep learning model to analyze and identify water level line images. It can automatically learn complex and effective features from a large number of water level line images, improve the accuracy and automation of water level monitoring, reduce the need for manual monitoring, and effectively support water resource security management and disaster prevention. BRIEF DESCRIPTION OF THE DRAWINGS

[0102] In order to more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings required for use in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative work.

[0103] Figure 1 A flow chart of a water level monitoring method provided by an embodiment of the present invention;

[0104] Figure 2 A schematic diagram of an electronic device provided by an embodiment of the present invention. DETAILED DESCRIPTION

[0105] In order to make the purpose, technical solution and advantages of the embodiments of the present invention clearer, the technical solution in the embodiments of the present invention will be clearly and completely described below in conjunction with the drawings in the embodiments of the present invention. Obviously, the described embodiments are part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.

[0106] It should be clear that the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.

[0107] The terms used in the embodiments of the present invention are only for the purpose of describing specific embodiments, and are not intended to limit the present invention. The singular forms "a", "said" and "the" used in the embodiments of the present invention are also intended to include plural forms, unless the context clearly indicates other meanings.

[0108] It should be understood that the term "and / or" used in this article is only a description of the association relationship of associated objects, indicating that there can be three relationships. For example, A and / or B can represent: A exists alone, A and B exist at the same time, and B exists alone. In addition, the character " / " in this article generally indicates that the associated objects before and after are in an "or" relationship.

[0109] The word "if" as used herein may be interpreted as "at the time of" or "when" or "in response to determining" or "in response to detecting", depending on the context. Similarly, the phrases "if it is determined" or "if (stated condition or event) is detected" may be interpreted as "when it is determined" or "in response to determining" or "when detecting (stated condition or event)" or "in response to detecting (stated condition or event)", depending on the context.

[0110] Figure 1 A flow chart of a water level monitoring method provided by an embodiment of the present invention, such as Figure 1 As shown, the method includes:

[0111] Step 1: Image preprocessing and data enhancement: Preprocess the water body images taken by the field camera to optimize the image quality; apply data enhancement technology to the training set by random rotation, flipping and scaling to obtain the first processed image.

[0112] In the embodiment of the present invention, preprocessing includes cropping, adjusting brightness, contrast and denoising, mainly involving adaptive image enhancement, edge detection optimization and Gaussian filtering denoising to increase the diversity of the training data set and the robustness of the model.

[0113] In the embodiment of the present invention, step 1 includes:

[0114] Step 11: Image cropping and adjustment: First, the size of the original image is cropped from 1024×768 pixels to a central area of ​​500×500 pixels; then the cropped image is adjusted to a standard size of 256×256 pixels. The expressions for cropping and adjusting ResizedImage are:

[0115] ResizedImage=Resize(Crop(1024,768),256,256);

[0116] Resize(·) means adjusting the cropped image to a standard size for subsequent processing or analysis; Crop(·) means cropping the redundant parts of the image and retaining only the most important area, that is, the area of ​​interest or the target area;

[0117] The mathematical expression of the crop function is: if the size of the original image is original_image and the size after cropping is cropped_image, the cropping operation can be expressed as:

[0118] cropped_image=original_image[y:y+h,x:x+w];

[0119] Where x and y are the starting coordinates of the cropping area, and w and h are the width and height of the cropping area.

[0120] Mathematical expression of the resize function: If the cropped image size is cropped_image and the adjusted size is resized_image, the adjustment operation can be expressed as:

[0121] resized_image=cv2.resize(cropped_image,(new_width,new_height)).

[0122] In the embodiment of the present invention, the image is adjusted to a uniform resolution and size to facilitate subsequent processing.

[0123] Step 12: Perform adaptive grayscale histogram equalization on the cropped and adjusted image; the expression of adaptive grayscale histogram equalization is:

[0124]

[0125] Among them, r k Represents the gray level of the original image, p ′ (r k ) represents the new gray level of the equalized image;

[0126] In the embodiment of the present invention, the purpose of the adaptive grayscale histogram equalization is to improve the contrast of the image, especially in the light and dark areas of the image.

[0127] Step 13, adjust brightness and contrast: set the brightness adjustment factor of the original image to 10, and the contrast adjustment factor to 1.2; the brightness and contrast of the original image are expressed as Iorig , image I after adjusting brightness and contrast adj Expressed as: I adj =1.2×I orig +10;

[0128] The expression of grayscale linear transformation is:

[0129] Iout=a·Iin+b;

[0130] Among them, Iin represents the gray value of the input original image, and Iout represents the gray value of the output image; parameter a controls the slope of the transformation and affects the contrast of the image, and parameter b represents the Y-axis intercept and affects the brightness of the image;

[0131] In the embodiment of the present invention, by adjusting a and b, the contrast and brightness of the image can be enhanced while retaining the image details, making the image more suitable for subsequent processing and analysis.

[0132] Step 14: Image noise reduction: Apply a Gaussian filter with a standard deviation of 1.5 to remove noise from the image; the Gaussian filter G(x,y,1.5) is used for noise reduction. The image after noise reduction is expressed as: denoise =I orig *G(x,y,1.5);

[0133] Assume f(x,y) is the original image and g(x,y) is the image after Gaussian filtering. The expression of Gaussian filtering is:

[0134]

[0135] Among them, w(s,t) represents the weight of the Gaussian filter; a and b are used to define the size of the Gaussian filter;

[0136] w(s,t) is calculated from Gaussian distribution and its expression is:

[0137]

[0138] Among them, σ represents the standard deviation of the Gaussian filter and controls the smoothness of the filter;

[0139] In the embodiment of the present invention, by adjusting the value of σ, the intensity of the filtering effect can be changed, thereby better meeting the noise reduction requirements of different images.

[0140] Step 15: Data enhancement: The image is rotated 30 degrees clockwise and counterclockwise, flipped horizontally, flipped vertically, and scaled 0.8 to 1.2 times. The enhanced image I aug The expression is:

[0141] I aug =T(Iorig );

[0142] Where T represents the image transformation operation.

[0143] In the embodiment of the present invention, image preprocessing mainly includes the mathematical principles of the following key links:

[0144] Image scaling: changing the size of an image. Usually bilinear interpolation or nearest neighbor interpolation is used. The formula for bilinear interpolation is:

[0145]

[0146] Among them, I is the original image, I ′ is the scaled image, (x,y) and (x ′ ,y ′ ) are the original and scaled pixel coordinates, respectively.

[0147] Normalization: Convert image pixel values ​​to a specific range. A common method is to subtract the mean and divide by the standard deviation:

[0148]

[0149] Where I is the original image, μ is the mean of the pixel values, and σ is the standard deviation.

[0150] Step 2: Build a feature extraction and recognition model: By combining the advanced deep learning model U-Net++ and the VGGBlock convolutional block, a feature extraction and recognition model is obtained.

[0151] In the embodiment of the present invention, the advanced deep learning model U-Net++ learns complex features through multiple layers to effectively identify the water level line.

[0152] In the embodiment of the present invention, step 2 includes:

[0153] Step 21. Construct VGGBlock convolution block: Initialize VGGBlock convolution block. First, define input channel in_channels, middle channel middle_channels and output channel out_channels. Input channel is used to define the number of image channels input to VGGBlock, which is 3 for RGB image. Middle channel is used to define the number of channels between two convolution operations. It is an internal parameter used to transfer features between convolution layers. Output channel is used to define the number of channels output by VGGBlock, which determines the number of channels of the image after passing through VGGBlock.

[0154] Initialize the ReLU activation function and batch normalization layer. The ReLU activation function is initialized using nn.ReLU(inplace=True) to add nonlinearity. The inplace=True parameter will modify the input data in place. The batch normalization layer initializes the intermediate layer and the output layer nn.BatchNorm2d layers, corresponding to the number of intermediate channels and output channels respectively.

[0155] Step 22, VGGBlock forward propagation:

[0156] (a) The first convolution operation: The first convolution layer uses nn.Conv2d(in_channels, middle_channels, kernel_size = 3, padding = 1) to initialize the convolution layer, with a kernel size of 3×3 and an edge padding of 1 to keep the image size unchanged; batch normalization and ReLU activation: After applying batch normalization nn.BatchNorm2d(middle_channels), the ReLU activation function nn.ReLU(inplace = True) is used to activate the intermediate features;

[0157] For the convolutional layer, the expression is:

[0158] O = ReLU(BN(W*I+b));

[0159] Where: O represents the output feature map Output Feature Map; I represents the input feature map Input Feature Map; W represents the convolution kernel Kernel; * represents the convolution operation; b represents the bias term (Bias); BN represents the batch normalization operation; ReLU represents the activation function, which is defined as ReLU(x)=max(0,x);

[0160] (b) Second convolution operation: The second convolution layer uses nn.Conv2d(middle_channels, out_channels, kernel_size=3, padding=1), keeping the convolution kernel size and edge padding unchanged; batch normalization and ReLU activation: apply batch normalization nn.BatchNorm2d(out_channels), and use ReLU activation function nn.ReLU(inplace=True) to activate output features;

[0161] The batch normalization operation expression is:

[0162]

[0163] Where: x represents the output of the convolutional layer; μ represents the mean value within the batch; σ2 represents the variance within the batch; ∈ represents a positive parameter; γ and β represent learned parameters for rescaling and offsetting the normalized values;

[0164] Final output: The output after the last ReLU activation is regarded as the final output of the VGGBlock convolution block and is used in subsequent network layers or as a feature map.

[0165] In the embodiments of the present invention, the convolution operation is a basic step for feature extraction in deep learning, and plays an important role in image processing in particular. The convolution operation involves the following key concepts:

[0166] Convolution kernel: A smaller matrix that slides over the input image to extract features.

[0167] Feature Map: The output matrix produced by applying the convolution kernel to the image.

[0168] Mathematically, the convolution operation can be expressed as:

[0169] F(i,j)=∑ m ∑ n I(i+m,j+n)·K(m,n);

[0170] Among them, F(i,j) is an element on the feature map, I is the input image, K is the convolution kernel, and m and n are the dimension indices of the convolution kernel.

[0171] In this process, the convolution kernel slides over the entire input image, each time moving a certain stride, performing element-wise multiplication with the corresponding area of ​​the input image at each position, and then summing the results to form an element of the feature map. In this way, the convolution operation can capture local features in the input image, reduce the number of parameters, and improve the efficiency and generalization ability of the model.

[0172] The purpose of batch normalization is to standardize the input in each layer of the network to speed up training and improve the stability and performance of the model. The specific operation is as follows:

[0173] Calculate batch mean and variance: First calculate the mean μ of the current batch data B and variance

[0174]

[0175] Where m is the batch size, x i is a single sample in the batch.

[0176] Normalization: Next, normalize each sample:

[0177]

[0178] Here, ∈ is a small number used to prevent the denominator from being zero.

[0179] Scaling and translation: Finally, the normalized data is scaled and translated using learnable parameters: Here, γ and β are learnable scaling and translation parameters of the model that allow the model to recover to the original data distribution if doing so helps in training the model.

[0180] Through this process, batch normalization helps reduce the so-called internal covariate shift, that is, the change in the distribution of network activations caused by changes in network parameters during training, which can speed up the convergence process of the model and may improve the final performance of the model.

[0181] ReLU (Rectified Linear Unit) activation function is a commonly used activation function in deep learning, mainly used to increase the nonlinear characteristics of the network. The mathematical expression of the ReLU function is very simple:

[0182] R(x)=max(0,x);

[0183] This means: if the input x is positive or zero, the ReLU function outputs a value equal to x. If the input x is negative, the ReLU function outputs a value of 0.

[0184] The ReLU function is used because it solves the vanishing gradient problem (when training deep neural networks, the gradient can become very small, making it difficult for the network to learn) and is computationally efficient. Due to its simplicity, ReLU often performs better than traditional Sigmoid or tanh functions in practice.

[0185] In the embodiment of the present invention, the implementation of VGGBlock is:

[0186] Class definition and initialization: Define the VGGBlock class, which is the basic building block in Nested U-Net. The class initialization function __init__(self, in_channels, middle_channels, out_channels) receives three parameters: the number of input channels in_channels, the number of middle channels middle_channels, and the number of output channels out_channels.

[0187] Convolutional layer and batch normalization: Initialize two 2D convolutional layers self.conv1 and self.conv2. The convolutional layer uses a 3x3 convolution kernel with a stride of 1 and an edge padding of 1. Convolution formula: Conv2d(x) = ReLU(W*x+b), where x is the input feature map, W and b are the weights and biases of the convolutional layer. Initialize two batch normalization layers self.bn1 and self.bn2 to normalize the distribution of feature maps.

[0188] Batch normalization formula:

[0189] where μ and σ 2 are the mean and variance of the feature map, and γ and β are learnable scaling and offset parameters.

[0190] ReLU activation function: Initialize the ReLU activation function self.relu. ReLU activation formula: ReLU(x) = max(0,x); here x represents the output of the convolutional layer.

[0191] Forward propagation definition: Define the forward propagation function forward(self,x). The input data x first passes through the first convolution layer self.conv1, then through batch normalization self.bn1, and finally applies the ReLU activation function. After the second convolution self.conv2, batch normalization self.bn2 and ReLU activation, the final output is obtained.

[0192] Through these steps, VGGBlock is able to extract more complex and abstract features from the input feature map, preparing for the next stage of Nested U-Net.

[0193] Definition and initialization of Nested U-Net: In this step, the Nested U-Net network will be defined and initialized in detail. This is an improved U-Net network that improves the performance of image segmentation through a deeper network structure and complex connection mode.

[0194] Class definition: Define the NestedUNet class in Python, which inherits from nn.Module. The class constructor receives parameters such as the number of categories num_classes and the number of input channels input_channels.

[0195] Setting the number of filters: Set the number of filters in the class constructor and define a list nb_filter = [32, 64, 128, 256, 512] to indicate the number of filters at different levels in the network.

[0196] Initialization of encoder layers: Initialize a VGGBlock instance for each encoder layer, use self.conv0_0 = VGGBlock(input_channels, nb_filter[0], nb_filter[0]) to create the first encoder layer, etc. Each encoder layer is followed by a max pooling layer for downsampling.

[0197] Initialization of decoder layer: Initialize upsampling layer and multiple VGGBlock instances for the decoder path, and use self.up = nn.Upsample(scale_factor = 2, mode = 'bilinear', align_corners = True) for upsampling. In the decoder, the upsampled features are concatenated with the features of the corresponding encoder layer through skip connections.

[0198] Initialization of the output layer: Initialize the final output layer, for example, using self.final = nn.Conv2d(nb_filter[0], num_classes, kernel_size = 1) to produce the final segmentation result.

[0199] Deep supervision mechanism: The code enables deep supervision (deep_supervision=True) and adds additional output layers to the intermediate layers. These layers can be used to calculate additional losses during training and help the model learn deeper features.

[0200] Forward propagation function: define the forward(self,input) function to describe how data flows through the network. In this function, the data will pass through the encoder layer, the decoder layer, and finally generate the prediction result through the output layer. In the deep supervision mode, the network will generate multiple intermediate layer outputs, which are used to assist training.

[0201] Through this step, we obtain a Nested U-Net network model with complex structure and powerful functions, which is suitable for processing highly complex image segmentation tasks.

[0202] Step 23: Build the U-Net++ network structure:

[0203] (c) Network initialization: define the number of filters at different levels as [32, 64, 128, 256, 512], which will determine the feature extraction capability of each level; initialize the encoder layer conv_{i,0} and the decoder layer conv_{i,j} of U-Net++ to ensure feature extraction and processing;

[0204] (d) Encoder path, the input image I first passes through the first encoder level conv_{0,0}, which is the starting point of feature extraction; next, for the output of each encoder level, the maximum pooling operation MaxPool is performed to reduce the dimension of the feature map and increase the level of abstraction; this continues until the last encoder level conv_{4,0}, each level can capture different levels of image features;

[0205] (e) Decoder path: First, the output of the deepest encoder is upsampled to increase the dimension of the feature map. The upsampled features are concatenated with the features of the corresponding encoder level through skip connections to preserve spatial information. The fused features are processed through the convolutional layers of the decoder to gradually reconstruct the feature map. This process is repeated in different decoder levels to gradually reconstruct high-resolution feature maps.

[0206] (f) Output layer: At the end of the network, the final output of the decoder is passed through a convolutional layer to convert the number of channels of the feature map into the number of target categories; a softmax or sigmoid activation function is used to assign a probability or classification to each pixel;

[0207] (g) Deep supervision. When deep supervision is enabled, the intermediate layers of the network will produce additional outputs. The auxiliary outputs help the network focus on deeper features during training. By calculating the loss of the auxiliary outputs and combining it with the main loss function, the model representation can learn complex features.

[0208] In the embodiment of the present invention, upsampling and downsampling are commonly used operations in convolutional neural networks, which are used to change the size of feature maps:

[0209] Upsampling: Upsampling is used to increase the size of the feature map, that is, to enlarge the image. Common methods include nearest neighbor interpolation, bilinear interpolation, etc. Mathematically, if nearest neighbor interpolation is used, given a pixel point p, its upsampled value p′ can be expressed as:

[0210] p′=p;

[0211] That is, the original pixel value is directly used for the new enlarged pixel position.

[0212] Downsampling: Downsampling is used to reduce the size of the feature map, that is, to shrink the image. Common methods are max pooling or average pooling. For example, in max pooling, an n×n window slides over the image and takes the maximum value in each window as the output. Mathematically, max pooling can be expressed as:

[0213] p′=max(all pixel values ​​in the window);

[0214] Where p′ is the pixel value output by the pooling window.

[0215] In the embodiment of the present invention, the role of the final classification layer in the deep learning model is to map the extracted features to the target category. For binary classification problems, this is usually achieved through the sigmoid activation function. The mathematical expression of the sigmoid function is:

[0216]

[0217] Where x is the input feature. The output range of the sigmoid function is between 0 and 1, which is suitable for expressing probability. In this type of binary classification problem, the output value can be interpreted as the probability of belonging to a certain category. A threshold (0.5) can be set to classify samples with output values ​​greater than this threshold into one category and samples with output values ​​less than or equal to the threshold into another category.

[0218] In the embodiment of the present invention, the downsampling process is as follows: for each encoder layer, the input data is first processed by VGGBlock to extract and enhance features. The maximum pooling layer (nn.MaxPool2d) is used to reduce the spatial dimension of the feature map to reduce the amount of calculation and increase the receptive field: self.pool = nn.MaxPool2d(2,2).

[0219] Mathematical representation: P(x) = max subregion (x);

[0220] Among them, P represents the maximum pooling operation and x is the input feature map.

[0221] Upsampling process: For each level of the decoder, the spatial dimension of the feature map is first increased through the upsampling layer (nn.Upsample). The mathematical formula used for upsampling can be expressed as:

[0222] U(x)=upsample(x,scale factor );

[0223] Among them, U is the upsampling operation, x is the input feature map, and scale factor Controls the upsampling factor.

[0224] Feature fusion and reconstruction: At each decoder level, the upsampled features are combined with the features of the corresponding encoder level through skip connections, and feature concatenation is performed using torch.cat.

[0225] Mathematical representation: C(x,y)=concat(x,y);

[0226] Among them, C represents the concatenation operation, and x and y are the two feature maps that need to be concatenated. The concatenated features are then processed by VGGBlock at the corresponding level to fuse the features and reconstruct a more refined feature map.

[0227] Through these steps, the Nested U-Net model achieves effective feature extraction, downsampling, upsampling, and feature fusion in the forward propagation process, so that it can handle complex image segmentation tasks and provide accurate segmentation results.

[0228] In the embodiment of the present invention, feature merging and feature connection describe how to merge features of different levels through skip connections in U-Net++ to improve the model's ability to capture details and contextual information.

[0229] In U-Net++, feature maps x and y are merged through the concatenation operation, usually along the feature channel dimension. If the dimensions of x and y are (H, W, Cx) and (H, W, Cy), the result of concatenation is a new feature map with dimensions (H, W, Cx + Cy). The mathematical representation is:

[0230] Concat(x,y) = [x; y];

[0231] Here, [x;y] represents a join operation along a specific dimension.

[0232] The final convolutional layer is used to map the merged features to the output dimension. The merged feature map is z, and the operation of the final convolutional layer can be expressed as:

[0233] f final (z) = W*z + b;

[0234] Where W is the weight of the convolution kernel, b is the bias term, and * represents the convolution operation. This step converts the combined feature map into the final output. For example, in an image segmentation task, the output may be the category probability of each pixel.

[0235] Auxiliary output:

[0236] A i =Conv(D i,4-i );

[0237] Generate auxiliary outputs of the network's intermediate layers to facilitate deep feature learning.

[0238] Deep Supervision Loss:

[0239]

[0240] Calculate the main loss L main and each auxiliary output The loss is combined to optimize network learning.

[0241] Step 3: Use BCEDiceLoss as the loss function to optimize the feature extraction and recognition model to obtain the optimized feature extraction and recognition model.

[0242] In the embodiment of the present invention, the loss function BCEDiceLoss helps to balance the classification accuracy at the pixel level and the continuity of the overall area, thereby improving the accuracy of water level recognition.

[0243] BCEDiceLoss is a composite loss function that combines two key metrics: pixel-level classification accuracy (measured by BCE loss) and the overlap between the predicted and true regions (measured by Dice loss). This combined approach aims to improve the overall performance of the model for waterline recognition. The role of binary cross entropy loss (BCE): It is used to calculate the difference between the predicted probability and the actual label of each pixel. For each pixel, it will evaluate whether the model accurately classifies it as a waterline or a non-waterline. The role of Dice loss: quantify the similarity between the entire predicted region and the true labeled region. It is very suitable for situations where positive and negative samples in the dataset are unbalanced, which is common in medical and natural environment images.

[0244] In the embodiment of the present invention, step 3 includes:

[0245] The goal of BCEDiceLoss loss function optimization is to minimize BCEDiceLoss to balance the classification accuracy of a single pixel and the continuity of the entire prediction area; its specific calculation includes:

[0246] Binary cross entropy loss BCE, use F.binary_cross_entropy_with_logits function to calculate the binary cross entropy loss (BCE Loss) between the model prediction output (logits) and the target label, its expression is:

[0247]

[0248] where y i represents the true label, y i预测 represents the predicted probability;

[0249] Dice loss is used to evaluate the degree of spatial overlap between the predicted area and the true label. The model output is converted into a predicted probability by applying the sigmoid function, and the Dice coefficient is calculated together with the target label to obtain Dice Loss, which is expressed as:

[0250]

[0251] Here, smooth is a smoothing term used to avoid division by zero errors.

[0252] The expression of the combined loss function BCEDiceLoss is:

[0253] BCEDiceLoss=α·BCE+(1-α)·Dice;

[0254] The parameter α is used to weigh the importance of BCE loss and Dice loss.

[0255] The goal of loss function optimization is to minimize BCEDiceLoss to balance the classification accuracy of a single pixel and the continuity of the entire prediction area. This method is particularly suitable for processing image segmentation tasks, which not only focuses on the correct classification of each pixel, but also on the shape and integrity of the overall prediction area.

[0256] In the embodiment of the present invention, the performance evaluation index is implemented as follows:

[0257] IoU (Intersection over Union): measures the degree of overlap between the predicted area and the true area.

[0258] Mathematical formula:

[0259] Here, x and y are the predicted and true segmentation regions, respectively.

[0260] Dice coefficient: Similar to Dice loss, but used to evaluate performance.

[0261] Mathematical formula:

[0262]

[0263] With these definitions and implementations, we are able to accurately evaluate the performance of our models on segmentation tasks while ensuring that the training process is effectively optimizing model performance.

[0264] In an embodiment of the present invention, the batch_size parameter is set: the number of images processed by the network in each training iteration is determined, and it is set to a specific value here. The learning_rate parameter is set: the optimization step during model training is determined, and it is set to a specific value here. The epochs parameter is set: the number of times the entire data set is traversed during model training is determined, and it is set to a specific value here. The momentum parameter is set: it helps the optimization algorithm avoid uncertainties during training and accelerates convergence, and it is set to a specific value here. The weight_decay parameter is set: a regularization term is added to the optimization algorithm to avoid overfitting of the model, and it is set to a specific value here.

[0265] Step 4: Image distortion correction and inverse perspective transformation: Using inverse perspective transformation and distortion correction technology, the image after the first processing is subjected to distortion correction and inverse perspective transformation to obtain the image after the second processing.

[0266] In the embodiment of the present invention, the image distortion caused by the camera angle and perspective is corrected to ensure the accurate marking of the water level line.

[0267] In the embodiment of the present invention, step 4 includes:

[0268] Step 41: Image distortion correction:

[0269] Load the camera calibration image, and obtain the checkerboard image used for camera calibration by loading the camera calibration image; use the Glob library to obtain the file path of the camera calibration image;

[0270] In the embodiment of the present invention, the image contains known checkerboard corner points, which are used for parameter calculation of camera distortion correction.

[0271] Find the corners of the chessboard, use the camera calibration image, and use OpenCV's cv2.findChessboardCorners function to find the corners of the chessboard;

[0272] In the embodiment of the present invention, the corner points are key data for subsequent camera calibration and are used to calculate the distortion coefficient of the camera.

[0273] Calibrate the camera and remove image distortion. Use the corner points of the chessboard and the corresponding real coordinate points to calibrate the camera. Calculate the camera matrix and distortion coefficients of the camera through the cv2.calibrateCamera function, and then use the cv2.undistort function to correct the image distortion. The distortion coefficients are expressed in polynomial form to represent the camera distortion, including radial distortion k1, k2, k3 and tangential distortion p1, p2. The camera matrix K contains the intrinsic parameter information of the camera, including focal length, optical axis offset, etc. The expression of the camera matrix K is:

[0274]

[0275] Among them, f x and f y is the focal length, (c x ,c y ) are the pixel coordinates of the optical center;

[0276] Calculation of camera calibration parameters: This step mainly prepares the 3D coordinate set objp of the checkerboard corner points. Calculation of camera calibration parameters: Use cv2.calibrateCamera(objpoints,imgpoints,img_size,None,None) to calculate the camera's internal matrix and distortion coefficients.

[0277] Distortion correction application: Apply dst = cv2.undistort(img,mtx,dist,None,mtx) to perform distortion correction on the image.

[0278] Inverse perspective transformation preparation: Use M = cv2.getPerspectiveTransform(src,dst) to prepare the matrix for inverse perspective transformation.

[0279] Water level detection class initialization:

[0280] Initialize the water level detection class: Initialize an instance of the Line class to store various properties and states of the water level.

[0281] Detect water level: Use cv2.findChessboardCorners and cv2.calibrateCamera methods, combined with the chessboard calibration image, to extract water level features. The extracted features include the 2D coordinates (imgpoints) of the chessboard corners on the image plane and the corresponding 3D world coordinates (objpoints).

[0282] Water level detection and drawing:

[0283] Water level fitting and updating: For each detected water level, calculate the quadratic polynomial fitting parameters: fit = np.polyfit (self.y, self.x, 2). Here self.x and self.y are the pixel coordinates of the detected water level. The form of the fitted quadratic polynomial is Ax 2 +Bx+C.

[0284] Calculate the curvature of the water level line: Calculate the curvature based on the polynomial parameters obtained by fitting: curverad = ((1+(2A*y eval +B) 2 ) 3 / 2 ) / |2A|. Here y eva1 The bottom of the image (i.e. the highest y value) is usually taken to estimate the actual curvature of the water level on the road.

[0285] Inverse perspective transformation: Apply the cv2.warpPerspective method to map the detected water level from the image plane to another perspective according to the inverse perspective transformation matrix M, so as to more accurately analyze the shape and position of the water level.

[0286] Visualize the water level detection results: Draw the detected water level and the calculated quadratic polynomial curve on the original image, as well as the calculated curvature and water level position information.

[0287] Water level position evaluation: Based on the relative position of the water level fitting curve and the lane center, calculate the position offset of the water level relative to the lane center. Formula: offset = (img_shape[1] / 2-xmean)*xm_per_pix, where xmean is the average x-coordinate of the bottom of the water level, and xm_per_pix is ​​the actual distance represented by each pixel.

[0288] Step 42: Image reverse perspective:

[0289] In image processing, selecting key points through user interaction or automatic algorithms is a key step in inverse perspective transformation. The basis of inverse perspective transformation is to select four non-collinear points from the original image, which form the basis of perspective transformation. The selection of these points has a profound impact on the final inverse perspective transformation result.

[0290] Select the key points of the inverse perspective transformation. The inverse perspective transformation requires four non-collinear points, which are expressed as P = {(x1, y1), (x2, y2), (x3, y3), (x4, y4)}. The four non-collinear points are selected on the original image to form the basis of the inverse perspective transformation and define the perspective area of ​​the image;

[0291] In the embodiment of the present invention, four key points are selected on the image using user interaction. These points are usually the four corners of the water level, which are used to define the perspective area of ​​the image.

[0292] Calculate the inverse perspective transformation matrix. The calculation of the inverse perspective transformation matrix is ​​based on the four key points in the selected original image and the four corresponding vertices of the target image; this function requires two sets of points: pts1 (points in the original image) and pts2 (points in the target image). Here pts1 is the four points selected interactively, and pts2 is the corresponding four points in the target view, usually selected as a rectangle or square, such as [[500,0],[500,500],[0,500],[0,0]]. The inverse perspective transformation matrix is ​​obtained by solving a system of linear equations, using the relationship between the four points in the original image and the corresponding vertices of the target image; the four points P in the original image original={(x1,y1),(x2,y2),(x3,y3),(x4,y4)}, the corresponding four vertices P in the target image target ={(u1,v1),(u2,v2),(u3,v3),(u4,v4)}, the inverse perspective transformation matrix M is calculated by the cv2.getPerspectiveTransform function, which is a 3x3 matrix; the inverse perspective transformation matrix M is obtained by solving the following linear equations:

[0293]

[0294] Among them, the M matrix represents the mapping relationship between the points in the original image and the corresponding points in the target image, thereby realizing the inverse perspective transformation;

[0295] Perform inverse perspective transformation. The inverse perspective transformation function cv2.warpPerspective transforms the original image according to the calculated inverse perspective transformation matrix M; this function applies the perspective transformation matrix M to the image and sets the size of the output image to (500,500). Given the original image I original And the inverse perspective transformation matrix M, perform the inverse perspective transformation to obtain the transformed image I transformed , whose expression is:

[0296] I transformed =cv2.warpPerspective(I original ,M,target_size);

[0297] Where target_size represents the target image size of the desired output; the inverse perspective transformation function uses the inverse perspective transformation matrix M to transform the original image I original Mapping to a new perspective or geometry to generate a transformed image I transformed ;

[0298] In the embodiment of the present invention, the inverse perspective transformation is the process of projecting the selected area from the original image to a new viewing angle or geometric shape. This transformation uses the inverse perspective transformation matrix to map the area in the original image to the target position, thereby correcting the perspective distortion in the image.

[0299] In the embodiment of the present invention, cv2.warpPerspective is used again, but this time the inverse transformation matrix of the perspective transformation is used. The purpose of this step is to map the transformed image dst back to the perspective of the original image.

[0300] Mask generation and application: Create a mask of the same size as the original image, with the perspective transformed area in the mask as white (value 255) and other areas as black (value 0). Use the cv2.fillConvexPoly function to fill the perspective transformed area on the mask.

[0301] Image processing and synthesis, use the cv2.bitwise_and function to apply the mask to the inverse transformed image dst_transformed_back and the original image. This retains the inverse transformed image in the masked area and the original image in the area outside the mask. Finally, use cv2.add to merge the two images to create the final corrected image. After the inverse perspective transformation, the transformed image and the original image are processed and synthesized to obtain the final image after correcting the perspective distortion; the image is segmented and merged using the mask Mask and the inverse mask Inverse Mask; the mask is a matrix of the same size as the image, which is used to identify the area that needs to be inversely transformed; the inverse mask is the complement of the mask, which is used to retain the area that has not been transformed; the inverse perspective transformed image is separated from the original image through the bit operation function, and merged in the appropriate area to obtain the final processed image; its expression is:

[0302] masked_dst=cv2.bitwise_and(I transformed ,mask);

[0303] masked_img=cv2.bitwise_and(I original ,inverse_mask);

[0304] final_img=cv2.add(masked_dst, masked_img);

[0305] Among them, I transformed I represents the image after inverse perspective transformation; original Represents the original image; mask represents the mask of the inverse perspective transformed area; inverse_mask represents the inverse mask of the untransformed area; masked_dst represents the area after the inverse perspective transformed image is applied with the mask; masked_img represents the area after the inverse mask is applied to the original image; final_img represents the final image that merges the transformed area and the untransformed area.

[0306] In the embodiment of the present invention, the bit operation function includes cv2.bitwise_and.

[0307] In the embodiment of the present invention, data preprocessing and enhancement, in this step, will focus on preprocessing and enhancing the image and mask to improve the performance and generalization ability of the model.

[0308] Image and mask reading, load the image and the corresponding mask from the dataset. Read the image file using OpenCV's cv2.imread function. Read the mask file and make sure the mask corresponds to the image. Resize the image and mask: Unify the size of the image and mask to meet the input requirements of the model. Resize the image and mask to a specific size (192x192). Use the interpolation method (bilinear interpolation) to resize the image to ensure image quality. Use nearest neighbor interpolation for the mask to preserve the category information of the mask. Data augmentation, improve the generalization and robustness of the model through augmentation techniques. Rotation: Randomly rotate the image and mask to increase the diversity of perspectives. Use a rotation matrix Perform coordinate transformation. Flip: Flip the image and mask horizontally or vertically. Color adjustment: Change the brightness, contrast, and saturation of the image to simulate different lighting and device conditions. Use color transformation formula I new =α·I orig +β, where α adjusts contrast and β adjusts brightness.

[0309] Through the above steps, we can effectively prepare the data to make it suitable for training deep learning models, while improving the model's ability to adapt to various changes.

[0310] Step 5: Train the feature extraction and recognition model: Through an iterative training process, a gradient descent algorithm is used to train the feature extraction and recognition model using the image after the second processing to obtain a trained feature extraction and recognition model.

[0311] In the embodiment of the present invention, model training aims to ensure that the network can effectively generalize to new, unseen test data sets. Use a validation set (data not involved in training). Calculate the model's loss and performance indicators on the validation set: IoU and Dice coefficient. Used to adjust hyperparameters and early stopping to avoid overfitting.

[0312] In the embodiment of the present invention, step 5 includes:

[0313] Step 51, initialize the training configuration: set the training cycle epochs, which indicates the number of times the network will traverse the entire data set during training; set the batch size batch_size, which indicates the number of samples used for one training, affecting gradient estimation and memory usage;

[0314] Step 52, optimizer selection and configuration: select optimizer to determine the weight of the updated network; set the learning rate lr to control the step size of the weight adjustment; set momentum for SGD, which helps to accelerate the optimization of SGD in the relevant direction and suppress oscillation; weight decay weight_decay is a regularization term used to prevent overfitting;

[0315] Step 53, training loop:

[0316] Forward propagation: input data passes through the network and calculates the output of each layer; loss calculation: use the loss function to calculate the difference between the predicted result and the true label; backward propagation: calculate the gradient of the loss function with respect to the network weight; gradient descent: update the network weight according to the calculated gradient; the update rule is defined by the optimizer; its expression is:

[0317]

[0318] Among them, w new and w old are the weights before and after the update, η is the learning rate, is the gradient of the loss function L with respect to the weight;

[0319] Model evaluation: Use the validation dataset to check model performance and monitor overfitting;

[0320] Step 54, learning rate adjustment: During the model training process, the learning rate scheduler is used to adjust the learning rate according to different stages of training, which is crucial for the optimization process and avoiding overfitting. The learning rate scheduler is CosineAnnealingLR, which adjusts the learning rate according to the cosine function so that it first decreases and then increases in each cycle. Its expression is:

[0321]

[0322] Among them, η t is the learning rate at time t, η min and η max are the minimum and maximum values ​​of the learning rate, T cur is the current iteration number, T max is the maximum number of iterations in a cycle.

[0323] In the embodiment of the present invention, the learning rate adjustment dynamically adjusts the learning rate according to the performance of the model to optimize the training process.

[0324] In the embodiment of the present invention, the training cycle is explained in detail:

[0325] Load training data and read a batch of data from the data loader, including input images X and corresponding target labels Y.

[0326] Forward propagation, passing the input X to the model f for forward propagation, generating the predicted output Y 预测 The formula is: Y 预测 =f(X;θ), where θ is a model parameter.

[0327] Calculate the loss and use the loss function L to calculate the predicted output Y 预测 The gap between the true target Y. For the binary cross entropy loss function, the calculation formula is: N is the batch size, y i and i预测 are the actual and predicted labels, respectively.

[0328] Back propagation, by back propagating the gradient of the loss with respect to the parameter θ The gradient calculation formula is:

[0329] Parameter update, use the optimizer to update the model parameters θ according to the gradient. The gradient descent update rule is: Here, α is the learning rate.

[0330] Verification cycle details:

[0331] Load validation data. Get a batch of validation data from the data loader. This includes the input image X. val and the corresponding target label Y val .

[0332] Forward propagation (verification), verify the data X val Pass it to the model f for forward propagation to obtain the verification prediction result Y val预测 The formula is: Y val预测 =f(X val ;θ);

[0333] Calculate the validation loss and use the same loss function L to evaluate the performance of the model on the validation data. The loss calculation formula is the same as training, but using the validation dataset:

[0334]

[0335] Calculate evaluation indicators. In the verification phase, in addition to calculating the loss function, other evaluation indicators are often calculated, such as IOU or Dice coefficient, to more comprehensively evaluate model performance.

[0336] Optimizer settings explained:

[0337] Select an optimizer and choose the appropriate optimizer according to the model and task requirements. In this project, you can choose Adam or SGD. If you choose the Adam optimizer, initialize the Adam object. The formula is: Optimizer = Adam (θ, lr = η, betas = (β1, β2), weight_decay = λ), where θ is the model parameter, η is the learning rate, β1 and β2 are the momentum terms of the Adam optimizer, and λ is the weight decay parameter.

[0338] Set the learning rate and set the optimizer's initial learning rate η = 0.001. This is one of the most important hyperparameters in the optimization process. The learning rate controls the step size of each parameter update.

[0339] Set the optimizer hyperparameters and adjust other hyperparameters β1 and β2 of the optimizer according to the characteristics of the model and data. For the Adam optimizer, set β1=0.9 and β2=0.999.

[0340] Weight decay, set weight decay λ to prevent overfitting. Weight decay is the L2 regularization term in the optimization process. The formula for weight update (taking Adam as an example) can be expressed as: θ new =θ old -η·Adam_update-η·λ·θ old ;

[0341] Apply the optimizer and use it in the training loop to update the weights of the model. This step happens after backpropagation of each batch.

[0342] In the embodiment of the present invention, in order to avoid overfitting, an early stopping condition is set, and the training is stopped if the performance of the validation set does not improve for multiple consecutive cycles.

[0343] In the embodiment of the present invention, the training parameters are configured as follows: Set the batch size (batch_size): determine the number of samples input into the model for each iteration. Set the learning rate (learning_rate): control the step size of weight update. Set the optimizer (SGD and Adam): determine the algorithm for weight update. Set the loss function (BCEDiceLoss): measure the difference between the model output and the target.

[0344] Training loop: Iterates over each batch. Forward propagation: Calculates the output of the model. Loss calculation: Calculates the error using the loss function. Backward propagation: Calculates the gradient of the loss with respect to the model parameters. Parameter update: Updates the model weights based on the gradient and the learning rate.

[0345] Step 6: Water level detection and feature extraction and recognition model evaluation: Use the trained feature extraction and recognition model to perform water level detection, and perform performance evaluation on the feature extraction and recognition model under the evaluation index.

[0346] In the embodiment of the present invention, the accuracy and reliability of the model are verified through testing of actual application scenarios.

[0347] In the embodiment of the present invention, step 6 includes:

[0348] Step 61: Saving and loading model parameters. After training is completed, the model parameters are saved to disk. Usually, the model with the best performance on the validation set is selected for saving. In the prediction stage, the trained model parameters are loaded from disk to ensure that an optimized model is used.

[0349] Step 62, test set prediction, using the loaded model to predict the water level images in the test set; the model outputs the predicted water level position and related features for each test image;

[0350] Step 63: Performance evaluation: comprehensively evaluate the performance of the model on the test set through evaluation indicators to quantify the application effect of the model in real scenarios.

[0351] In the embodiment of the present invention, the evaluation indicators include precision, recall rate, and F1 score.

[0352] Step 64: Analyze the results of the model prediction to obtain the analysis results of the model;

[0353] In the embodiment of the present invention, the analysis content includes the performance differences of the model on different types of images and cases of incorrect prediction.

[0354] Step 65: Improvement suggestions: Improve the model and data processing flow based on the performance evaluation and analysis results.

[0355] In the embodiment of the present invention, the improvement measures include adjusting the model architecture, introducing new data enhancement methods or optimizing the training strategy.

[0356] In the embodiment of the present invention, the model is evaluated by performing model performance evaluation on a test set, and key indicators such as intersection over union (IoU) and Dice coefficient are used to quantify the segmentation accuracy of the model.

[0357] Model saving, use torch.save to save the model state dictionary (state_dict), record the model structure and training configuration information for future reuse and research.

[0358] Interactive Image Processing and Visualization:

[0359] Build the User Interface: Design and implement a graphical user interface (GUI) using Python's Tkinter library. This interface contains the necessary buttons, labels, and image display frames. The "Open Image" button on the interface allows the user to select and load an image from the local file system.

[0360] Image uploading and preprocessing: When the user selects an image, the system automatically loads the image into the display area of ​​the interface and performs necessary preprocessing on the image, such as resizing and format conversion, to meet the model input requirements.

[0361] Model processing and result display: Provide an "Identify water level" button. When the user clicks it, the system passes the pre-processed image to the model for inference. Overlay the model processing results (such as the detected water level) on the original image and display them to the user in the interface.

[0362] Interactive feature annotation: Implement interactive annotation capabilities, such as allowing users to click on an image to mark specific points or areas. Through this interactive method, users can manually adjust or verify the output of the model.

[0363] Result saving and exporting: A "Save Result" button is provided, allowing the user to save the processed image to a specified path. This feature allows the user to easily archive the result image or use it in other applications and reports.

[0364] In an embodiment of the present invention, the method uses an advanced neural network model to analyze and identify water level line images, thereby improving the accuracy of water level monitoring, and is suitable for application scenarios such as hydrological monitoring, flood warning, and reservoir management. Through automated water level line recognition, the present invention aims to improve the efficiency and accuracy of water level monitoring, while reducing the need for manual monitoring, which is of great significance for ensuring water resource management and disaster prevention and mitigation. The method can automatically learn complex and effective features from a large number of water level line images, thereby achieving higher accuracy and stronger generalization capabilities in the detection and identification of water level lines. Through this method, the degree of automation of water level monitoring can be greatly improved, effectively supporting water resource management and disaster prevention.

[0365] In the embodiment of the present invention, an advanced neural network architecture and image processing technology are involved. The method mainly includes steps such as image preprocessing and data enhancement, feature extraction, loss function optimization, model training and performance evaluation. In the preprocessing stage, the original water level image is cropped, brightness adjusted, contrast optimized and denoised to improve image quality. Data enhancement techniques such as random rotation, flipping and scaling are used to increase the diversity of training data.

[0366] The core part is to use the advanced deep learning model Nested U-Net to accurately detect and classify water levels. This model effectively learns the characteristics of water levels through a complex hierarchical structure and skip connection strategy. The BCEDiceLoss loss function is used to optimize the model to balance the classification accuracy at the pixel level and the continuity of the overall area.

[0367] During the model training process, the gradient descent algorithm and the learning rate adjustment strategy CosineAnnealingLR were used to improve the training effect and avoid overfitting. Deep supervision technology was also introduced to promote the learning of deep features. Finally, the model was tested under multiple performance evaluation indicators, proving its efficiency and accuracy in water level recognition. Compared with traditional methods, the method of this project shows higher efficiency and better performance, which has important practical value for water level monitoring and management.

[0368] Each step of the embodiment of the present invention may be performed by an electronic device, which includes but is not limited to a mobile phone, a tablet computer, a portable PC, a desktop computer, a wearable device, etc.

[0369] In the technical solution provided by the present invention, the method includes image preprocessing and data enhancement: preprocessing the water body image taken by the field camera to optimize the image quality; applying the data enhancement technology to the training set by random rotation, flipping and scaling to obtain the image after the first processing; constructing a feature extraction and recognition model: combining the advanced deep learning model U-Net++ and the VGGBlock convolution block to obtain the feature extraction and recognition model; using BCEDiceLoss as the loss function to optimize the feature extraction and recognition model to obtain the optimized feature extraction and recognition model; image distortion correction and inverse perspective transformation: using the inverse perspective transformation and distortion correction technology to perform distortion correction and inverse perspective transformation on the image after the first processing to obtain the image after the second processing; training the feature extraction and recognition model: through an iterative training process, using the gradient descent algorithm, using the image after the second processing to train the feature extraction and recognition model, to obtain the trained feature extraction and recognition model; water level detection and feature extraction and recognition model evaluation: using the trained feature extraction and recognition model to perform water level detection, and performing performance evaluation on the feature extraction and recognition model under the evaluation index. This method uses a deep learning model to analyze and identify water level line images. It can automatically learn complex and effective features from a large number of water level line images, improve the accuracy and automation of water level monitoring, reduce the need for manual monitoring, and effectively support water resource security management and disaster prevention.

[0370] An embodiment of the present invention provides a computer-readable storage medium, which includes a stored program, wherein when the program is running, the electronic device where the computer-readable storage medium is located is controlled to execute the above-mentioned embodiment of the water level monitoring method based on deep learning.

[0371] Figure 2 A schematic diagram of an electronic device provided by an embodiment of the present invention, such as Figure 2 As shown, the electronic device 21 includes: a processor 211, a memory 212, and a computer program 213 stored in the memory 212 and executable on the processor 211. When the computer program 213 is executed by the processor 211, the water level line monitoring method based on deep learning in the embodiment is implemented. To avoid repetition, they are not described one by one here.

[0372] The electronic device 21 includes, but is not limited to, a processor 211 and a memory 212. Those skilled in the art will appreciate that Figure 2 It is only an example of the electronic device 21 and does not constitute a limitation of the electronic device 21. It may include more or fewer components than shown in the figure, or a combination of certain components, or different components. For example, the electronic device may also include input and output devices, network access devices, buses, etc.

[0373] The processor 211 may be a central processing unit (CPU), or 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 any conventional processor, etc.

[0374] The memory 212 may be an internal storage unit of the electronic device 21, such as a hard disk or memory of the electronic device 21. The memory 212 may also be an external storage device of the electronic device 21, such as a plug-in hard disk, a smart media card (SMC), a secure digital (SD) card, a flash card, etc. equipped on the electronic device 21. Further, the memory 212 may also include both an internal storage unit of the electronic device 21 and an external storage device. The memory 212 is used to store computer programs and other programs and data required by network devices. The memory 212 may also be used to temporarily store data that has been output or is to be output.

[0375] Those skilled in the art can clearly understand that, for the convenience and brevity of description, the specific working processes of the systems, devices and units described above can refer to the corresponding processes in the aforementioned method embodiments and will not be repeated here.

[0376] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, equivalent substitutions, improvements, etc. made within the spirit and principles of the present invention should be included in the scope of protection of the present invention.

Claims

1. A water level monitoring method based on deep learning, characterized in that: The method comprises: Step 1: Image preprocessing and data enhancement: Preprocess the water body images captured by the field camera to optimize the image quality; apply data enhancement technology to the training set by random rotation, flipping and scaling to obtain the first processed image; Step 2: Build a feature extraction and recognition model: By combining the advanced deep learning model U-Net++ and the VGGBlock convolutional block, a feature extraction and recognition model is obtained; Step 3: Use BCEDiceLoss as the loss function to optimize the feature extraction and recognition model to obtain the optimized feature extraction and recognition model; Step 4, image distortion correction and inverse perspective transformation: using inverse perspective transformation and distortion correction technology, the image after the first processing is subjected to distortion correction and inverse perspective transformation to obtain the image after the second processing; Step 5, training the feature extraction and recognition model: through an iterative training process, using a gradient descent algorithm, the feature extraction and recognition model is trained using the image after the second processing to obtain a trained feature extraction and recognition model; Step 6: Water level detection and feature extraction and recognition model evaluation: Use the trained feature extraction and recognition model to perform water level detection, and perform performance evaluation on the feature extraction and recognition model under the evaluation index.

2. The method according to claim 1, characterized in that The step 1 comprises: Step 11: Image cropping and adjustment: First, the size of the original image is cropped from 1024×768 pixels to a central area of ​​500×500 pixels; then the cropped image is adjusted to a standard size of 256×256 pixels. The expressions for cropping and adjusting ResizedImage are: ResizedImage=Resize(Crop(1024,768),256,256); Resize(·) means adjusting the cropped image to a standard size for subsequent processing or analysis; Crop(·) means cropping the redundant parts of the image and retaining only the most important area, that is, the area of ​​interest or the target area; Step 12: Perform adaptive grayscale histogram equalization on the cropped and adjusted image; the expression of adaptive grayscale histogram equalization is: Among them, r k Represents the gray level of the original image, p ′ (r k ) represents the new gray level of the equalized image; Step 13, adjust brightness and contrast: set the brightness adjustment factor of the original image to 10, and the contrast adjustment factor to 1.2; the brightness and contrast of the original image are expressed as I orig , image I after adjusting brightness and contrast adj Expressed as: I adj =1.2×I orig +10; The expression of grayscale linear transformation is: Iout=a·Iin+b; Among them, Iin represents the gray value of the input original image, and Iout represents the gray value of the output image; parameter a controls the slope of the transformation and affects the contrast of the image, and parameter b represents the Y-axis intercept and affects the brightness of the image; Step 14: Image noise reduction: Apply a Gaussian filter with a standard deviation of 1.5 to remove noise from the image; the Gaussian filter G(x,y,1.5) is used for noise reduction. The image after noise reduction is expressed as: denoise =I orig *G(x,y,1.5); Assume f(x,y) is the original image and g(x,y) is the image after Gaussian filtering. The expression of Gaussian filtering is: Among them, w(s,t) represents the weight of the Gaussian filter; a and b are used to define the size of the Gaussian filter; w(s,t) is calculated from Gaussian distribution and its expression is: Among them, σ represents the standard deviation of the Gaussian filter and controls the smoothness of the filter; Step 15: Data enhancement: The image is rotated 30 degrees clockwise and counterclockwise, flipped horizontally, flipped vertically, and scaled 0.8 to 1.2 times. The enhanced image I aug The expression is: I aug =T(I orig ); Where T represents the image transformation operation.

3. The method according to claim 1, characterized in that The step 2 comprises: Step 21. Construct VGGBlock convolution block: Initialize VGGBlock convolution block. First, define input channel in_channels, middle channel middle_channels and output channel out_channels. Input channel is used to define the number of image channels input to VGGBlock, which is 3 for RGB image. Middle channel is used to define the number of channels between two convolution operations. It is an internal parameter used to transfer features between convolution layers. Output channel is used to define the number of channels output by VGGBlock, which determines the number of channels of the image after passing through VGGBlock. Initialize the ReLU activation function and batch normalization layer. The ReLU activation function is initialized using nn.ReLU(inplace=True) to add nonlinearity. The inplace=True parameter will modify the input data in place. The batch normalization layer initializes the intermediate layer and the output layer nn.BatchNorm2d layers, corresponding to the number of intermediate channels and output channels respectively. Step 22, VGGBlock forward propagation: (a) The first convolution operation: The first convolution layer uses nn.Conv2d(in_channels, middle_channels, kernel_size = 3, padding = 1) to initialize the convolution layer, with a kernel size of 3×3 and an edge padding of 1 to keep the image size unchanged; batch normalization and ReLU activation: After applying batch normalization nn.BatchNorm2d(middle_channels), the ReLU activation function nn.ReLU(inplace = True) is used to activate the intermediate features; For the convolutional layer, the expression is: O = ReLU(BN(W*I+b)); Where: O represents the output feature map Output Feature Map; I represents the input feature map Input Feature Map; W represents the convolution kernel Kernel; * represents the convolution operation; b represents the bias term (Bias); BN represents the batch normalization operation; ReLU represents the activation function, which is defined as ReLU(x)=max(0,x); (b) Second convolution operation: The second convolution layer uses nn.Conv2d(middle_channels, out_channels, kernel_size=3, padding=1), keeping the convolution kernel size and edge padding unchanged; batch normalization and ReLU activation: apply batch normalization nn.BatchNorm2d(out_channels), and use ReLU activation function nn.ReLU(inplace=True) to activate output features; The batch normalization operation expression is: Where: x represents the output of the convolutional layer; μ represents the mean value within the batch; σ 2 represents the variance within the batch; ∈ represents a positive parameter; γ and β represent learned parameters for rescaling and offsetting the normalized values; Final output: The output after the last ReLU activation is regarded as the final output of the VGGBlock convolution block and is used in subsequent network layers or as a feature map. Step 23: Build the U-Net++ network structure: (c) Network initialization: define the number of filters at different levels as [32, 64, 128, 256, 512], which will determine the feature extraction capability of each level; initialize the encoder layer conv_{i,0} and the decoder layer conv_{i,j} of U-Net++ to ensure feature extraction and processing; (d) Encoder path, the input image I first passes through the first encoder level conv_{0,0}, which is the starting point of feature extraction; next, for the output of each encoder level, the maximum pooling operation MaxPool is performed to reduce the dimension of the feature map and increase the level of abstraction; this continues until the last encoder level conv_{4,0}, each level can capture different levels of image features; (e) Decoder path: First, the output of the deepest encoder is upsampled to increase the dimension of the feature map. The upsampled features are concatenated with the features of the corresponding encoder level through skip connections to preserve spatial information. The fused features are processed through the convolutional layers of the decoder to gradually reconstruct the feature map. This process is repeated in different decoder levels to gradually reconstruct high-resolution feature maps. (f) Output layer: At the end of the network, the final output of the decoder is passed through a convolutional layer to convert the number of channels of the feature map into the number of target categories; a softmax or sigmoid activation function is used to assign a probability or classification to each pixel; (g) Deep supervision. When deep supervision is enabled, the intermediate layers of the network will produce additional outputs. The auxiliary outputs help the network focus on deeper features during training. By calculating the loss of the auxiliary outputs and combining it with the main loss function, the model representation can learn complex features.

4. The method according to claim 1, characterized in that: The step 3 comprises: The goal of BCEDiceLoss loss function optimization is to minimize BCEDiceLoss to balance the classification accuracy of a single pixel and the continuity of the entire prediction area; its specific calculation includes: Binary cross entropy loss BCE, its expression is: where y i represents the true label, y i预测 represents the predicted probability; Dice loss is used to evaluate the spatial overlap between the predicted region and the true label, and its expression is: Here, smooth is a smoothing term used to avoid division by zero errors. The expression of the combined loss function BCEDiceLoss is: BCEDiceLoss=α·BCE+(1-α)·Dice; The parameter α is used to weigh the importance of BCE loss and Dice loss.

5. The method according to claim 1, characterized in that The step 4 comprises: Step 41: Image distortion correction: Load the camera calibration image, and obtain the checkerboard image used for camera calibration by loading the camera calibration image; use the Glob library to obtain the file path of the camera calibration image; Find the corners of the chessboard, use the camera calibration image, and use OpenCV's cv2.findChessboardCorners function to find the corners of the chessboard; Calibrate the camera and remove image distortion. Use the corner points of the chessboard and the corresponding real coordinate points to calibrate the camera. Calculate the camera matrix and distortion coefficients of the camera through the cv2.calibrateCamera function, and then use the cv2.undistort function to correct the image distortion. The distortion coefficients are expressed in polynomial form to represent the camera distortion, which includes radial distortion k1, k2, k3 and tangential distortion p1, p2. The expression of the camera matrix K is: Among them, f x and f y is the focal length, (c x ,c y ) are the pixel coordinates of the optical center; Step 42: Image reverse perspective: Select the key points of the inverse perspective transformation. The inverse perspective transformation requires four non-collinear points, which are expressed as P = {(x1, y1), (x2, y2), (x3, y3), (x4, y4)}. The four non-collinear points are selected on the original image to form the basis of the inverse perspective transformation and define the perspective area of ​​the image; Calculate the inverse perspective transformation matrix. The calculation of the inverse perspective transformation matrix is ​​based on the four key points in the selected original image and the four corresponding vertices of the target image. The inverse perspective transformation matrix is ​​obtained by solving a system of linear equations, using the relationship between the four points in the original image and the corresponding vertices of the target image. The four points P in the original image original ={(x1,y1),(x2,y2),(x3,y3),(x4,y4)}, the corresponding four vertices P in the target image target ={(u1,v1),(u2,v2),(u3,v3),(u4,v4)}, the inverse perspective transformation matrix M is calculated by the cv2.getPerspectiveTransform function, which is a 3x3 matrix; the inverse perspective transformation matrix M is obtained by solving the following linear equations: Among them, the M matrix represents the mapping relationship between the points in the original image and the corresponding points in the target image, thereby realizing the inverse perspective transformation; Perform inverse perspective transformation. The inverse perspective transformation function cv2.warpPerspective transforms the original image according to the calculated inverse perspective transformation matrix M. Given the original image I original And the inverse perspective transformation matrix M, perform the inverse perspective transformation to obtain the transformed image I transformed , whose expression is: I transformed =cv2.warpPerspective(I original ,M,target_size); Where target_size represents the target image size of the desired output; the inverse perspective transformation function uses the inverse perspective transformation matrix M to transform the original image I original Mapping to a new perspective or geometry to generate a transformed image I transformed ; Image processing and synthesis: After the inverse perspective transformation, the transformed image and the original image are processed and synthesized to obtain the final image after correcting the perspective distortion; the image is segmented and merged using the mask and the inverse mask; the mask is a matrix of the same size as the image, which is used to identify the area that needs to be inversely transformed; the inverse mask is the complement of the mask, which is used to retain the area that has not been transformed; the image after inverse perspective transformation is separated from the original image through the bit operation function, and merged in the appropriate area to obtain the final processed image; its expression is: masked_dst=cv2.bitwise_and(I transformed ,mask); masked_img=cv2.bitwise_and(I original ,inverse_mask); final_img=cv2.add(masked_dst, masked_img); Among them, I transformed I represents the image after inverse perspective transformation; original Represents the original image; mask represents the mask of the inverse perspective transformed area; inverse_mask represents the inverse mask of the untransformed area; masked_dst represents the area after the inverse perspective transformed image is applied with the mask; masked_img represents the area after the inverse mask is applied to the original image; final_img represents the final image that merges the transformed area and the untransformed area.

6. The method according to claim 1, characterized in that The step 5 comprises: Step 51, initialize the training configuration: set the training cycle epochs, which indicates the number of times the network will traverse the entire data set during training; set the batch size batch_size, which indicates the number of samples used for one training, affecting gradient estimation and memory usage; Step 52, optimizer selection and configuration: select optimizer to determine the weight of the updated network; set the learning rate lr to control the step size of the weight adjustment; set momentum for SGD, which helps to accelerate the optimization of SGD in the relevant direction and suppress oscillation; weight decay weight_decay is a regularization term used to prevent overfitting; Step 53, training loop: Forward propagation: input data passes through the network and calculates the output of each layer; loss calculation: use the loss function to calculate the difference between the predicted result and the true label; backward propagation: calculate the gradient of the loss function with respect to the network weight; gradient descent: update the network weight according to the calculated gradient; the update rule is defined by the optimizer; its expression is: Among them, w new and w old are the weights before and after the update, η is the learning rate, is the gradient of the loss function L with respect to the weight; Model evaluation: Use the validation dataset to check model performance and monitor overfitting; Step 54, learning rate adjustment: The learning rate scheduler is CosineAnnealingLR, which adjusts the learning rate according to the cosine function so that it first decreases and then increases in each cycle. Its expression is: Among them, η t is the learning rate at time t, η min and η max are the minimum and maximum values ​​of the learning rate, T cur is the current iteration number, T max is the maximum number of iterations in a cycle.

7. The method according to claim 1, characterized in that The step 6 comprises: Step 61: Saving and loading model parameters. After training is completed, the model parameters are saved to disk. Usually, the model with the best performance on the validation set is selected for saving. In the prediction stage, the trained model parameters are loaded from disk to ensure that an optimized model is used. Step 62, test set prediction, using the loaded model to predict the water level images in the test set; the model outputs the predicted water level position and related features for each test image; Step 63: Performance evaluation: comprehensively evaluate the performance of the model on the test set through evaluation indicators to quantify the application effect of the model in real scenarios. Step 64: Analyze the results of the model prediction to obtain the analysis results of the model; Step 65: Improvement suggestions: Improve the model and data processing flow based on the performance evaluation and analysis results.

8. A computer-readable storage medium, characterized in that: The computer-readable storage medium includes a stored program, wherein when the program is running, the electronic device where the computer-readable storage medium is located is controlled to execute the water level monitoring method based on deep learning as described in any one of claims 1 to 7.

9. An electronic device, characterized in that: include: one or more processors; Memory; And one or more computer programs, wherein the one or more computer programs are stored in the memory, and the one or more computer programs include instructions, which, when executed by the electronic device, enable the device to execute the water level monitoring method based on deep learning as described in any one of claims 1 to 7.

Citation Information

Cited By

  • Optical lens automatic focusing method and system

    CN119126326A

  • Model training method and device for long-tail noise, equipment and medium

    CN119888412A

  • Model Training Method, Apparatus, Device, and Medium for Long-Tail Noise

    CN119888412B

  • Hydraulic engineering management data processing method and system based on cloud computing

    CN122090359A

  • An urban waterlogging point non-contact water level depth intelligent monitoring method

    CN122714888A