A method, medium and device for H.264 video intelligent detection triggering based on reinforcement learning

By using a reinforcement learning-based approach, the system directly parses H.264 video streams to extract metadata from the coding domain, constructs multi-dimensional temporal state vectors, and optimizes the decision model. This solves the problems of computational resource consumption and detection reliability in AI analysis systems for fixed surveillance cameras, achieving low-cost and highly robust intelligent detection triggering.

CN122093583BActive Publication Date: 2026-11-24NINGBO BEILUN FIRST CONTAINER TERMINAL CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202610473273.0
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-04-10
Publication Date
2026-11-24
Estimated Expiration
2046-04-10

AI Technical Summary

Technical Problem

Existing technologies in real-time AI analysis systems based on fixed surveillance cameras suffer from high computational resource consumption and insufficient detection reliability. In particular, when processing multiple high-definition video streams, the traditional "decode first, then detect" process leads to computational resource bottlenecks, and existing triggering mechanisms are inefficient and susceptible to environmental noise.

Method used

By using a reinforcement learning-based approach, H.264 video streams are directly parsed to extract metadata such as motion vectors, macroblock types, quantization parameters, and compressed packet size. Multidimensional temporal state vectors are constructed, and the Q-Learning algorithm is used to optimize the decision model to select or skip detection actions, thereby achieving adaptive intelligent detection triggering.

Benefits of technology

Without performing complete image decoding, it effectively alleviates the computing power bottleneck of multi-channel video stream AI analysis, reduces system computing resource consumption, and improves detection accuracy and robustness, adapting to the real-time requirements of different monitoring scenarios.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122093583B_ABST
    Figure CN122093583B_ABST
Patent Text Reader

Abstract

This application discloses a method, medium, and device for intelligent detection triggering of H.264 video based on reinforcement learning. The method includes: real-time parsing of the H.264 video bitstream to directly extract metadata from the coding domain; constructing a multi-dimensional temporal state vector that integrates motion, coding, and temporal features based on this metadata; and inputting this vector into a pre-trained decision model to output a trigger command. The decision model is based on the Q-Learning algorithm, which selects the action to trigger or skip detection based on the current state by establishing and iteratively updating a Q-value table, and calculates a reward based on the action execution result to continuously optimize the decision strategy. This invention utilizes metadata from the coding domain for intelligent decision-making, fundamentally solving the computational bottleneck problem caused by full-frame decoding in multi-stream video AI analysis, and significantly reducing system computational resource consumption while ensuring detection accuracy.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application belongs to the field of video surveillance technology, specifically relating to a method, medium, and device for intelligent detection triggering of H.264 video based on reinforcement learning. Background Technology

[0002] In real-time AI analysis systems based on fixed surveillance cameras, the traditional "decode first, then detect" process has inherent performance bottlenecks. Even with compressed H.264 video streams, this process requires decoding each frame into raw pixel images before feeding them into the detection model, resulting in significant computational resource consumption.

[0003] Specifically, existing technologies face the following main problems: (1) Huge computational overhead caused by decoding: Video decoding is a computationally intensive operation. When processing multiple high-definition video streams, decoding each frame consumes a lot of CPU or hardware resources, becoming the main bottleneck of system computing power.

[0004] (2) The efficiency and robustness of existing triggering mechanisms are insufficient: In order to avoid the above decoding overhead, existing optimization schemes attempt to selectively execute the "decoding-detection" process through a certain triggering mechanism, but these mechanisms all have obvious defects.

[0005] (3) Pixel-based motion detection (such as background subtraction method): Although the computational cost is low, it depends on the decoded pixel data and is extremely sensitive to environmental noise (such as changes in lighting and shadows), which can easily generate a large number of false triggers, resulting in the high-computing-power detection model being invalidally called.

[0006] In summary, existing technologies lack an effective method to achieve low-cost, highly robust trigger detection by directly utilizing video stream information without performing complete image decoding. This prevents the system from achieving an optimal balance between computational resource consumption and detection reliability. Summary of the Invention

[0007] In view of the above problems, this application provides a technical solution for H.264 video intelligent detection triggering based on reinforcement learning, which is used to solve the technical problem of how to balance the real-time performance, accuracy and resource consumption of real-time AI detection of multiple fixed surveillance cameras under limited computing power conditions through intelligent analysis of encoding domain metadata based on reinforcement learning.

[0008] To achieve the above objectives, in a first aspect, this application provides a reinforcement learning-based intelligent detection triggering method for H.264 video, the method comprising: S1: Real-time parsing of H.264 video stream, directly extracting its coding domain metadata, which includes motion vectors, macroblock type, quantization parameters, frame type and compressed packet size; S2: Based on the encoded domain metadata, construct a multi-dimensional temporal state vector, which includes a motion feature dimension vector, an encoded feature dimension vector, and a temporal feature dimension vector; S3: Input the multidimensional temporal state vector into a predefined decision model and output a trigger command; the decision model performs decision-making and optimization through the following steps: S31: Establish a Q-value table and initialize the Q-value table. The Q-value table is used to store the Q-value corresponding to each state-action pair. The state is represented by the multi-dimensional temporal state vector, and the action includes triggering the intelligent detection operation or skipping the intelligent detection operation. S32: For the multidimensional time-series state vector at the current moment, query the Q-value table, select the action with the largest Q-value according to the Q-value table, and use the action with the largest Q-value as the trigger instruction; S33: Execute the selected action and calculate the immediate reward based on the execution result; where, when the selected action triggers a smart detection operation and detects a target, a positive reward is given; when the selected action triggers a smart detection operation but does not detect a target, a negative reward is given; when the selected action skips a smart detection operation, a delayed reward is given based on the detection result of subsequent frames or a preset rule. S34: Based on the immediate reward and the multidimensional temporal state vector of the next moment, the Q-Learning algorithm is used to update the Q value in the Q value table corresponding to the current state-action pair, thereby iteratively optimizing the decision model and realizing an adaptive triggering strategy.

[0009] Furthermore, the motion feature dimension vector is constructed based on the amplitude and direction statistical features of the motion vector, specifically including: S21: Calculate the motion intensity of each macroblock based on the motion vectors extracted from the H.264 video stream; S22: Set a dynamic threshold and determine macroblocks whose motion intensity exceeds the dynamic threshold as active macroblocks; S23: Based solely on the motion vector of the active macroblock, calculate the amplitude and orientation statistical features of the entire frame image to construct the motion feature dimension vector.

[0010] Furthermore, the encoded feature dimension vector is constructed based on the statistical features of the macroblock type and quantization parameters, specifically including: S24: Calculate the proportion of different types of macroblocks in a frame of an image to the total number of macroblocks, as a statistical feature of macroblock types; S25: Calculate the mean and variance of the quantization parameters of all macroblocks in the frame image as statistical characteristics of the quantization parameters; S26: Based on the statistical characteristics of the macroblock type and the statistical characteristics of the quantization parameters, the coding feature dimension vector is calculated.

[0011] Furthermore, the temporal feature dimension vector is constructed based on the changing trends of the compressed package size and / or frame type across multiple consecutive video frames, specifically including: S27: Using a sliding window of size N, calculate the exponentially weighted moving average of the compressed packet size for N consecutive frames within the sliding window, as the trend of the compressed packet size change; S28: Statistically analyze the frequency of I-frames, P-frames, and B-frames within the sliding window to show the changing trend of frame types; S29: Construct the temporal feature dimension vector based on the changing trend of the compressed package size and / or the changing trend of the frame type.

[0012] Furthermore, based on the aforementioned encoded domain metadata, a multi-dimensional temporal state vector is constructed, specifically including: Set a time series observation window of size M to cache the coding domain metadata and intermediate feature values ​​of the current time and the previous M time steps. The intermediate feature values ​​refer to the feature values ​​calculated based on the coding domain metadata and used to construct the coding feature dimension vector and the motion feature dimension vector. For each type of data cached within the time series observation window, an exponentially weighted moving average algorithm is used for time series fusion to calculate the final value of the corresponding dimension in the multidimensional time series state vector. The exponentially weighted moving average algorithm controls the weight of historical data through a decay factor between 0 and 1, so that data closer to the current time is assigned a higher weight.

[0013] Furthermore, step S34 specifically includes: S341: At decision time t, the state S composed of the multidimensional temporal state vector is observed. t ; S342: Based on state S t Action A is selected and executed from the Q-value table according to the ε-Greedy policy. t Action A t This includes triggering or skipping intelligent detection operations; S343: Receive the immediate reward R from environmental feedback. t And observe the new state S at the next decision moment. t+1 ; S344: Update the state-action pair (S) in the Q-value table according to the following Q-value update formula. t A t The corresponding Q value: Q(S)t A t )←Q(S t A t )+η×[R t +γ×max a' Q(S t+1 ,a')- Q(S t A t )]; Among them, Q(S) t A t ) indicates that in state S t Take action A t The original value estimate, where η is the learning rate. For discount factor, max a' Q(S t+1 ,a') indicates that in the next state S t+1 Below, for all possible actions a', the maximum Q value is taken, Q(S t+1 , a') indicates that in state S t+1 The value estimate of taking a certain action a'.

[0014] Furthermore, the method also includes: During the iterative optimization of the decision model, at least one of the following strategies is employed: learning rate decay strategy, exploration rate decay strategy, and model rollback strategy, in order to improve model convergence and stability. The learning rate decay strategy includes: gradually decreasing the learning rate η as the number of training iterations increases; The exploration rate decay strategy includes: gradually reducing the exploration rate ε in the ε-Greedy strategy as the number of training iterations increases; The model rollback strategy includes: periodically evaluating and saving a copy of the Q-value table with the best performance, and rolling back to the saved copy when the performance of the decision model deteriorates.

[0015] Furthermore, since the decision model serves as the primary decision model, the method also includes: A meta-decision module is constructed, which is used to evaluate the matching degree between the current environmental state and the training environment of the main decision model, and output the trust state of the main decision model. Step S3 specifically includes: The multidimensional temporal state vector is simultaneously input into the main decision model and the meta-decision module; Based on the trust status output by the meta-decision module, execute the branch operation: If the trust state is trust, then the trigger command output by the master decision model is adopted; If the trust status is distrust, then a conservative strategy is executed and model fine-tuning is initiated; The conservative strategy includes ignoring the output of the main decision model and forcibly generating a trigger command to execute the intelligent detection operation. The initial model fine-tuning includes: using empirical data consisting of the current state, action, immediate reward, and the state at the next moment, and updating the Q-value table of the master decision model in a progressive fine-tuning manner based on the empirical data. The update magnitude of the Q-value table by the progressive fine-tuning method is less than the update magnitude of the Q-value table when iteratively optimizing using the Q-Learning algorithm in step S34.

[0016] In a second aspect, this application provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the reinforcement learning-based H.264 video intelligent detection triggering method as described in the first aspect of this application.

[0017] In a third aspect, this application provides an electronic device having a computer program stored thereon, including a processor and a storage medium, wherein the computer program is stored on the storage medium, and when executed by the processor, the computer program implements the reinforcement learning-based H.264 video intelligent detection triggering method as described in the first aspect of this application.

[0018] Unlike existing technologies, the above technical solution involves a reinforcement learning-based intelligent detection triggering method, medium, and device for H.264 video. The method includes: real-time parsing of the H.264 video stream to directly extract metadata such as motion vectors, macroblock types, quantization parameters, frame types, and compressed packet sizes; constructing a multi-dimensional temporal state vector integrating motion, coding, and temporal features based on this metadata; and inputting this vector into a pre-trained decision model to output a trigger command. The decision model is based on the Q-Learning algorithm, which establishes and iteratively updates a Q-value table, selects actions to trigger or skip detection based on the current state, and calculates rewards based on the action execution results to continuously optimize the decision strategy. The core of this invention is to bypass the computationally intensive decoding stage in the traditional "decode first, detect later" process, utilizing metadata from the coding domain for intelligent decision-making. This fundamentally solves the computational bottleneck problem caused by full-frame decoding in multi-stream video AI analysis, achieving a significant reduction in system computational resource consumption while ensuring detection accuracy.

[0019] The above description of the invention is merely an overview of the technical solution of this application. In order to enable those skilled in the art to better understand the technical solution of this application and to implement it based on the description and drawings, and to make the above-mentioned objectives and other objectives, features and advantages of this application easier to understand, the following description is provided in conjunction with the specific embodiments and drawings of this application. Attached Figure Description

[0020] The accompanying drawings are only used to illustrate the principles, implementation methods, applications, features, and effects of specific embodiments of this application and other related content, and should not be considered as limitations on this application.

[0021] In the accompanying drawings of the instruction manual: Figure 1 A flowchart illustrating the reinforcement learning-based intelligent detection triggering method for H.264 video according to the first exemplary embodiment of this application; Figure 2 This is a flowchart of the reinforcement learning-based intelligent detection triggering method for H.264 video as described in the second exemplary embodiment of this application; Figure 3 A flowchart of the reinforcement learning-based intelligent detection triggering method for H.264 video according to the third exemplary embodiment of this application; Figure 4 This is a flowchart of the reinforcement learning-based intelligent detection triggering method for H.264 video as described in the fourth exemplary embodiment of this application; Figure 5 This is a flowchart of the reinforcement learning-based intelligent detection triggering method for H.264 video as described in the fifth exemplary embodiment of this application; Figure 6 This is a schematic diagram of an electronic device according to an exemplary embodiment of this application; The reference numerals used in the above figures are explained as follows: 10. Electronic equipment; 101. Processor; 102. Storage medium. Detailed Implementation

[0022] To explain in detail the possible application scenarios, technical principles, specific feasible solutions, and the objectives and effects that this application can achieve, the following detailed description is provided in conjunction with the listed specific embodiments and accompanying drawings. The embodiments described herein are only used to more clearly illustrate the technical solutions of this application, and are therefore only examples, and should not be used to limit the scope of protection of this application.

[0023] In the first aspect, such as Figure 1 As shown, this application provides a reinforcement learning-based intelligent detection triggering method for H.264 videos, the method comprising: S1: Real-time parsing of H.264 video streams, directly extracting their encoding domain metadata; S2: Construct a multi-dimensional temporal state vector based on the aforementioned encoded domain metadata; S3: Input the multidimensional temporal state vector into a predefined decision model and output a trigger command.

[0024] In step S1, the encoding domain metadata refers to the auxiliary information generated during the H.264 video encoding process, which describes the video compression features and dynamic changes in content. It can be extracted without decoding and restoring the pixel image.

[0025] The H.264 bitstream consists of a series of Network Abstraction Layer Units (NALs), each containing explicit header information and data. The coded domain metadata is stored in the NAL unit header and internal structures such as slices and macroblocks. This metadata can be read by a lightweight bitstream parser (which can be customized based on FFmpeg's libavcodec library, only calling the parsing function rather than the full decoding function), without performing computationally intensive operations such as inverse transformation, dequantization, and motion compensation during the decoding process.

[0026] When extracting encoded domain metadata, the raw NAL unit data packets can be obtained in real time from the RTSP camera video stream or local H.264 file. Then, the encoded domain metadata can be extracted from the raw NAL unit data packets. The extracted content specifically includes: Motion vectors: Read from the macroblock structure of P-frames or B-frames, including horizontal (MV) values. x ) and vertical (MV) y The displacement information in the direction is readily available data calculated by the encoder during the motion estimation stage.

[0027] Macroblock type: Extracted from the macroblock header information, it identifies the coding mode used by the macroblock (such as inter-frame prediction, intra-frame prediction, skip mode, etc.).

[0028] Quantization parameters: These are parameters that reflect the degree of quantization during video compression, read from structures such as Picture Parameter Set (PPS) and Slice Header.

[0029] Frame type: Determined by NAL unit type or Slice Header, it is divided into I-frame (key frame, independently coded), P-frame (forward prediction frame, coded based on the previous I / P frame), and B-frame (bidirectional prediction frame, coded based on the preceding and following I / P frames).

[0030] Compressed packet size: The size of the data packet corresponding to each NAL unit or each frame is statistically analyzed, which directly reflects the amount of information in the frame content.

[0031] In step S2, the multidimensional temporal state vector includes a motion feature dimension vector, an encoding feature dimension vector, and a temporal feature dimension vector. The multidimensional temporal state vector is a vector that comprehensively and dynamically describes the current video scene state, providing input for the decision-making model.

[0032] Dynamic changes in video scenes require comprehensive judgment based on multi-dimensional features. Single features are easily affected by environmental noise (such as changes in lighting and swaying tree shadows), leading to misjudgments. Multi-dimensional temporal state vectors integrate motion, encoding, and temporal features, while introducing temporal windows and exponentially weighted averaging. This not only covers the core information of scene dynamics but also captures the temporal evolution trend of features, improving the robustness and accuracy of state description.

[0033] In step S3, the decision model is built based on reinforcement learning. It takes a multi-dimensional temporal state vector as input and outputs instructions to trigger or skip intelligent detection. It is continuously optimized through interaction with the environment. The core components include the Q-value table and the Q-Learning algorithm.

[0034] like Figure 2 As shown, the decision-making model makes decisions and optimizes through the following steps: S31: Establish a Q-value table and initialize the Q-value table. The Q-value table is used to store the Q-value corresponding to each state-action pair. The state is represented by the multi-dimensional temporal state vector, and the action includes triggering the intelligent detection operation or skipping the intelligent detection operation. S32: For the multidimensional time-series state vector at the current moment, query the Q-value table, select the action with the largest Q-value according to the Q-value table, and use the action with the largest Q-value as the trigger instruction; S33: Execute the selected action and calculate the immediate reward based on the execution result; where, when the selected action triggers a smart detection operation and detects a target, a positive reward is given; when the selected action triggers a smart detection operation but does not detect a target, a negative reward is given; when the selected action skips a smart detection operation, a delayed reward is given based on the detection result of subsequent frames or a preset rule. S34: Based on the immediate reward and the multidimensional temporal state vector of the next moment, the Q-Learning algorithm is used to update the Q value in the Q value table corresponding to the current state-action pair, thereby iteratively optimizing the decision model and realizing an adaptive triggering strategy.

[0035] In step S31, the Q-value table is the experience base of the decision model. During initialization, the range of the state space and action space must be determined first. The state space is composed of the discretization results of multi-dimensional temporal state vectors (each feature dimension is divided into multiple levels according to physical meaning and numerical range, and combined to form all possible discrete states); the action space is a binary set, namely "triggering intelligent detection operation" and "skipping intelligent detection operation".

[0036] During initialization, the Q values ​​of all "state-action pairs" in the Q-value table are set to random small values ​​(such as random numbers in the range of [-0.1, 0.1]) to provide an initial basis for subsequent iterative optimization and avoid excessive interference from initial value deviations on the model's learning direction.

[0037] In step S32, under the current scene state, selecting the action with the largest Q-value means that this action brings the best long-term benefit in historical interactions, which is in line with the core objective of reinforcement learning: "maximizing cumulative reward." For the multi-dimensional temporal state vector at the current moment, its corresponding discrete state is first determined, and then the Q-values ​​of two actions (trigger / skip) under this discrete state are queried in the Q-value table. The action with the larger Q-value is selected as the trigger instruction. If the Q-values ​​of the two actions are equal, "skip intelligent detection operation" can be selected by default to save computing power.

[0038] In step S33, the immediate reward is the feedback from the environment to the action decision. By quantifying the quality of the action result, the model is guided to adjust the Q-value estimation, enabling the model to gradually learn a strategy that meets the goals of high detection accuracy and low computational consumption. If the triggering instruction is "trigger intelligent detection operation", a high-computing-power AI detection model (such as YOLO or Faster R-CNN) is invoked to decode and detect the target in the current frame; if it is "skip intelligent detection operation", the decoding and detection process is not executed.

[0039] When the action is "triggering intelligent detection operation" and a target is detected (True Positive), a positive reward (such as +1.0) is given to encourage the model to accurately trigger detection when a target is present.

[0040] When the action is "triggering intelligent detection operation" but no target is detected (False Positive): give a negative reward (e.g., -0.1) to punish the model for meaningless computational consumption.

[0041] When the action is "skip smart detection operation", the detection results of subsequent frames or preset rules determine whether there is a missed detection. If there is no target (True Negative), a positive reward (such as +0.1) is given; if there is a missed detection (False Negative), a negative reward (such as -0.5) is given, which satisfies the need to balance saving computing power and avoiding missed detection.

[0042] In step S34, the Q-Learning algorithm updates the Q-value using Temporal Difference (TD) error, combining the current immediate reward with the optimal expected reward for the next state. This allows the Q-value to gradually approach the true state-action value, achieving iterative optimization of the model. As the number of interactions increases, the Q-value table gradually converges, and the decision model gradually learns the optimal triggering strategy adapted to the specific monitoring scenario, achieving adaptive adjustment.

[0043] The above solution eliminates the need for complete decoding of the H.264 video stream. State determination can be achieved simply by extracting metadata from the encoded domain through lightweight parsing, effectively alleviating the computational bottleneck in multi-channel video analysis and adapting to edge computing or server-side scenarios with limited computing power. The multi-dimensional temporal state vector integrates motion, encoding, and temporal features, comprehensively describing scene dynamics and avoiding the problem of single features being affected by environmental noise. For example, it effectively distinguishes between "pedestrian intrusion" (significant changes in motion intensity and direction consistency) and "tree shadow swaying" (chaotic motion, stable trend), reducing the probability of false triggers and missed detections. Based on the iterative optimization mechanism of the Q-Learning algorithm, the decision model can learn autonomously through continuous interaction with the environment, adapting to different monitoring scenarios (such as daytime streets and nighttime warehouses) without manual parameter tuning. As running time increases, the strategy is continuously optimized, gradually improving the balance between real-time performance, accuracy, and resource consumption.

[0044] like Figure 3 As shown, the motion feature dimension vector is constructed based on the statistical features of the magnitude and direction of the motion vector, specifically including: S21: Calculate the motion intensity of each macroblock based on the motion vectors extracted from the H.264 video stream; S22: Set a dynamic threshold and determine macroblocks whose motion intensity exceeds the dynamic threshold as active macroblocks; S23: Based solely on the motion vector of the active macroblock, calculate the amplitude and orientation statistical features of the entire frame image to construct the motion feature dimension vector.

[0045] In this embodiment, motion intensity is a parameter used to measure the intensity of motion of a single macroblock. It is calculated based on the magnitude of the motion vector and can directly reflect the degree of dynamic change of the image region corresponding to the macroblock.

[0046] Active macroblocks are macroblocks whose motion intensity exceeds the dynamic threshold. They represent regions in the image where significant motion actually occurs, excluding false motion caused by background noise (such as slight swaying of leaves or gradual changes in light). They are the core data foundation for calculating motion feature dimension vectors.

[0047] Amplitude statistical characteristics refer to the characteristics obtained by statistical analysis of the motion intensity of active macroblocks, such as average motion intensity and motion intensity variance, which reflect the overall intensity of motion and distribution differences in active regions.

[0048] Directional statistical features refer to the features obtained by statistically analyzing the movement direction of active macroblocks, such as the directional consistency index and directional distribution entropy. They reflect the degree of concentration of movement direction within an active region and can be used to distinguish different movement scenarios such as "same-direction traffic flow" and "chaotic crowds".

[0049] In step S21, the motion vector is the displacement vector calculated by the H.264 encoder during inter-frame prediction to match the positions of the current macroblock and the macroblock in the reference frame. Its amplitude directly corresponds to the motion distance of the macroblock and can be used as a core indicator to measure motion intensity. By calculating the amplitude of the motion vector, discrete displacement information is transformed into continuous motion intensity values, which facilitates subsequent quantitative analysis.

[0050] From the coded domain metadata parsed in step S1, obtain the motion vector (MV) of each macroblock (especially macroblocks in P-frames and B-frames). x MV y ), where MV x For horizontal displacement, MV y This represents the vertical displacement. The motion intensity of each macroblock is calculated using the Euclidean distance formula, as follows: The higher the motion intensity value, the more intense the macroblock motion.

[0051] In step S22, the dynamic threshold is adaptively adjusted based on historical motion data to ensure that the threshold always matches the noise level of the current scene, guaranteeing that only truly significant motion macroblocks are identified as active macroblocks. Specifically, the dynamic threshold confirmation process is as follows: Macroblock motion intensity data from the past N frames (recommended N=30, corresponding to 1 second) are selected to construct a historical motion intensity dataset. The dynamic threshold is determined using statistical methods. For example, to calculate the mean μ and standard deviation σ of historical data, set... =μ+2σ, ensuring that the motion intensity of more than 95% of noise interference macroblocks is below this threshold; or the threshold can be updated in real time through a sliding window, and the dynamic threshold is adjusted accordingly when the scene noise level changes (such as when a sudden gust of wind causes the shadows of trees to sway more).

[0052] Then the motion intensity of each macroblock is... With dynamic threshold Perform a comparison, if > If the current macroblock is active, it will be marked as an active macroblock and included in the subsequent feature calculation; otherwise, it will be an inactive macroblock and excluded from motion feature analysis. Used to distinguish between real motion and background noise, preferably, (in pixels), meaning that motion vector magnitude less than 2 pixels is considered noise.

[0053] In step S23, the motion information of a single macroblock cannot reflect the overall scene motion state. By statistically analyzing the motion intensity and direction of all active macroblocks, globally representative features can be extracted to form a motion feature dimension vector that can describe the scene motion pattern, providing accurate motion state input for the decision model.

[0054] When calculating the amplitude statistical characteristics, the calculation includes calculating the average motion intensity of all active macroblocks and the variance of the motion intensity of active macroblocks. The average active motion intensity is calculated as (∑active macroblock motion intensity) / number of active macroblocks. The average active motion intensity reflects the overall intensity of motion within the active region. For example, the average active motion intensity in a "vehicles rapidly entering" scene is much higher than in a "pedestrians walking slowly" scene. The motion intensity variance reflects the difference in the intensity of motion within the active region. A large variance indicates that there are targets with different speeds within the scene (e.g., "vehicles and pedestrians mixed together"), while a small variance indicates that the motion intensity of targets within the scene is relatively uniform (e.g., "uniform traffic flow in the same direction").

[0055] When calculating directional statistical characteristics, the calculation includes the motion direction consistency index and direction distribution entropy. The motion direction consistency index is obtained by calculating the deviation between the average direction of all active macroblock motion vectors and the direction of each vector. The calculation formula is: Motion direction consistency index = ||∑(active macroblock motion vector unit vector)|| / number of active macroblocks, where the motion vector unit vector = (MV x / Exercise intensity, MV y The motion direction consistency index ranges from [0,1], with values ​​close to 1 indicating highly consistent motion directions (e.g., "vehicles moving straight") and values ​​close to 0 indicating chaotic motion directions (e.g., "crowded crowds"). The direction distribution entropy is calculated based on the angular distribution of motion directions of active macroblocks. Smaller entropy values ​​indicate a more concentrated direction distribution, while larger entropy values ​​indicate a more dispersed direction distribution. It can serve as a supplementary feature to the direction consistency index, further distinguishing different motion scenarios.

[0056] When constructing the motion feature dimension vector, the average active motion intensity, motion intensity variance, motion direction consistency index, direction distribution entropy, and other features calculated above are normalized (e.g., mapped to the [0,1] interval) and then combined to form the motion feature dimension vector, ensuring that the magnitude of each feature is consistent and avoiding excessive influence of a single feature on the state judgment.

[0057] The above scheme effectively eliminates non-target motion caused by background noise (such as swaying leaves or changes in lighting) by using dynamic thresholds to filter active macroblocks. This allows motion feature calculations to focus on truly significant motion regions, improving the effectiveness and reliability of features and reducing the probability of misjudgment by the decision model. By fusing amplitude and direction statistical features, it reflects both the intensity of motion and the distribution pattern of motion direction, enabling the differentiation of different types of motion scenarios (such as "same-direction traffic flow," "chaotic crowds," and "single pedestrian walking"), providing the decision model with richer motion state information and helping to accurately determine whether detection needs to be triggered.

[0058] In some embodiments, such as Figure 4As shown, the encoded feature dimension vector is constructed based on the statistical features of the macroblock type and quantization parameters, specifically including: S24: Calculate the proportion of different types of macroblocks in a frame of an image to the total number of macroblocks, as a statistical feature of macroblock types; S25: Calculate the mean and variance of the quantization parameters of all macroblocks in the frame image as statistical characteristics of the quantization parameters; S26: Based on the statistical characteristics of the macroblock type and the statistical characteristics of the quantization parameters, the coding feature dimension vector is calculated.

[0059] In step S24, the H.264 encoder selects different encoding modes (macroblock types) based on the content complexity of the region where the macroblock is located and the matching status of the reference frame. The distribution of different macroblock types directly reflects the dynamic changes and complexity of the frame content. By statistically analyzing the proportion of each type of macroblock, discrete macroblock type information can be transformed into continuous statistical features, providing input for the encoding feature dimension vector.

[0060] Specifically, firstly, from the coded domain metadata obtained in step S1, the types of all macroblocks within a frame are extracted and categorized according to coding mode into intra-frame prediction macroblocks, inter-frame prediction macroblocks (including P-frame forward prediction and B-frame bidirectional prediction), and skip mode macroblocks. The number of macroblocks in each category is then counted. For each macroblock category, the proportion of its quantity to the total number of macroblocks is calculated using the following formula: Proportion of a macroblock category = (Number of macroblocks of that category / Total number of macroblocks) × 100%. For example, if the total number of macroblocks in a 1080p video frame is 8160, and the number of skip mode macroblocks is 6000, then the proportion of skip mode macroblocks = (6000 / 8160) × 100% ≈ 73.5%. Then, the proportion of key macroblock types is selected as statistical features, such as the proportion of skip mode macroblocks, the proportion of intra-frame prediction macroblocks, and the proportion of inter-frame prediction macroblocks. A high percentage of skip mode macroblocks indicates that the frame content is similar to the reference frame (such as a static background frame), while a high percentage of intra-prediction macroblocks indicates that the frame content is complex or the scene changes drastically (such as a target suddenly entering). These features can directly reflect the dynamic state of the scene.

[0061] In step S25, the quantization parameter is a core parameter controlling the degree of lossy compression in H.264 encoding. The encoder dynamically adjusts the quantization parameter based on factors such as macroblock content complexity and target bitrate (complex regions typically use lower quantization parameters to preserve details, while simple regions use higher quantization parameters to save bitrate). By statistically analyzing the mean and variance of the intra-frame quantization parameters, scene complexity and regional difference information can be indirectly obtained, supplementing non-motion variations (such as texture abrupt changes and illumination changes) that motion features cannot cover.

[0062] Specifically, the quantization parameters (QP values, ranging from 0 to 51) of each macroblock within a frame are first obtained from the Picture Parameter Set (PPS), Slice Header, and macroblock header information in the coding domain metadata. Then, the average quantization parameter is calculated by taking the arithmetic mean of the QP values ​​of all macroblocks. A higher average quantization parameter indicates a higher overall compression level of the frame and potentially a more complex scene. Next, the variance of the quantization parameters is calculated using the variance formula to determine the dispersion of the QP values ​​of all macroblocks. A larger variance indicates a more significant difference in complexity between different regions within the frame. For example, the variance in a scene with a "static background (high QP) + textured target (low QP)" will be significantly higher than that in a scene with a "uniform background."

[0063] In step S26, macroblock type statistical features reflect the coding pattern distribution of the frame content (difference from the reference frame), and quantization parameter statistical features reflect the complexity of the frame content and compression strategy. The two describe key information in the video coding process from different perspectives. When combined, they can comprehensively cover the core features of the coding domain, providing a more complete scene state input for the decision model. In particular, they can capture non-motion changes (such as sudden changes in illumination and increased texture) that cannot be reflected by motion features.

[0064] Specifically, the proportion of skip mode macroblocks, the proportion of intra-frame predicted macroblocks (macroblock type statistical features), normalized average QP, and normalized QP variance (quantization parameter statistical features) can be selected as the coding feature dimension vector. These features can most intuitively reflect the scene dynamics and complexity changes.

[0065] The above scheme can capture non-motion changes (such as image brightness changes caused by sudden changes in illumination, or increased texture caused by wall advertisements) through encoded features. These changes may be accompanied by the appearance of a target (such as a person posting an advertisement). The introduction of encoded features makes the scene state judgment more comprehensive and reduces the risk of missed detections. Encoded features and motion features describe the scene state from different dimensions. The combination of the two can cover both "motion changes" and "non-motion changes". For example, "motion features show no significant motion, but encoded features show a sharp drop in average QP (increased texture)", which may be due to a static target (such as a stationary vehicle) entering the scene. In this case, the decision model can trigger detection based on encoded features, improving the comprehensiveness of detection.

[0066] In some embodiments, such as Figure 5 As shown, the temporal feature dimension vector is constructed based on the changing trends of the compressed package size and / or frame type of multiple consecutive video frames, specifically including: S27: Using a sliding window of size N, calculate the exponentially weighted moving average of the compressed packet size for N consecutive frames within the sliding window, as the trend of the compressed packet size change; S28: Statistically analyze the frequency of I-frames, P-frames, and B-frames within the sliding window to show the changing trend of frame types; S29: Construct the temporal feature dimension vector based on the changing trend of the compressed package size and / or the changing trend of the frame type.

[0067] In step S27, the size of a single frame encoded compressed packet is greatly affected by instantaneous noise (such as encoding error), making it difficult to accurately reflect the scene change trend. By covering N consecutive frames of data with a sliding window and combining it with an exponentially weighted moving average to highlight the influence of recent data, noise can be smoothed and the medium- to long-term change trend of the encoded compressed packet size can be captured. This trend is highly correlated with the change in scene information and can serve as an important basis for determining whether detection needs to be triggered.

[0068] Specifically, the compressed file size of each frame is obtained in real time from the encoded domain metadata parsed by S1. A sliding window of length N (recommended N=6, corresponding to 0.2 seconds for 30fps video) is constructed, and the compressed file size data of the latest N frames is stored in the window. t Size t-1 Size t-N+1 ).

[0069] Then, based on the exponentially weighted moving average rule, weights w are assigned to the compressed file sizes at different times within the window. k The weighting coefficient decays exponentially, and the calculation formula is: w k =α k Where α is the time decay factor (α=0.8 is recommended), k is the time offset of the frame (k=0 corresponds to the current frame, k=1 corresponds to the previous frame, ..., k=N-1 corresponds to the earliest frame in the window), recent frames (small k value) have high weight, and distant frames (large k value) have low weight.

[0070] Then, the EWMA (Exponential Weighted Moving Average) value of the compressed file size within the sliding window is calculated using the following formula: ; in, These are weighting coefficients. It is the past number The size of the compressed file at each point in time. It is the sum of all weights, used for normalization to avoid the window length affecting the results.

[0071] Then, the EWMA of two adjacent sliding windows is calculated. SizeThe difference or ratio yields the rate of change of the compressed file size. This rate of change is a quantitative indicator of the trend of the compressed file size change. A high rate of change indicates a significant change in the amount of scene information (such as the entry of a target), while a low rate of change indicates that the amount of scene information is stable (such as a static background).

[0072] In step S28, the frame type sequence (I / P / B frame arrangement) of the H.264 video is closely related to scene changes. I-frames (keyframes) are encoded independently, containing complete frame information, and are typically inserted at the beginning of a GOP (Group of Pictures) or when the scene changes drastically. P / B frames are encoded based on reference frames, and the proportion of P / B frames is high when the scene is calm. By statistically analyzing the frame type frequency within the sliding window, the changing patterns of the frame sequence can be captured, indirectly reflecting the stability of the scene. For example, a sudden increase in the frequency of I-frames may indicate a scene switch or drastic change.

[0073] Specifically, within the sliding window, the type (I-frame, P-frame, B-frame) of each frame is extracted from the encoding domain metadata, and the number of frames of each type is counted (denoted as Count). I ,Count P ,Count B If the total number of frames in the window is Count, then the total number of frames in the window is Count. I +Count P +Count B =N. Then calculate the frequencies of I-frames, P-frames, and B-frames respectively, using the formula: Freq I =Count I / N, Freq P =Count P / N, Freq B =Count B / N, where the frequency ranges from [0,1], and the sum of the three is 1. The frame type change trend is analyzed by comparing the frequency differences between adjacent sliding windows. For example, the Freq of the current window and the previous window is calculated. I The difference, if the difference ΔFreq I A significant increase (e.g., from 0.167 to 0.333) indicates an increased frequency of I-frames, which may be due to drastic scene changes (e.g., rapid target movement, camera shake); if the frequency of each frame type remains stable over a long period (e.g., Freq), then the I-frame frequency is likely to be higher. I Maintain at 0.1-0.2, Freq P Maintaining a value between 0.7 and 0.8 indicates a stable scene (such as a static monitoring scene). Simultaneously, the frame type frequency can be compared with a preset threshold, such as when Freq... I When Freq > 0.25, the frame type change trend is judged as "drastic". I When the value is less than 0.1, the trend of frame type change is determined to be "stable".

[0074] In step S29, motion features and coding features mainly reflect the scene state in a single frame or instant, while temporal features can capture the dynamic evolution of the scene state by analyzing the changing trends of multiple consecutive frames. For example, "the size of the compressed package continues to increase + the frequency of I-frames increases" may indicate that the target gradually enters and causes the scene complexity to increase. The introduction of temporal features upgrades the state judgment from "instantaneous snapshot" to "dynamic process analysis", improving the decision model's ability to predict scene changes.

[0075] Specifically, the rate of change in compressed packet size obtained in step S27 and the rate of change in frame type frequency obtained in step S28 (e.g., ΔFreq) are used to calculate the changes in the compressed packet size. I ΔFreq P Quantization processing is performed, for example, dividing the rate of change in compressed package size into three levels: "low change (0-0.2)", "medium change (0.2-0.5)", and "high change (0.5-1.0)", and mapping them to normalized values ​​of [0, 0.5, 1.0]; and quantifying the frame type frequency change (such as ΔFreq). I ΔFreq P Similar normalization is also performed to ensure that the temporal features are consistent in magnitude with the motion features and coding features. The normalized features such as the rate of change of compressed package size, the frequency change of frame type, the variance of compressed package size EWMA, and the entropy of frame type frequency are combined in a fixed order to form a temporal feature dimension vector.

[0076] The above-described scheme, by analyzing the temporal trends of multiple consecutive frames, can capture the dynamic evolution of the scene in advance (such as the gradual entry of a target causing the compressed file size to continuously increase). Compared with decision-making methods that rely solely on single-frame features, it can detect potential targets earlier and reduce the probability of missed detections. It is particularly suitable for monitoring scenarios where the target moves slowly or the scene changes gradually. The temporal features are smoothed by sliding windows and weighted averaging to make the features more stable and reliable. For example, the size of a single-frame compressed file may increase sharply due to encoding errors, but the temporal trend shows overall stability. The decision model can avoid false detections due to instantaneous noise, saving computing power.

[0077] In some embodiments, a multidimensional temporal state vector is constructed based on the encoded domain metadata, specifically including: S601: Set a time-series observation window of size M to cache the coding domain metadata and intermediate feature values ​​of the current time and the previous M time steps. The intermediate feature values ​​refer to the feature values ​​calculated based on the coding domain metadata and used to construct the coding feature dimension vector and the motion feature dimension vector. S602: For each type of data cached within the time series observation window, the exponentially weighted moving average algorithm is used for time series fusion to calculate the final value of the corresponding dimension in the multidimensional time series state vector; wherein, the exponentially weighted moving average algorithm controls the weight of historical data through a decay factor between 0 and 1, so that the data closer to the current time is given a higher weight.

[0078] In step S601, the metadata and intermediate feature values ​​of the coded domain of a single frame can only reflect the instantaneous scene state and are easily affected by random noise (such as instantaneous light flicker and coding errors), resulting in a one-sided state description. By caching M consecutive frames of data through a temporal observation window, the temporal information of multiple frames can be fused to capture the dynamic evolution of the scene state and improve the robustness and reliability of the state vector.

[0079] Specifically, the window size M can be determined by combining the monitoring video frame rate (e.g., 30fps) with the time scale of scene motion characteristics. Preferably, M is 6 (corresponding to a 0.2-second time span in 30fps video). This size can cover most of the time-series information of meaningful motion (e.g., pedestrian movement across frames) while avoiding the computational latency and increased memory usage caused by an excessively large window. After receiving each new frame of H.264 video data, the new data is stored in the time-series observation window after parsing the encoded domain metadata and calculating intermediate feature values. If the window data volume has reached M, the earliest frame is deleted before storing the new data, ensuring that the window always maintains continuous data of M frames.

[0080] In step S602, the traditional equal-weighted averaging method treats recent and distant data as equally important, failing to highlight the impact of the latest scene changes and potentially causing the state vector to lag behind the actual scene dynamics. The EWMA algorithm assigns higher weights to recent data through a decay factor, making the fused features more closely match the current scene state, while smoothing out noise interference from distant data, achieving the dual effect of "dynamic tracking + noise suppression".

[0081] For different types of intermediate feature values, a differentiated attenuation factor is set based on their time sensitivity differences to ensure optimal time-series fusion results. The different types of intermediate feature values ​​specifically include: Intermediate motion features (such as active macroblock motion intensity and motion region coverage): are sensitive to scene changes. The preferred value is α=0.9 (the weight decay of recent data is slower, and some historical motion trends are preserved). Intermediate features of the coding class (such as the proportion of macroblock types and normalized quantization parameters): the changes are relatively gradual. Preferably, the value of α is 0.7-0.8 (recent data has higher weight, and the coding strategy can be adjusted quickly). Intermediate features of time series (such as the rate of change of compressed file size): need to balance short-term fluctuations and long-term trends, preferably α=0.85.

[0082] For a certain intermediate feature value of M frames within the time-series observation window (such as the motion intensity x of the active macroblock in the i-th frame), i The EWMA algorithm is used to calculate the fused value X, and the formula is: ; Where t is the current frame time, x t-k This is the intermediate feature value of frame tk (k=0 corresponds to the current frame, k=1 corresponds to the previous frame, ..., k=M-1 corresponds to the earliest frame within the window); denominator This is the sum of weights used for normalization to avoid the influence of window size M on the fusion result.

[0083] The above EWMA temporal fusion calculation is performed on each dimension of the motion feature dimension vector, the coding feature dimension vector, and the temporal feature dimension vector. All the fused dimensions are combined in a preset order (such as motion feature → coding feature → temporal feature) to form the final multi-dimensional temporal state vector, ensuring that each dimension of the vector incorporates M-frame temporal information and can comprehensively and dynamically describe the current scene state.

[0084] The above scheme fuses multi-frame data through a temporal observation window, effectively filtering out instantaneous noise in single-frame data (such as sudden changes in compressed packet size due to encoding errors, or false motion caused by brief changes in lighting and shadows). This makes the state vector more reflective of the true dynamics of the scene, reducing false triggers or missed detections caused by noise interference in the decision-making model. The EWMA algorithm assigns higher weights to recent data, ensuring that the state vector can quickly track scene changes (such as a sudden increase in motion intensity caused by a target's sudden entry), avoiding state lag caused by equal-weighted averaging, balancing the needs of "temporal smoothing" and "dynamic response," and adapting to the timeliness requirements of real-time monitoring scenarios.

[0085] In some embodiments, step S34 specifically includes: S341: At decision time t, the state S composed of the multidimensional temporal state vector is observed. t ; S342: Based on state S t Action A is selected and executed from the Q-value table according to the ε-Greedy policy. t Action A t This includes triggering or skipping intelligent detection operations; S343: Receive the immediate reward R from environmental feedback. t And observe the new state S at the next decision moment. t+1 ; S344: Update the state-action pair (S) in the Q-value table according to the following Q-value update formula. t A t The corresponding Q value: Q(S) t A t )←Q(S t A t )+η×[R t +γ×max a' Q(S t+1 ,a')- Q(S t A t )]; Among them, Q(S) t A t ) indicates that in state S t Take action A t The original value estimate, where η is the learning rate. For discount factor, max a' Q(S t+1 ,a') indicates that in the next state S t+1 Below, for all possible actions a', the maximum Q value is taken, Q(S t+1 , a') indicates that in state S t+1 The value estimate of taking a certain action a'.

[0086] In step S341, state S t First, it undergoes discretization processing, mapping it to discrete state indices in the Q-value table, ensuring that the Q-value of the corresponding action can be retrieved in the Q-value table.

[0087] Preferably, state S t Represented by an 8-dimensional vector, denoted as... The following is an explanation of the meaning represented by each dimension in the 8-dimensional vector: Normalized Significant Motion Intensity measures the average intensity of motion of "real moving" objects in the current frame, excluding background noise interference. The calculation formula is as follows: ,in, ; Is The instantaneous salient motion intensity of a frame is calculated using the following formula: ; in, express The set of active macroblocks in a frame.

[0088] This represents the maximum possible amplitude of the motion vector, used for normalization calculations. In the H.264 standard, the search range is typically set to 64 or 128, preferably... The value is 64.

[0089] for The corresponding time decay factor, preferably, The value is 0.9.

[0090] like (Indicating no active macroblocks), then .

[0091] Motion Coverage Ratio indicates the proportion of the entire image where there is significant motion, reflecting the size or number of moving objects. The calculation formula is as follows: ,in, ; Is Instantaneous frame coverage The calculation formula is as follows: ; This represents the total number of macroblocks in the image (e.g., 8160 for 1080p).

[0092] express The corresponding time decay factor, preferably, .

[0093] The Motion Direction Consistency Index measures whether all moving objects in an image are facing the same direction. A value close to 1 indicates a high degree of directional consistency (such as vehicles traveling in the same direction), while a lower value indicates chaotic directional movement (such as a crowd in turmoil). The calculation formula is as follows: ,in, ; Is The instantaneous directional consistency of a frame is obtained by calculating the ratio of the magnitude of the average motion vector to the average of the magnitudes of all vectors. The calculation formula is as follows: ; in, express The corresponding time decay factor. Preferably, .

[0094] like ,but .

[0095] The temporal motion variation rate describes how quickly the intensity of motion changes, distinguishing between uniform motion and acceleration / deceleration. A high rate of change may indicate the arrival of a new object or a sudden change in the scene. The calculation formula is as follows: ; in, This represents the normalized instantaneous significant motion intensity. It should be a very small positive number to prevent the denominator from being zero. Preferably, .

[0096] The frame type feature (B) maps discrete frame types (I, P, B) to continuous values, reflecting the coding dependencies and information completeness of the current frame. I-frames have the most complete information, while B-frames have the least. The calculation formula is as follows: in, ; in, Is The frame type encoding value is defined as follows: ; express The corresponding time decay factor, preferably, .

[0097] This represents the normalized quantization parameter. The QP value is used to represent the compression quality of the video, indirectly indicating the texture complexity of the scene. A higher QP value usually means that the scene is more complex or that bandwidth needs to be saved. The calculation formula is as follows: ,in, ;

[0098] Indicates in The normalized QP value of the frame. The calculation formula is as follows: ; in, express Average QP value of the frame; These represent the lower and upper limits of the QP value range in the H.264 standard, respectively. Preferably, .

[0099] express The corresponding time decay factor, preferably, .

[0100] This represents the packet size variation rate, where the size of the compressed frame directly reflects the complexity of the content. The packet size variation rate can capture sudden changes in the amount of scene information, and its calculation formula is as follows: ; in, express The size of the compressed frame. It represents a very small positive number to prevent the denominator from being zero.

[0101] The Temporal Trend Stability Index measures the stability of recent exercise intensity. A value close to 1 indicates stable motion intensity (such as uniform motion or stillness), while a value close to 0 indicates drastic fluctuations in motion intensity. It is a complement to the rate of change of motion. The calculation formula is as follows: ; in, The table represents the sequence of instantaneous significant motion intensities in the most recent N frames. To calculate the standard deviation of the sequence, To calculate the mean of the sequence.

[0102] In step S342, if only the action with the largest current Q value is selected, the model may get stuck in a local optimum due to the initial Q value bias or the unexplored state-action pair; if overexploration is carried out, the learned optimal policy ε-Greedy policy cannot be stably used to balance the two through probability allocation, so as to ensure that the model can converge stably during training and discover better policies.

[0103] Specifically, a probability value p is first randomly generated from the uniform distribution of [0,1], and then the action selection mode is determined. The action selection mode includes the exploration mode (p≤ε) and the exploitation mode (p>ε).

[0104] In exploration mode, an action is randomly selected as A from the action space {0,1} (0 = skip detection, 1 = trigger detection). t Regardless of the current Q-value, the initial exploration rate ε is recommended to be 0.2, gradually decreasing with training iterations. In exploit mode, the state S is queried from the Q-value table. t The corresponding two rows of Q values ​​(Q(S) t ,0) and Q(S t ,1)), select the action with the larger Q value as A. t If the two Q values ​​are equal, action 0 is selected by default (prioritizing saving computing power).

[0105] If A t =1, invoke a high-performance AI detection model (such as YOLO, Faster R-CNN) to decode the current frame (decoding only upon triggering) and detect the target, and output the detection results; if A t =0, no decoding and detection operations are performed, and the process proceeds directly to the reward calculation stage.

[0106] In step S343, the immediate reward R t Is the environment an influence on action A? t A direct evaluation requires accurate quantification of the quality of the action's outcome to provide a basis for updating the Q-value; the new state S t+1 It reflects the environmental changes after the action is performed and serves as a bridge connecting the current Q value and future rewards. Together, they constitute the update input of the Q-Learning algorithm.

[0107] In calculating the immediate reward R t At that time, first according to action A t The execution results, combined with the ground truth (obtained through offline detection of all frames by a high-precision AI detector or manual annotation), determine the result type and allocate rewards according to preset rules, specifically including: If A t =1 and the detection result is consistent with the true value (target detected and the true value indicates the presence of a target, i.e., True Positive), then R t =+1.0 (Positive reward, encouraging correct triggering); If A t When R = 1 and the detection result contradicts the true value (no target detected but the true value indicates the target exists, i.e., False Negative, or target detected but the true value indicates the target does not exist, i.e., False Positive), then when False Positive, R...t =-0.1, when False Negative, R t =-0.5 (negative reward, penalty for false alarms and missed detections); If A t =0 and the truth value has no objective (True Negative, skip correctly), then R t =+0.1 (positive reward to encourage saving computing power); If A t =0 and the true value exists for the target (False Negative, missed detection), then R t =-0.5 (Negative reward, severe punishment for missed detection, ensuring monitoring security).

[0108] Then, the H.264 video frame data at decision time t+1 is obtained, the coded domain metadata is parsed, a multi-dimensional temporal state vector is constructed and discretized, and the new state S is obtained. t+1 The corresponding discrete state index is used to complete the observation of the new state.

[0109] In step S344, the Q-Learning algorithm updates the Q value using the temporal difference error (TD error) and adjusts the current instantaneous reward R. t The expected value of the optimal future reward in the next state (γ×max) a' Q (S t+1 The combination of ,a')) makes Q(S t A t By gradually approximating the true state-action value, the model can be iteratively optimized.

[0110] Specifically, first calculate the optimal Q-value for the next state, which can be done by looking up the Q-value table for state S. t+1 Take the maximum value (max) from the two corresponding Q values. a 'Q (S t+1 ,a') (a'∈{0,1}), representing the agent's pair in S t+1 The maximum long-term reward that can be obtained under the given conditions is estimated. Then, the TD error is calculated, and the formula for the TD error is as follows: TD error = R t +γ×max a' Q (S t+1 ,a')-Q(S t A t ), TD error reflects the gap between the current Q value and "immediate reward + future optimal reward".

[0111] Then, Q(S) is adjusted according to the Q-value update formula. t A tThe recommended value for the learning rate η is 0.1-0.3 (e.g., initial η=0.2, decaying with training), and the discount factor... The recommended value range is 0.9-0.95 (e.g., =0.92).

[0112] The above scheme associates immediate rewards with future rewards using the Q-Learning algorithm, enabling the decision-making model to learn from historical interaction experience, gradually optimizing the value estimation of "state-action pairs," and ultimately converging to the optimal triggering policy, balancing detection accuracy and computational efficiency. The ε-Greedy policy ensures that the model fully explores unknown state-action pairs in the early stages of training, avoiding getting trapped in local optima; in the later stages of training, exploration is gradually reduced, stably utilizing the learned optimal policy, balancing policy optimization potential and decision stability. Immediate reward R t Real-time feedback on environmental changes (such as a scene changing from static to dynamic) allows Q-value updates to respond quickly to these changes, enabling the model strategy to dynamically adjust with the environment without the need for manual retraining, thus improving the method's environmental adaptability.

[0113] In some embodiments, the method further includes: During the iterative optimization of the decision model, at least one of the following strategies is employed: learning rate decay strategy, exploration rate decay strategy, and model rollback strategy, in order to improve model convergence and stability.

[0114] In the early stages of training, the decision model's estimation of the value of "state-action pairs" is inaccurate, requiring a large learning rate η (e.g., 0.3) to quickly correct the Q-value and accelerate the learning process. In the later stages of training, the Q-value is close to the true value; maintaining a large learning rate at this stage can easily lead to Q-value oscillations due to random fluctuations in immediate rewards, preventing stable convergence. Learning rate decay can strike a balance between "rapid learning" and "stable convergence." Therefore, the learning rate decay strategy involves gradually decreasing the learning rate η as the number of training iterations increases.

[0115] Initial learning rate It can be set to 0.2-0.3 (e.g.) =0.2); the decay coefficient β can be set to 0.99 (decaying by 1% per iteration); minimum learning rate η min The optimal learning rate is 0.05 (to avoid training stagnation caused by an excessively small learning rate). After each Q-value update (i.e., one training iteration), the learning rate is updated using the following formula: η new =max(η min , η old ×β).

[0116] For example, initially =0.2, after the first iteration =max(0.05,0.2×0.99)=0.198, after the second iteration =max(0.05,0.198×0.99)=0.19602, and so on, until η drops to 0.05 and remains stable.

[0117] Periodically (e.g., every 1000 iterations), calculate the average update magnitude of the Q-value table (the mean of the absolute values ​​of all Q-value updates). If the average update magnitude is less than a threshold (e.g., 0.01) for 500 consecutive iterations, the model is considered close to convergence, and the learning rate can be fixed at η in advance. min This reduces computational overhead.

[0118] In the early stages of training, the decision model has not fully explored all state-action pairs, requiring a high exploration rate ε (e.g., 0.2) to try different actions and avoid missing the optimal strategy due to initial Q-value bias. In the later stages of training, the model has learned a better strategy, requiring a low exploration rate ε (e.g., 0.01) to reduce ineffective exploration, ensure stable decision results, and reduce the risk of false positives or false negatives caused by exploration. The exploration rate decay strategy includes gradually decreasing the exploration rate ε in the ε-Greedy strategy as the number of training iterations increases.

[0119] Specifically, the initial exploration rate can be... Set to 0.15-0.2 (e.g.) =0.2), the decay coefficient δ is set to 0.995 (decaying by 0.5% per iteration), and the minimum exploration rate ε min Set to 0.01 (to reserve a small amount of exploration to cope with environmental changes). After each action selection and Q-value update (one training iteration), update the exploration rate according to the following formula: ε new =max(ε min ,ε old ×δ); If the model's false negative rate suddenly increases during training (e.g., exceeding the preset threshold of 0.05), the exploration rate ε can be temporarily increased (e.g., restored to 0.05) to increase action diversity and help the model escape local optima. Once the false negative rate returns to the normal range (e.g., <0.03), ε can be further reduced using the decay strategy.

[0120] In monitoring scenarios, sudden anomalies may occur (such as blurred images due to heavy rain or temporary camera obstruction), causing the training data distribution to deviate from the normal range. If the model continues to learn on abnormal data, it will lead to Q-value table degradation and performance decline (such as a sharp increase in false positive rate). A model rollback strategy can be used to save historically optimal models and restore them in a timely manner when performance deteriorates, ensuring the long-term reliability of the model. The model rollback strategy includes: periodically evaluating and saving a copy of the best-performing Q-value table, and rolling back to the saved copy when the decision model's performance deteriorates.

[0121] Specifically, you can first set model performance evaluation indicators, including detection accuracy (TP / (TP+FP)), false negative rate (FN / (TP+FN)), false positive rate (FP / (FP+TN)), and computing power saving rate (TN / (TP+FP+TN+FN)). Preset qualified thresholds for each indicator (such as accuracy ≥ 0.95, false negative rate ≤ 0.03, false positive rate ≤ 0.02, and computing power saving rate ≥ 0.7).

[0122] After each evaluation period T, calculate the above performance metrics of the current model. If all metrics are better than the historical best model (or it is the first evaluation), save the current Q value table, learning rate η, and exploration rate ε as the "best model copy" to the specified path (such as a disk directory), and record the saving time and performance metrics for future reference.

[0123] If any performance metric of the model falls below the acceptable threshold for two consecutive periods within a certain evaluation period (e.g., the false negative rate is ≥0.05 for two consecutive periods), the model performance is deemed to have degraded. The most recently saved "optimal model copy" is automatically loaded, and the Q-value table, η, and ε are restored to their optimal state. At the same time, the current data is marked as anomalous data, and the update weight of anomalous data on the Q-value is reduced during subsequent training (e.g., multiplied by 0.5) to prevent anomalous data from affecting the model again.

[0124] In some embodiments, the decision model serves as the primary decision model, and the method further includes: A meta-decision module is constructed, which is used to evaluate the matching degree between the current environmental state and the training environment of the main decision model, and output the trust state of the main decision model. Step S3 specifically includes: The multidimensional temporal state vector is simultaneously input into the main decision model and the meta-decision module; Based on the trust status output by the meta-decision module, execute the branch operation: If the trust state is trust, then the trigger command output by the master decision model is adopted; If the trust status is distrust, then a conservative strategy is executed and model fine-tuning is initiated; The conservative strategy includes ignoring the output of the main decision model and forcibly generating a trigger command to execute the intelligent detection operation. The initial model fine-tuning includes: using empirical data consisting of the current state, action, immediate reward, and the state at the next moment, and updating the Q-value table of the master decision model in a progressive fine-tuning manner based on the empirical data. The update magnitude of the Q-value table by the progressive fine-tuning method is less than the update magnitude of the Q-value table when iteratively optimizing using the Q-Learning algorithm in step S34.

[0125] In this embodiment, the master decision-making model performs optimally in the training environment. However, the monitoring scene may change over time or space (e.g., daytime → nighttime, street → warehouse), causing a mismatch between the training environment and the actual environment, resulting in a decrease in the accuracy of the master model's decisions. The meta-decision module dynamically adjusts the master model's usage strategy by evaluating the scene matching degree, addressing the problem of insufficient model generalization ability and achieving online adaptation.

[0126] Specifically, the meta-decision module adopts a lightweight model architecture to avoid excessive computational overhead. It can use either an anomaly detection model or a reinforcement learning model. The input to the meta-decision module is a multi-dimensional temporal state vector identical to that of the main decision model, ensuring that both are evaluated based on the same environmental information and avoiding evaluation bias. The output of the meta-decision module is a binary trust state (0 = distrust, 1 = trust), with an output frequency consistent with the main model's decision frequency (e.g., once per frame), ensuring real-time response.

[0127] When training the meta-decision module, data on "normal scene states" (such as multi-frame state vectors of a street during the day) and "abnormal scene states" (such as state vectors of a warehouse at night) from the main model training environment are collected to construct a meta-model training set. The meta-decision module is then trained using this training set. After training, the decision thresholds of the meta-decision module (such as the anomaly score threshold for an anomaly detection model) are adjusted using a validation set to ensure that the accuracy of the "trust" state is ≥0.95 (the decision accuracy of the main model in the trust state is ≥0.95), and the recall rate of the "distrust" state is ≥0.9 (the proportion of unknown scenes judged as distrustful is ≥0.9), thus balancing "trust accuracy" and "anomaly recognition capability."

[0128] Then, based on the trust status of the meta-decision module, the usage mode of the main model is dynamically selected. That is, when the meta-decision module outputs a trust status, the main decision model is used normally to ensure computing power saving; when the meta-decision module outputs a distrust status, a conservative strategy is executed and the main model is fine-tuned, which not only ensures security but also gradually adapts to new scenarios, achieving the dual goals of security and adaptability.

[0129] In this embodiment, the termination condition for progressive fine-tuning is: continuous fine-tuning until the meta-decision module's trust state for the current scene changes to a trust state (e.g., outputting 1 for 5 consecutive frames), or the number of fine-tuning iterations reaches a preset upper limit (e.g., 1000 times, corresponding to 30 seconds of data for a new scene); after fine-tuning, the learning rate is restored to η. normal The master decision model then switches to normal update mode.

[0130] In a second aspect, the present invention also provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the reinforcement learning-based H.264 video intelligent detection triggering method as described in the first aspect of the present invention.

[0131] The computer-readable storage medium may be volatile memory or non-volatile memory, or may include both volatile and non-volatile memory.

[0132] The non-volatile memory may be a read-only memory (ROM), a programmable read-only memory (PROM), an erasable programmable read-only memory (EPROM), an electrically erasable programmable read-only memory (EEPROM), a magnetic random access memory (FRAM), a flash memory, a magnetic surface memory, an optical disc, or a compact disc read-only memory (CD ROM); the magnetic surface memory may be a disk storage device or a magnetic tape storage device.

[0133] The volatile memory may be random access memory (RAM), which serves as an external cache. By way of example, but not limitation, many forms of RAM are available, such as static random access memory (SRAM), synchronous static random access memory (SSRAM), dynamic random access memory (DRAM), synchronous dynamic random access memory (SDRAM), double data rate synchronous dynamic random access memory (DDRSDRAM), enhanced synchronous dynamic random access memory (ESDRAM), synclink dynamic random access memory (SLDRAM), and direct memory bus random access memory (DRRAM). The computer-readable storage media described in the embodiments of the present invention are intended to include these and any other suitable types of memory.

[0134] like Figure 6 As shown, in a third aspect, the present invention provides an electronic device 10, including a processor 101 and a storage medium 102, wherein a computer program is stored on the storage medium, and the computer program, when executed by the processor, implements the reinforcement learning-based H.264 video intelligent detection triggering method as described in the first aspect of the present invention.

[0135] In some embodiments, the processor may be implemented by software, hardware, firmware, or a combination thereof, and may use at least one of the following: circuit, single or multiple application-specific integrated circuits (ASICs), digital signal processors (DSPs), digital signal processing devices (DSPDs), programmable logic devices (PLDs), field-programmable gate arrays (FPGAs), central processing units (CPUs), controllers, microcontrollers, and microprocessors, thereby enabling the processor to execute some or all of the steps, or any combination thereof, of the reinforcement learning-based H.264 video intelligent detection triggering method described in the various embodiments of this application.

[0136] Finally, it should be noted that although the above embodiments have been described in the text and drawings of this application, this should not limit the scope of patent protection of this application. Any technical solutions that are based on the essential concept of this application and utilize the content described in the text and drawings of this application, resulting in equivalent structural or procedural substitutions or modifications, as well as the direct or indirect application of the technical solutions of the above embodiments to other related technical fields, are all included within the scope of patent protection of this application.

Claims

1. A method for intelligent detection triggering of H.264 video based on reinforcement learning, characterized in that, The method includes: S1: Real-time parsing of H.264 video stream, directly extracting its coding domain metadata, which includes motion vectors, macroblock type, quantization parameters, frame type and compressed packet size; S2: Based on the encoded domain metadata, construct a multi-dimensional temporal state vector, which includes a motion feature dimension vector, an encoded feature dimension vector, and a temporal feature dimension vector; S3: Input the multidimensional temporal state vector into a predefined decision model and output a trigger command; the decision model performs decision-making and optimization through the following steps: S31: Establish a Q-value table and initialize the Q-value table. The Q-value table is used to store the Q-value corresponding to each state-action pair. The state is represented by the multi-dimensional temporal state vector, and the action includes triggering the intelligent detection operation or skipping the intelligent detection operation. S32: For the multidimensional time-series state vector at the current moment, query the Q-value table, select the action with the largest Q-value according to the Q-value table, and use the action with the largest Q-value as the trigger instruction; S33: Execute the selected action and calculate the immediate reward based on the execution result; where, when the selected action triggers a smart detection operation and detects a target, a positive reward is given; when the selected action triggers a smart detection operation but does not detect a target, a negative reward is given; when the selected action skips a smart detection operation, a delayed reward is given based on the detection result of subsequent frames or a preset rule. S34: Based on the immediate reward and the multidimensional temporal state vector of the next moment, the Q-Learning algorithm is used to update the Q value in the Q value table corresponding to the current state-action pair, thereby iteratively optimizing the decision model and realizing an adaptive triggering strategy.

2. The H.264 video intelligent detection triggering method based on reinforcement learning as described in claim 1, characterized in that, The motion feature dimension vector is constructed based on the statistical features of the magnitude and direction of the motion vector, specifically including: S21: Calculate the motion intensity of each macroblock based on the motion vectors extracted from the H.264 video stream; S22: Set a dynamic threshold and determine macroblocks whose motion intensity exceeds the dynamic threshold as active macroblocks; S23: Based solely on the motion vector of the active macroblock, calculate the amplitude and orientation statistical features of the entire frame image to construct the motion feature dimension vector.

3. The H.264 video intelligent detection triggering method based on reinforcement learning as described in claim 1, characterized in that, The encoded feature dimension vector is constructed based on the statistical features of the macroblock type and quantization parameters, specifically including: S24: Calculate the proportion of different types of macroblocks in a frame of an image to the total number of macroblocks, as a statistical feature of macroblock types; S25: Calculate the mean and variance of the quantization parameters of all macroblocks in the frame image as statistical characteristics of the quantization parameters; S26: Based on the statistical characteristics of the macroblock type and the statistical characteristics of the quantization parameters, the coding feature dimension vector is calculated.

4. The H.264 video intelligent detection triggering method based on reinforcement learning as described in claim 1, characterized in that, The temporal feature dimension vector is constructed based on the changing trend of the compressed package size and / or frame type of multiple consecutive video frames, specifically including: S27: Using a sliding window of size N, calculate the exponentially weighted moving average of the compressed packet size for N consecutive frames within the sliding window, as the trend of the compressed packet size change; S28: Statistically analyze the frequency of I-frames, P-frames, and B-frames within the sliding window to show the changing trend of frame types; S29: Construct the temporal feature dimension vector based on the changing trend of the compressed package size and / or the changing trend of the frame type.

5. The H.264 video intelligent detection triggering method based on reinforcement learning as described in claim 1, characterized in that, Based on the aforementioned encoded domain metadata, a multidimensional temporal state vector is constructed, specifically including: Set a time series observation window of size M to cache the coding domain metadata and intermediate feature values ​​of the current time and the previous M time steps. The intermediate feature values ​​refer to the feature values ​​calculated based on the coding domain metadata and used to construct the coding feature dimension vector and the motion feature dimension vector. For each type of data cached within the time series observation window, an exponentially weighted moving average algorithm is used for time series fusion to calculate the final value of the corresponding dimension in the multidimensional time series state vector. The exponentially weighted moving average algorithm controls the weight of historical data through a decay factor between 0 and 1, so that data closer to the current time is assigned a higher weight.

6. The H.264 video intelligent detection triggering method based on reinforcement learning as described in claim 1, characterized in that, Step S34 specifically includes: S341: At decision time t, the state S composed of the multidimensional temporal state vector is observed. t ; S342: Based on state S t Action A is selected and executed from the Q-value table according to the ε-Greedy policy. t Action A t This includes triggering or skipping intelligent detection operations; S343: Instant reward for receiving environmental feedback R t And observe the new state S at the next decision moment. t+1 ; S344: Update the state-action pair (S) in the Q-value table according to the following Q-value update formula. t A t The corresponding Q value: Q(S) t A t )←Q(S t A t )+η×[R t +γ×max a' Q(S t+1 ,a')- Q(S t A t )]; Among them, Q(S) t A t ) indicates that in state S t Take action A t The original value estimate, where η is the learning rate. For discount factor, max a' Q(S t+1 ,a') indicates that in the next state S t+1 Below, for all possible actions a', the maximum Q value is taken, Q(S t+1 , a') indicates that in state S t+1 The value estimate of taking a certain action a'.

7. The H.264 video intelligent detection triggering method based on reinforcement learning as described in claim 6, characterized in that, The method further includes: During the iterative optimization of the decision model, at least one of the following strategies is employed: learning rate decay strategy, exploration rate decay strategy, and model rollback strategy, in order to improve model convergence and stability. The learning rate decay strategy includes: gradually decreasing the learning rate η as the number of training iterations increases; The exploration rate decay strategy includes: gradually reducing the exploration rate ε in the ε-Greedy strategy as the number of training iterations increases; The model rollback strategy includes: periodically evaluating and saving a copy of the Q-value table with the best performance, and rolling back to the saved copy when the performance of the decision model deteriorates.

8. The H.264 video intelligent detection triggering method based on reinforcement learning as described in claim 1, characterized in that, The decision model serves as the primary decision model, and the method further includes: A meta-decision module is constructed, which is used to evaluate the matching degree between the current environmental state and the training environment of the main decision model, and output the trust state of the main decision model. Step S3 specifically includes: The multidimensional temporal state vector is simultaneously input into the main decision model and the meta-decision module; Based on the trust status output by the meta-decision module, execute the branch operation: If the trust state is trust, then the trigger command output by the master decision model is adopted; If the trust status is distrust, then a conservative strategy is executed and model fine-tuning is initiated; The conservative strategy includes ignoring the output of the main decision model and forcibly generating a trigger command to execute the intelligent detection operation. The initial model fine-tuning includes: using empirical data consisting of the current state, action, immediate reward, and the state at the next moment, and updating the Q-value table of the master decision model in a progressive fine-tuning manner based on the empirical data. The update magnitude of the Q-value table by the progressive fine-tuning method is less than the update magnitude of the Q-value table when iteratively optimizing using the Q-Learning algorithm in step S34.

9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements the reinforcement learning-based H.264 video intelligent detection triggering method as described in any one of claims 1 to 8.

10. An electronic device having a computer program stored thereon, characterized in that, The device includes a processor and a storage medium, wherein a computer program is stored on the storage medium, and when executed by the processor, the computer program implements the reinforcement learning-based H.264 video intelligent detection triggering method as described in any one of claims 1 to 8.

Citation Information

Patent Citations

  • Progressive compressed domain computer vision and deep learning systems

    CN111670580A

  • Motion perception video recording method and device based on monitoring video inter-frame decoding

    CN119814970A