A method and system for detecting a crowd gathering
By preprocessing video frames, performing multi-target tracking, and using two-layer spatial clustering analysis, the problems of high manpower costs and inconsistent judgment results in traditional crowd monitoring are solved, achieving high-precision, low-false-alarm real-time crowd gathering detection.
Patent Information
- Application Number
- CN202611206707.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-10
- Publication Date
- 2026-11-20
AI Technical Summary
Traditional crowd monitoring suffers from high labor costs, limited monitoring coverage, delayed response to abnormal events, and insufficient consistency in judgment results, making it difficult to meet the needs of all-weather, full-coverage, and high-precision security and prevention.
A crowd gathering detection method is adopted. By acquiring video frames and preprocessing them, people are detected and located. Combined with multi-target tracking and two-layer spatial clustering analysis, crowd density is calculated, and multi-condition joint judgment and temporal consistency verification are performed to output an alarm.
It improves the accuracy and reliability of crowd gathering detection, reduces false alarm and false negative rates, ensures the authenticity and timeliness of alarm signals, and adapts to the monitoring needs of complex and dynamic scenarios.
Smart Images

Figure CN123142147A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the technical field of public safety monitoring, and in particular to a method and system for detecting crowd gatherings. Background Technology
[0002] In the field of public safety monitoring, real-time monitoring and risk warning of crowd gatherings are key to preventing safety accidents in public places. In densely populated places such as stations, shopping malls, squares, and sports venues, abnormal crowd gatherings are often accompanied by multiple public safety risks, including mass incidents, illegal gatherings, and the display of unauthorized promotional materials. At the same time, excessive crowd gatherings can easily lead to stampedes, placing high demands on the timeliness of security forces and emergency response.
[0003] Traditional crowd monitoring mainly adopts a manual duty mode, which requires a large number of security personnel to continuously monitor multiple surveillance videos. This not only results in high labor costs and limited monitoring coverage, but also has drawbacks such as delayed response to abnormal events and the risk of missing the best time to deal with them. Furthermore, the standards for manually judging the risk of gathering are greatly affected by the condition and subjective experience of the duty personnel, resulting in insufficient consistency in the judgment results. This is no longer able to meet the current needs of public places for all-weather, full-coverage, and high-precision security and prevention. Summary of the Invention
[0004] To achieve high-precision detection of crowd gatherings with a low false alarm rate, this application provides a crowd gathering detection method and system.
[0005] Firstly, this application provides a method for detecting crowd gatherings, employing the following technical solution:
[0006] 1. A method for detecting crowd gatherings, comprising:
[0007] The system acquires and preprocesses input video frames, performs personnel detection and localization on the preprocessed video frames, and obtains personnel bounding boxes and their corresponding spatial positions.
[0008] Multi-target tracking is performed based on the personnel bounding box, and the detection and tracking results are fused to calculate the current actual number of people;
[0009] A two-layer spatial clustering analysis is performed on the personnel based on their spatial location. The two-layer spatial clustering analysis includes a first-layer clustering based on distance to obtain the largest cluster and the number of people, and a second-layer clustering based on dense cores to obtain the largest dense core cluster and the number of people.
[0010] Calculate the crowd density based on the largest cluster and the number of people in it;
[0011] Based on the current actual number of people, the largest cluster and number of people, the largest dense core cluster and number of people, and the crowd density, a multi-condition joint determination including the number of people, clustering conditions, dense core conditions, and density conditions is performed to obtain the current frame clustering determination result.
[0012] Based on the current frame aggregation determination result, a timing consistency verification is performed, and an alarm is output when the verification passes.
[0013] By adopting the above technical solution, this method integrates personnel detection with multi-target tracking technology. It calculates the actual number of people by complementing the detection and tracking results, effectively overcoming the shortcomings of single-frame detection, which is susceptible to occlusion, target overlap, and dynamic blurring, leading to missed detections and false detections. This improves the accuracy of people counting in complex dynamic scenes. Furthermore, a two-layer spatial clustering analysis mechanism is employed. The first layer, based on distance dimension clustering, can quickly identify large-scale clusters and grasp the overall cluster size and spatial distribution. The second layer, based on dense cores, further delves into locally highly dense areas within the clusters. This hierarchical design of the two-layer clustering not only ensures overall control of the global clustering situation but also achieves precise positioning of locally high-risk dense areas. This overcomes the shortcomings of traditional single-layer clustering algorithms, which cannot simultaneously adapt to both large-scale and locally high-density clustering scenarios, and can more comprehensively and meticulously depict the spatial morphological characteristics of crowd gatherings. Meanwhile, abandoning the traditional single-threshold judgment logic, a multi-condition joint judgment system was constructed, encompassing the conditions of the number of people, clustering, dense core, and density. This system integrates four characteristic indicators—total global population, overall cluster size, core dense area size, and population density—for comprehensive evaluation. This effectively distinguishes between dispersed and concentrated population scenarios, avoiding false alarms caused by a total number of people meeting the threshold but the actual population being dispersed. Furthermore, it captures high-risk states of extreme local congestion through the dense core dimension, preventing missed detections where the overall density is within limits but local clustering risks exist, thus enhancing the rationality and accuracy of cluster judgment. Finally, a temporal consistency verification mechanism is introduced based on the single-frame judgment results. By verifying the judgment results of consecutive frames, it filters out single-frame misjudgments caused by instantaneous detection jitter, brief pedestrian stops, and occasional detection errors, ensuring that the final output alarm signal corresponds to a real and continuous crowd gathering event. This suppresses false alarms and reduces the interference of invalid alarms on security operations and maintenance.
[0014] 2. Optionally, the steps of performing personnel detection and localization on the preprocessed video frames to obtain personnel bounding boxes and their corresponding spatial positions specifically include:
[0015] Perform target detection on the preprocessed video frames to obtain the initial personnel bounding boxes and their corresponding confidence scores;
[0016] Set a confidence threshold, filter and retain the initial personnel bounding boxes with a confidence level not less than the confidence threshold, and use them as the filtered personnel bounding boxes;
[0017] The center point of the person is calculated based on the upper left and lower right corner coordinates of the filtered person bounding box, and is used as the spatial position of the person bounding box;
[0018] Configure the coordinates of the polygon vertices to define the region of interest. Use the ray method to determine whether the center point of the person is within the region of interest. Only retain the bounding box of the person and the corresponding spatial position of the person located within the region of interest. The ray method involves emitting a horizontal ray to the right from the center point of the person and counting the number of intersections between the ray and the polygon boundary. If the number of intersections is odd, the person is determined to be within the region of interest; if it is even, the person is determined to be outside the region of interest.
[0019] By adopting the above technical solutions, the personnel detection and positioning process forms a complete data verification link of "detection output - confidence screening - spatial location standardization - control area filtering", which controls the accuracy and effectiveness of personnel targets from the data source, and takes into account detection accuracy, computational efficiency and scenario flexibility.
[0020] 3. Optionally, the step of performing multi-target tracking based on the personnel bounding box and fusing the detection and tracking results to calculate the current actual number of people specifically includes:
[0021] Assign a unique tracking identifier to the detected personnel, match the detection results of the current frame with historical trajectories, update the status of successfully matched trajectories, and handle the creation and deletion of trajectories;
[0022] After processing the creation and deletion of tracks, the total number of tracks that are not yet expired is counted as the current number of active tracks;
[0023] Obtain the number of people detected in the current frame, and take the maximum value between the number of people detected in the current frame and the number of active trajectories as the current actual number of people.
[0024] By adopting the above technical solution, the people counting process takes into account both the temporal stability of the statistical results and the accuracy of single frames. It can output stable and reliable people counting results in monitoring scenarios with dense crowds and complex personnel movement, while also adapting to the low latency processing requirements of real-time security monitoring.
[0025] 4. Optionally, the step of performing a two-layer spatial clustering analysis on personnel based on their spatial location specifically includes:
[0026] Extract the spatial locations of all personnel, construct adjacency relationships based on the maximum clustering distance threshold, identify all connected components through breadth-first search, and obtain the largest cluster containing the most personnel and the number of people.
[0027] For each person, count the number of nearest neighbors, and filter out dense core points by combining the dense nearest neighbor distance threshold and the minimum nearest neighbor number threshold.
[0028] Perform connectivity analysis between the dense core points to obtain the largest dense core cluster containing the most people and the number of people in it.
[0029] By adopting the above technical solution, the two-layer clustering forms a progressive feature system of "overall cluster size - core density". The two complement and corroborate each other, which can not only fully grasp the global clustering situation in the scene, but also accurately identify local high-density risk points. This makes the spatial characteristics of crowd gathering more comprehensive and detailed, avoiding the problems of "misjudging large-scale loose clusters as high risk" or "missing local dense clusters" that are prone to occur under a single clustering index. At the same time, the entire clustering process adopts efficient calculation logic based on connected components and adjacency relationships. The algorithm has low complexity and stable operation, and can continuously and efficiently output reliable clustering results in real-time monitoring scenarios with dense crowds, ensuring the real-time performance and detection accuracy of the entire crowd gathering detection method.
[0030] 5. Optionally, the step of calculating the crowd density based on the largest cluster and the number of people specifically includes:
[0031] Calculate the bounding rectangle of the largest cluster, and obtain the minimum x-coordinate, maximum x-coordinate, minimum y-coordinate, and maximum y-coordinate of the bounding rectangle;
[0032] Calculate the area of the circumscribed rectangle based on the extreme coordinates of the circumscribed rectangular region;
[0033] The population density is calculated based on the largest cluster and the number of people in it, and the area of the circumscribed rectangle.
[0034] By adopting the above technical solution, the degree of crowding was accurately quantified with a low algorithm implementation cost. This not only forms a smooth logical connection with the two-layer spatial clustering results mentioned above, but also adds a core density dimension evaluation index to the subsequent multi-condition joint judgment system, thereby improving the accuracy of the entire crowd gathering detection method in identifying risks of different forms of gathering and its adaptability to complex scenarios.
[0035] 6. Optionally, the step of performing a multi-condition joint determination including population condition, clustering condition, dense core condition, and density condition based on the current actual number of people, the largest cluster and its population, the largest dense core cluster and its population, and the population density, to obtain the current frame clustering determination result specifically includes:
[0036] The current actual number of people is compared with the global minimum number of people threshold to obtain the number of people conditions;
[0037] The clustering conditions are obtained by comparing the largest cluster and the number of people in it with the cluster size threshold.
[0038] The dense core cluster and its number of people are compared with the minimum number of people threshold for the dense core cluster to obtain the dense core condition;
[0039] The density condition is obtained by comparing the population density with the minimum density threshold.
[0040] Perform a logical AND operation on the number of people condition, the clustering condition, the dense core condition, and the density condition to obtain the clustering determination result of the current frame.
[0041] By adopting the above technical solutions, the multi-condition joint judgment mechanism has comprehensive dimensions and rigorous logical constraints. It takes into account both the global total characteristics and spatial distribution characteristics of gathering events, and deepens the consideration of local core density and quantitative density indicators. It can highly match the judgment standards for crowd gathering risks in public safety and security scenarios, ensuring a high detection rate of real high-risk gathering events while reducing the probability of false alarms, and improving the reliability of gathering judgment results.
[0042] 7. Optionally, the step of performing timing consistency verification based on the current frame aggregation determination result and outputting an alarm when the verification passes specifically includes:
[0043] A confirmation counter is maintained for each camera. When the current frame aggregation determination result is true, the count value of the confirmation counter is incremented by one; otherwise, it is reset to zero.
[0044] The count value of the confirmation counter is compared with the minimum confirmation frame threshold. When the count value is not less than the minimum confirmation frame threshold, the verification is deemed successful and an alarm is triggered.
[0045] After an alarm is triggered, a cooling timer is started to suppress similar alarms within a cooling time threshold, and normal detection is resumed after the cooling time threshold is reached.
[0046] By adopting the above technical solutions, the time-series verification and alarm control process achieves noise filtering of single-frame judgment results and frequency control of alarm output from the time dimension with low algorithm implementation cost. It complements the front-end personnel detection, two-layer clustering, and multi-condition judgment, enabling the entire crowd gathering detection method to accurately identify real and continuous gathering risks and output standardized and controllable alarm signals in complex and ever-changing real monitoring scenarios.
[0047] 8. Optionally, before constructing adjacency relationships based on the maximum clustering distance threshold, the following also applies:
[0048] Extract the vertical coordinate of the spatial position, and calculate the perspective distortion compensation coefficient based on the vertical coordinate, wherein the vertical coordinate represents the depth position of the person in the picture;
[0049] The preset baseline clustering distance threshold and baseline dense nearest neighbor distance threshold are dynamically corrected based on the perspective distortion compensation coefficient to obtain the maximum clustering distance threshold and the dense nearest neighbor distance threshold.
[0050] Wherein, the smaller the vertical coordinate of the spatial location, the farther away from the camera, and the perspective distortion compensation coefficient makes the corrected maximum clustering distance threshold and the dense nearest neighbor distance threshold decrease synchronously as the vertical coordinate decreases, so as to compensate for the visual distance compression effect of distant people.
[0051] By adopting the above technical solution, the perspective distortion compensation mechanism corrects the perspective deviation of monocular monitoring at a relatively low implementation cost. This fundamentally optimizes the judgment criteria for spatial clustering, making the spatial morphology analysis results of crowd gatherings closer to the actual physical scene's clustering state. It reduces clustering misjudgments and missed judgments caused by perspective distortion, further improving the detection stability and reliability of the entire crowd gathering detection method in large depth-of-field and wide-angle monitoring scenarios.
[0052] 9. Optionally, before maintaining a confirmation counter for each camera, the following is also included:
[0053] When the current frame aggregation determination result is true, the tracking trajectory of all personnel in the largest aggregation cluster is obtained, and the overall velocity variance and orientation dispersion of the largest aggregation cluster are calculated based on the tracking trajectory.
[0054] When the overall velocity variance is greater than the velocity variance threshold and the directional dispersion is greater than the directional dispersion threshold, it is determined to be a dynamic high-risk cluster, and the preset baseline confirmation frame number threshold is dynamically reduced as the minimum confirmation frame number threshold.
[0055] When the conditions for dynamic high-risk clustering are not met, it is determined to be a regular clustering, and the baseline confirmation frame number threshold is used as the minimum confirmation frame number threshold.
[0056] The overall velocity variance and directional dispersion characterize the degree of pushing and disorderly movement within the crowd. The minimum confirmation frame threshold corresponding to the dynamic high-risk cluster is less than the minimum confirmation frame threshold corresponding to the regular cluster, so as to achieve accelerated response under high-risk conditions.
[0057] By adopting the above technical solutions, the risk-adaptive time-series verification mechanism deeply binds the characteristics of crowd movement behavior with the alarm output logic, giving the time-series verification process the ability to classify and judge risks, making the entire crowd gathering detection early warning system more flexible and targeted. It can maintain a stable and reliable false alarm suppression effect for regular gathering scenarios, and can also achieve a rapid and sensitive early warning response for high-risk disorderly gatherings.
[0058] Secondly, this application provides a crowd gathering detection system, which adopts the following technical solution:
[0059] A crowd gathering detection system includes:
[0060] The personnel detection and localization module is used to acquire input video frames and preprocess them, then perform personnel detection and localization on the preprocessed video frames to obtain personnel bounding boxes and their corresponding spatial positions.
[0061] The multi-target tracking and fusion module is used to perform multi-target tracking based on the personnel bounding box, and to fuse the detection and tracking results to calculate the current actual number of people.
[0062] A two-layer spatial clustering analysis module is used to perform two-layer spatial clustering analysis on personnel based on the spatial location. The two-layer spatial clustering analysis includes a first-layer clustering based on distance to obtain the largest cluster and the number of people, and a second-layer clustering based on dense cores to obtain the largest dense core cluster and the number of people.
[0063] The density calculation module is used to calculate the crowd density based on the largest cluster and the number of people; the joint determination module is used to perform a multi-condition joint determination based on the current actual number of people, the largest cluster and the number of people, the largest dense core cluster and the number of people, and the crowd density, including the number of people condition, clustering condition, dense core condition and density condition, to obtain the current frame cluster determination result.
[0064] The timing verification and alarm module is used to perform timing consistency verification based on the current frame aggregation determination result, and output an alarm when the verification is successful.
[0065] In summary, this application includes at least one of the following beneficial technical effects:
[0066] 1. Stable crowd counting and objective spatial analysis closely reflect real physical scenarios. A fusion counting mechanism that takes the maximum value from detection and tracking results compensates for the shortcomings of single-frame detection in scenarios with occlusion, target overlap, and dynamic blur, ensuring the accuracy and continuity of crowd counting in complex crowd environments. A dynamic perspective distortion compensation mechanism based on the vertical coordinate of the image is introduced to adaptively correct the clustering distance threshold, offsetting the perspective compression effect of monocular monitoring images. This ensures that the judgment scale of two-layer spatial clustering is consistent with the real physical distance, improving the objectivity, fairness, and scene adaptability of spatial clustering analysis.
[0067] 2. Comprehensive risk assessment dimensions and improved identification accuracy. A two-layer spatial clustering system of "global clusters - local dense core clusters" is constructed, combined with the bounding rectangle method to quantify population density, forming four feature dimensions: total number of people, cluster size, core density, and regional density. Through logic and operations, multi-condition joint judgment is achieved, which can distinguish between different scenarios of dispersed and concentrated populations, and can also capture local high-density and high-risk areas, avoiding the one-sidedness of single threshold judgment and reducing the probability of false alarms and missed detections.
[0068] 3. The alarm output is standardized and controllable, balancing false alarm suppression and high-risk response efficiency. A frame-by-frame acknowledgment counter is used to verify timing consistency, filtering out single-frame misjudgments caused by momentary detection jitter or brief pedestrian pauses. An alarm cooling mechanism suppresses repeated alarms for the same clustering event, reducing interference from invalid alarms at the maintenance end. Simultaneously, dynamic high-risk clusters are identified based on crowd velocity variance and directional dispersion, and the acknowledgment frame threshold is dynamically lowered to accelerate early warning in high-risk scenarios. While ensuring alarm accuracy, this improves the response speed to high-risk clustering events such as disorderly surges, achieving a two-way optimization of alarm reliability and early warning timeliness. Attached Figure Description
[0069] Figure 1 This is a first flowchart of an embodiment of the method of this application;
[0070] Figure 2 This is a second flowchart of an embodiment of the method of this application;
[0071] Figure 3 This is a third flowchart of an embodiment of the method of this application;
[0072] Figure 4 This is the fourth flowchart of an embodiment of the method of this application. Detailed Implementation
[0073] To make the purpose, technical solution, and advantages of this application clearer, the following description is provided in conjunction with the appendix. Figures 1-4 The present application will be further described in detail below with reference to embodiments. It should be understood that the specific embodiments described herein are for illustrative purposes only and are not intended to limit the scope of the application.
[0074] The first embodiment of this application discloses a method for detecting crowd gatherings. (Refer to...) Figure 1 The methods for detecting population gatherings include S110-S160:
[0075] S110: Acquire input video frames and perform preprocessing; perform personnel detection and localization on the preprocessed video frames; and obtain personnel bounding boxes and corresponding spatial positions.
[0076] S120 performs multi-target tracking based on personnel bounding boxes and calculates the current actual number of people by fusing detection and tracking results;
[0077] S130, perform two-level spatial clustering analysis on personnel based on spatial location. The two-level spatial clustering analysis includes a first-level clustering based on distance to obtain the largest cluster and number of people, and a second-level clustering based on dense core to obtain the largest dense core cluster and number of people.
[0078] S140, calculate the population density based on the largest cluster and the number of people;
[0079] S150: Based on the current actual number of people, the largest cluster and number of people, the largest dense core cluster and number of people, and the crowd density, perform a multi-condition joint judgment including the number of people, clustering conditions, dense core conditions, and density conditions to obtain the current frame clustering judgment result.
[0080] S160: Perform timing consistency verification based on the current frame aggregation determination result, and output an alarm when the verification is successful.
[0081] Specifically, for step S110, the system acquires raw video frames frame by frame from the monitoring video stream. The raw frames are usually standard RGB color images. Since the resolution and aspect ratio of different front-end devices vary, image preprocessing is performed first. Specifically, the raw frames are scaled uniformly to the fixed input size required by the target detection network. At the same time, pixel value normalization and color space calibration are performed to map the pixel values to the numerical range that the model is adapted to, thereby eliminating the interference of input format differences on the inference results.
[0082] Reference Figure 2 In S110, the steps of detecting and locating people in the preprocessed video frames and obtaining the bounding boxes of people and their corresponding spatial positions specifically include S210-S240:
[0083] S210, Perform target detection on the preprocessed video frames to obtain the initial personnel bounding boxes and corresponding confidence scores;
[0084] S220, Set a confidence threshold, filter and retain the initial personnel bounding boxes with a confidence level not less than the confidence threshold, and use them as the filtered personnel bounding boxes;
[0085] S230, calculate the center point of the person based on the coordinates of the upper left and lower right corners of the filtered person bounding box, and use it as the spatial position of the person bounding box;
[0086] S240: Configure the coordinates of the polygon vertices to define the region of interest. Use the ray casting method to determine whether the center point of a person is within the region of interest. Only retain the bounding box and spatial position of the person located within the region of interest. The ray casting method involves emitting a horizontal ray to the right from the center point of the person and counting the number of intersections between the ray and the polygon boundary. If the number of intersections is odd, the person is determined to be within the region of interest; if it is even, the person is determined to be outside the region of interest.
[0087] Specifically, after preprocessing, the standardized image is input into a pre-trained deep learning object detection model. The model extracts multi-scale depth features of the image through a multi-layer convolutional neural network, and outputs the initial bounding boxes and corresponding confidence scores of all candidate personnel targets in the image through the detection head inference. Then, non-maximum suppression is used to remove duplicate and redundant detection boxes, ensuring that each personnel target corresponds to only one optimal detection result. Each initial personnel bounding box is represented in the form of the upper left and lower right pixel coordinates, uniformly denoted as bounding box B = (x1, y1, x2, y2), where (x1, y1) are the horizontal and vertical coordinates of the upper left corner of the bounding box, and (x2, y2) are the horizontal and vertical coordinates of the lower right corner of the bounding box. The confidence score is a real number between 0 and 1, representing the degree of credibility of the model in determining that the candidate region is a real person. The higher the value, the stronger the reliability of the detection result.
[0088] Next, a confidence filtering operation is performed. The system presets a confidence threshold θconf as the filtering benchmark. The default value of this threshold is 0.5. It can be flexibly adjusted according to the false detection tolerance of the scenario. In high-security scenarios, it can be appropriately increased to reduce false detections, while in open and high-traffic scenarios, it can be appropriately decreased to reduce missed detections.
[0089] The filtering process iterates through all initial person bounding boxes, comparing their confidence scores with a threshold value one by one. Only detection results with a confidence score not less than the threshold are retained as filtered person bounding boxes. Low-confidence candidate boxes are judged as background false detections and directly removed. The corresponding filtering rule can be expressed as Dfiltered={d∈D|d.confidence≥θconf}, where D is the set of all initial detection results, d is a single detection result in the set, d.confidence is the confidence score of a single detection result, and Dfiltered is the set of valid detection results after filtering. This filtering step can eliminate a large number of low-quality false detection results in advance, reducing the computational cost of subsequent steps and minimizing the interference of false detections on the aggregation determination.
[0090] After confidence filtering, the system calculates the center point of each person based on the filtered bounding boxes, using this as the spatial location benchmark. For each bounding box, the average of the horizontal and vertical coordinates is calculated to obtain the center point coordinates. The horizontal coordinate of the center point is the average of the left and right horizontal coordinates of the bounding box, and the vertical coordinate is the average of the top and bottom vertical coordinates of the bounding box. The corresponding calculation formula is C=(cx,cy)=((x1+x2) / 2,(y1+y2) / 2), where cx is the horizontal coordinate of the center point and cy is the vertical coordinate of the center point. All subsequent spatial distance calculations, region determinations, and cluster analyses are based on the center point coordinates. Compared to the complete bounding box, the center point can more stably represent the spatial location of a person, unaffected by fluctuations in the bounding box size, and also simplifies the complexity of distance calculations.
[0091] To eliminate the impact of different camera resolutions on distance determination, the system will normalize the pixel coordinates to the [0,1] range, that is, the horizontal coordinate is divided by the total width of the screen and the vertical coordinate is divided by the total height of the screen. The normalized coordinates are independent of the screen hardware parameters, which can ensure the consistency of the determination standard under different devices. All subsequent distance and area calculations are performed based on the normalized coordinates, and the units are unified to the normalized units.
[0092] Next, the system performs region of interest filtering. Users can define regions of interest by configuring the normalized coordinates of polygon vertices. The number of polygon vertices must be no less than 3, which can flexibly adapt to various control ranges such as narrow passages, irregular squares, and local key areas.
[0093] For each person's center point, the system uses a ray-mapping method to determine whether it falls within the area of interest. The specific logic is as follows: Starting from the center point of the person to be determined, a horizontal ray is emitted to the right along the direction of increasing x-coordinate. The intersection of this ray with each edge of the polygon is calculated sequentially. The total number of intersections between the ray and the polygon boundary is counted. If the total number of intersections is odd, the center point is determined to be within the area of interest; if it is even, it is determined to be outside the area of interest. For cases where the ray passes exactly through the boundary of a polygon vertex, the system uses a rule that excluding points on the same side of the vertex, only counting intersections when the endpoints of the vertex are located above or below the ray, respectively, to avoid double counting or omissions. Ultimately, the system only retains the bounding box and spatial position of people within the area of interest, directly excluding people outside the area, thus eliminating interference from irrelevant personnel in non-controlled areas of the image.
[0094] Reference Figure 3 S120, the steps of performing multi-target tracking based on the personnel bounding box and calculating the current actual number of people by fusing the detection and tracking results specifically include S310-S330:
[0095] S310 assigns a unique tracking identifier to the detected personnel, matches the detection results of the current frame with historical trajectories, updates the status of successfully matched trajectories, and handles the creation and deletion of trajectories.
[0096] S320, after processing the creation and deletion of tracks, counts the total number of tracks that are not yet expired, and uses this as the number of currently active tracks;
[0097] S330: Obtain the number of people detected in the current frame, and take the maximum value between the number of people detected in the current frame and the number of active trajectories as the current actual number of people.
[0098] Specifically, for step S120, after spatial filtering, the system enters the multi-target tracking processing stage. The system employs a detection-driven multi-target tracking paradigm, maintaining continuous motion trajectories for each consistently appearing person. To predict the next frame position of the trajectory, the system introduces a Kalman filter algorithm to predict the expected position of each trajectory in the current frame based on historical trajectory states. Then, combining positional similarity and motion trends, the Hungarian algorithm is used to optimally match the detection results of the current frame with historical trajectories, ensuring that the same person corresponds to the same tracking identifier in consecutive frames and avoiding identity jumps.
[0099] Successfully matched trajectories will update their motion status using the detection results of the current frame, including the latest position, real-time speed, and historical trajectory sequence, while also refreshing the trajectory's last update timestamp. The system presets a trajectory expiration threshold (e.g., no detection result matched for 5 consecutive frames). For trajectories that fail to match a detection result beyond this threshold, the system determines that the corresponding person has left the monitoring screen or has been obscured for an extended period, marks them as expired, and removes them from the active trajectory set, thus completing the full lifecycle management of trajectory creation, updating, and deletion.
[0100] After trajectory management is completed, the system counts the total number of all non-expired trajectories as the current active trajectory count Ntracking. Since the tracking mechanism has short-term occlusion completion capabilities, the active trajectory count can compensate for missed detections in a single frame, more accurately reflecting the actual number of people in the scene. Subsequently, the system performs an actual number fusion calculation, obtaining the number of detected people Ndetection after region filtering in the current frame and the current active trajectory count Ntracking, taking the maximum of the two as the current actual number Nactual. The corresponding calculation formula is Nactual = max(Ndetection, Ntracking). In other implementations, a weighted average equal probability fusion strategy can be used instead of the maximum value strategy. Using the maximum value fusion strategy is a compromise that prioritizes preventing missed detections: when short-term missed detections occur, the active trajectory count is usually higher, and taking the maximum value can compensate for the underestimation of the number of people caused by missed detections; simultaneously, the system introduces trajectory lifecycle management in the tracking stage (e.g., expiring and deleting if there are N consecutive frames without matching), which can promptly remove redundant expired trajectories caused by identity splitting, thereby suppressing the trajectory count inflation caused by identity splitting to a certain extent. While prioritizing ensuring no underreporting, and combining this with a short expiration mechanism, taking the maximum value can approximate the actual number of people as closely as possible.
[0101] Furthermore, before constructing adjacency relationships based on the maximum clustering distance threshold, the following steps are also included:
[0102] Extract the spatial positions of all personnel and extract the ordinates of the spatial positions. Calculate the perspective distortion compensation coefficient based on the ordinates, where the ordinates represent the depth position of the personnel in the image.
[0103] The preset baseline clustering distance threshold and baseline dense nearest neighbor distance threshold are dynamically corrected based on the perspective distortion compensation coefficient to obtain the maximum clustering distance threshold and dense nearest neighbor distance threshold.
[0104] Among them, the smaller the vertical coordinate of the spatial location, the farther away from the camera. The perspective distortion compensation coefficient makes the corrected maximum clustering distance threshold and dense nearest neighbor distance threshold decrease synchronously as the vertical coordinate decreases, in order to compensate for the visual distance compression effect of people at a distance.
[0105] Specifically, after the headcount is completed, the system performs perspective distortion compensation calculations to correct the near-to-far deviation caused by the overhead camera view. Because surveillance cameras are generally installed at an angle, the image has a natural perspective effect: for the same physical distance, the normalized distance is shorter in areas further away (i.e., areas with smaller vertical coordinate values), and longer in areas closer to the camera (i.e., areas with larger vertical coordinate values).
[0106] If a uniform distance threshold is used for clustering, a systemic bias will occur where distant people are easily misjudged as clustered together, while nearby people are easily missed. Therefore, the system first extracts the ordinate of the spatial position of all people. The ordinate represents the depth position of the person in the image; the smaller the ordinate, the farther the person is from the camera. The perspective distortion compensation coefficient is calculated based on the ordinate. In specific implementation, the baseline horizontal line at the bottom of the image is pre-selected as the depth reference, and the compensation coefficient corresponding to this position is 1.0. Then, based on the camera's installation height and tilt angle parameters, a linear mapping relationship between the ordinate and the compensation coefficient is fitted. That is, the compensation coefficient is equal to the ratio of the ordinate of the person's center point to the ordinate of the baseline position. The smaller the ordinate, the smaller the compensation coefficient, and the greater the correction range of the corresponding distance threshold.
[0107] After obtaining the compensation coefficient, the system dynamically corrects the preset baseline clustering distance threshold and baseline dense nearest neighbor distance threshold based on the perspective distortion compensation coefficient. This yields the maximum clustering distance threshold dmax and the dense nearest neighbor distance threshold ddense adapted to the current depth. The correction rule is that the corrected threshold equals the baseline threshold multiplied by the corresponding compensation coefficient, and both corrected thresholds decrease synchronously as the ordinate decreases. This compensates for the visual distance compression effect of distant people, ensuring that the clustering judgment criteria at different depths remain consistent in the physical space dimension. For example, if the compensation coefficient for the upper distant area of the image (normalized ordinate approximately 0.5) is 0.5 and the baseline maximum clustering distance is 0.22 normalized units, then the corrected maximum clustering distance is 0.11 normalized units, matching the perspective compression ratio at that location and avoiding an imbalance in the judgment criteria due to perspective effects.
[0108] S130, the specific steps for performing a two-level spatial cluster analysis on personnel based on spatial location include:
[0109] Adjacency relationships are constructed based on the maximum clustering distance threshold, and all connected components are identified through breadth-first search to obtain the largest cluster containing the most people and the number of people.
[0110] For each person, count the number of nearest neighbors, and filter out dense core points by combining the dense nearest neighbor distance threshold and the minimum nearest neighbor number threshold.
[0111] Perform connectivity analysis between dense core points to obtain the largest dense core cluster containing the most people and the number of people in it.
[0112] Specifically, for step S130, after threshold correction, the system proceeds to the first layer of spatial clustering, i.e., distance-based connected component analysis. The system constructs the adjacency relationship Aij between personnel based on the maximum clustering distance threshold. It iterates through all personnel pairwise, calculating the Euclidean distance between the center points of two personnel. If the distance is less than or equal to the maximum clustering distance threshold, it determines that the two individuals are adjacent and belong to the same candidate personnel cluster. The adjacency relationship can be represented by an adjacency matrix: Aij is 1 if and only if the Euclidean distance ||ci-cj||2≤dmax, otherwise it is 0. Here, ci and cj are the coordinates of the center points of the i-th and j-th personnel, respectively, and ||ci-cj||2 is the Euclidean distance between the two points, calculated as the square root of the sum of the squares of the differences between the horizontal and vertical coordinates. The distance unit is the same as the coordinate unit, which is a normalized unit.
[0113] After the adjacency relationships are established, the system uses a breadth-first search algorithm to traverse the adjacency relationships of all personnel, identifying all interconnected sets of personnel, i.e., connected components. Each connected component corresponds to a candidate cluster. After traversing all connected components, the set containing the largest number of personnel is selected as the largest cluster, and the total number of people in that cluster, Ncluster, is recorded. Through this distance-based clustering, spatially adjacent personnel can be grouped into the same cluster, filtering out scattered, geographically distant individuals and preventing isolated personnel from interfering with the clustering determination results.
[0114] Next, a second layer of dense core clustering is performed to further filter out chain-like distributions and loosely connected groups. First, the number of neighbors for each person is counted. Based on the dense nearest neighbor distance threshold `ddense`, the total number of other people within a distance of no more than this threshold for each person is counted, using the following formula: , where Ni is the number of neighbors of the i-th person. This is an indicator function; the function takes a value of 1 when the condition within the parentheses is true, and a value of 0 when the condition is false. The system also presets a minimum nearest neighbor threshold Nmin, with a default value of 2 people, meaning that a person needs at least 2 people in close proximity to meet the criteria for a dense core.
[0115] After traversing all personnel, those with a number of nearest neighbors greater than or equal to the minimum nearest neighbor threshold Nmin are marked as dense core points. The set of all dense core points can be represented as Core = {i | Ni ≥ Nmin}. Since the dense nearest neighbor distance threshold is less than the clustering distance threshold, only personnel who are spatially close enough are counted as nearest neighbors. Therefore, although personnel in a chain distribution meet the clustering connectivity requirement, they do not have a sufficient number of nearest neighbors and will not be identified as dense core points.
[0116] After the core point screening is completed, the system performs connected component analysis again within the dense core point range. The connectivity criterion remains that the distance between two points is less than or equal to the dense nearest neighbor distance threshold. A breadth-first search algorithm is used to identify all dense core connected components, selecting the set with the largest number of people as the largest dense core cluster, and recording the total number of people in this cluster, Ndense. The second layer of clustering further tightens the criteria based on the first layer of distance clustering. Only personnel clusters that form sufficiently large dense cores are considered to have clustered dense characteristics. This mechanism eliminates scenarios that are prone to false alarms, such as loose clustering and linear distribution, improving the accuracy of cluster determination.
[0117] It should be noted that the perspective distortion compensation step and the two-layer spatial clustering analysis step are not independent processing steps, but rather have a close upstream and downstream data collaboration and functional support relationship. Because surveillance cameras generally use an oblique overhead shooting method, the image has a natural perspective effect of near objects appearing larger and distant objects appearing smaller. If a fixed distance threshold is directly used for clustering, people in the distance in the image are easily judged as densely clustered (false positives) because their visual distance is compressed, while people in the foreground may be missed (false negatives) because their visual distance is lengthened.
[0118] This application first extracts the ordinate of the spatial location to calculate the perspective distortion compensation coefficient, and then dynamically corrects the maximum clustering distance threshold and the dense nearest neighbor distance threshold, so that the threshold decreases synchronously as the distance between people increases. This compensation correction directly provides a distance measurement benchmark with consistent physical spatial dimensions for subsequent two-layer spatial clustering. In the first-layer distance-based connected component analysis, the corrected threshold ensures that only people who are truly physically close in distant locations are grouped into the same cluster; in the second-layer dense core clustering, the corrected dense nearest neighbor distance threshold ensures that the statistical number of nearest neighbors truly reflects physical density rather than visually compressed density. Perspective distortion compensation fundamentally guarantees the accuracy of the input data for two-layer spatial clustering, enabling the two-layer clustering mechanism (especially the selection of dense core clusters) to accurately distinguish between true physical dense clusters and loose chain distributions. The two work together to reduce false positives and false negatives of clustering caused by perspective distortion, and improve the robustness and accuracy of clustering determination results across the entire depth range of the image.
[0119] S140, the steps for calculating crowd density based on the largest cluster and the number of people specifically include:
[0120] Calculate the bounding rectangle of the largest cluster, and obtain the minimum x-coordinate, maximum x-coordinate, minimum y-coordinate, and maximum y-coordinate of the bounding rectangle;
[0121] Calculate the area of the circumscribed rectangle based on the extreme coordinates of the circumscribed rectangle region;
[0122] Crowd density is calculated based on the largest cluster and the number of people, and the area of the circumscribed rectangle.
[0123] Specifically, for step S140, after completing the two-layer clustering, the population density calculation begins. First, the bounding rectangle of the largest cluster is calculated. The system iterates through the bounding boxes of all individuals within the largest cluster, extracting the minimum x-coordinate of the top-left corner of each bounding box as the minimum x-coordinate of the bounding rectangle, and the maximum x-coordinate of the bottom-right corner of each bounding box as the maximum x-coordinate of the bounding rectangle. Similarly, the minimum y-coordinate of the top-left corner of each bounding box is extracted as the minimum y-coordinate, and the maximum y-coordinate of the bottom-right corner is extracted as the maximum y-coordinate. The calculation rules for the four extreme coordinates are as follows: Here, x1,i and y1,i are the coordinates of the top-left corner of the bounding box of the i-th person within the cluster, and x2,i and y2,i are the coordinates of the corresponding bottom-right corner. The rectangle determined by these four extreme coordinates is the minimum bounding rectangle that encloses the entire largest cluster, representing the overall spatial range occupied by the clustered people in the image.
[0124] The area of the circumscribed rectangle is then calculated. In an optional implementation, if perspective distortion compensation is not enabled in the current application scenario, the system directly calculates the area of the circumscribed rectangle based on the minimum x-coordinate, maximum x-coordinate, minimum y-coordinate, and maximum y-coordinate of the circumscribed rectangle region. The width of the rectangle is obtained by subtracting the minimum x-coordinate from the maximum x-coordinate, and the height of the rectangle is obtained by subtracting the minimum y-coordinate from the maximum y-coordinate. The total area of the circumscribed rectangle, Area, is obtained by multiplying the two. The corresponding calculation formula is Area = (xmax - xmin) × (ymax - ymin).
[0125] In another preferred embodiment, if perspective distortion compensation is enabled in the current application scenario, due to perspective distortion in the monitoring image, the system dynamically restores the extreme values of the ordinate based on the aforementioned perspective distortion compensation coefficients to ensure that the density calculation standard remains consistent across the physical space dimension. Specifically, ymin' = ymin × α_ymin and ymax' = ymax × α_ymax are calculated, where α_ymin and α_ymax are the perspective distortion compensation coefficients at the corresponding ordinates. The width of the bounding rectangle is obtained by subtracting the minimum x-coordinate from the maximum x-coordinate, and the equivalent height of the rectangle is obtained by subtracting the minimum ordinate from the compensated maximum ordinate. Multiplying the two gives the total area of the compensated bounding rectangle, Area, calculated as Area = (xmax - xmin) × (ymax' - ymin').
[0126] Finally, the crowd density (Density) is calculated by dividing the total number of people in the largest cluster (Ncluster) by the area of the circumscribed rectangle (Area). The formula is Density = Ncluster / Area. The density unit is the number of people per normalized area unit. A higher density indicates more people in a unit of space, a higher level of crowd density, and a correspondingly higher risk of stampedes. Quantifying density avoids the limitations of judging gathering solely by the number of people. With the same number of people, the smaller the space occupied and the higher the density, the higher the risk of gathering.
[0127] S150, the steps of performing a multi-condition joint determination including the number of people, clustering conditions, dense core conditions, and density conditions to obtain the clustering determination result of the current frame specifically include:
[0128] The current actual number of people is compared with the global minimum number of people threshold to obtain the number of people criteria;
[0129] The clustering criteria are obtained by comparing the largest cluster and the number of people in it with the cluster size threshold.
[0130] The dense core condition is obtained by comparing the maximum dense core cluster and the number of people in it with the minimum number of people in the dense core cluster.
[0131] Density conditions are obtained by comparing the population density with a minimum density threshold.
[0132] Perform a logical AND operation on the number of people, clustering, dense core, and density conditions to obtain the clustering determination result for the current frame.
[0133] Specifically, for step S150, after all quantitative indicators are calculated, the system performs multi-condition joint aggregation judgment, verifies each of the four independent judgment conditions, and then obtains the final single-frame aggregation judgment result through logical AND operation. The first condition is the number of people. It compares the current actual number of people (Nactual) with the preset global minimum number of people threshold (Nmin_global). If the actual number of people is greater than or equal to this threshold, the number of people condition is met. This is used to filter out non-clustered scenes with very few people in the overall scene from a global perspective; otherwise, it is not met. The second condition is the clustering condition. It compares the number of people in the largest cluster (Ncluster) with the preset clustering threshold (Nmin_cluster). If the number of people in the cluster meets the threshold, the clustering condition is met. This is used to ensure that people are concentrated rather than scattered throughout the scene. The third condition is the dense core condition. It compares the number of people in the largest dense core cluster (Ndense) with the preset minimum number of people in the dense core cluster (Ndense_min). If the threshold is met, the condition is met. This is used to ensure that there are sufficient dense core areas for clustering. The fourth condition is the density condition. It compares the calculated crowd density (Density) with the minimum density threshold (ρmin). If the threshold is met, the density condition is met. This is used to quantitatively verify the density of the crowd.
[0134] After all four conditions are verified, the system performs a dynamic logical AND operation on the results of each condition based on the enabled configuration state. Specifically, when a condition is configured to be disabled, its result does not participate in the final logical judgment; when a condition is enabled and the judgment is true, it is recorded as true. Only when all enabled conditions are true simultaneously is the aggregation judgment result of the current frame true; if any enabled condition is not met, the current frame is judged to have no aggregation. The final judgment result can be expressed as Gathering=∧(Condition_i|Enabled_i==True), where Condition_i corresponds to the result of the i-th condition, and Enabled_i is the enabled state of that condition. Through flexible judgment strategy configuration, for example, density conditions can be enabled in open square scenes to improve the judgment rigor, while density conditions can be disabled in narrow passage scenes to adapt to spatial characteristics, thus achieving flexible judgment strategy configuration.
[0135] Furthermore, before maintaining a confirmation counter for each camera, the following is also included:
[0136] When the current frame clustering determination result is true, obtain the tracking trajectory of all personnel in the largest cluster, and calculate the overall velocity variance and orientation dispersion of the largest cluster based on the tracking trajectory;
[0137] When the overall velocity variance is greater than the velocity variance threshold and the directional dispersion is greater than the directional dispersion threshold, it is determined to be a dynamic high-risk cluster, and the preset baseline confirmation frame number threshold is dynamically reduced according to a preset ratio as the minimum confirmation frame number threshold.
[0138] When the conditions for dynamic high-risk clustering are not met, it is determined to be regular clustering, and the baseline confirmation frame number threshold is used as the minimum confirmation frame number threshold.
[0139] Among them, the overall velocity variance and directional dispersion characterize the degree of pushing and disorderly movement within the crowd. The minimum confirmation frame threshold corresponding to dynamic high-risk aggregation is lower than the minimum confirmation frame threshold corresponding to regular aggregation, so as to achieve accelerated response under high-risk conditions.
[0140] Specifically, after a single-frame clustering determination is completed, the system further analyzes the motion characteristics and risk level of the cluster and dynamically adjusts the timing verification criteria. When the clustering determination result of the current frame is true, the system extracts the tracking trajectory of all personnel in the largest cluster, retrieves the historical position sequence of each personnel for a preset number of consecutive frames (e.g., 10 frames), and calculates the instantaneous motion velocity vector of each person based on the position difference between adjacent frames and the frame interval time, including the velocity magnitude and motion direction.
[0141] Based on this, the overall velocity variance of the entire cluster is calculated, which is the variance of the velocity magnitudes of all individuals within the cluster. A larger variance indicates more significant velocity differences within the crowd, potentially indicating pushing, running, or disorderly surging. Simultaneously, the directional dispersion of the crowd is calculated. Each person's movement direction is converted into a unit direction vector. All unit vectors are summed, and the magnitude of the resultant vector is calculated. A smaller resultant vector magnitude indicates more dispersed movement directions and a higher degree of disorder. Directional dispersion can be defined as 1 minus the ratio of the resultant vector magnitude to the total number of people, ranging from 0 to 1. Higher values indicate more chaotic directions.
[0142] The system presets a velocity variance threshold and a direction dispersion threshold. If the overall velocity variance is greater than the velocity variance threshold and the direction dispersion is also greater than the direction dispersion threshold, the current gathering is determined to be a dynamic high-risk gathering. This type of gathering is usually accompanied by disorderly surging, pushing and shoving, or panicked evacuation within the crowd. The safety risk is much higher than that of ordinary gatherings, so a faster response speed is required.
[0143] For high-risk scenarios, the system dynamically reduces the preset baseline confirmation frame count threshold as the currently effective minimum confirmation frame count threshold Nconfirm, thereby shortening the verification time and accelerating alarms in high-risk situations. The dynamic reduction rule can be based on a preset reduction ratio. For example, if a high-risk reduction coefficient z is set (default value is 0.5), then the dynamically reduced minimum confirmation frame count threshold Nconfirm = Nbase × z, where Nbase is the baseline confirmation frame count threshold. Simultaneously, the system presets a minimum confirmation frame count lower limit (e.g., 1 frame). When the calculated Nconfirm is less than the lower limit, the lower limit value is used to prevent the threshold from decreasing to 0 and causing logical failure.
[0144] If the dual threshold conditions for dynamic high-risk gathering are not met, it is judged as regular gathering (including low-risk or low-disorder scenarios such as static gathering, queuing, and collective movement in a unified direction). The system maintains the original baseline confirmation frame threshold as the minimum confirmation frame threshold, maintaining a relatively strict timing verification standard. Continuous verification with more frames ensures the stability of the judgment and avoids false alarms caused by instantaneous crowd gathering or detection jitter. Overall, the dynamic adjustment mechanism achieves a match between risk level and response speed. High-risk scenarios prioritize response speed, while regular scenarios prioritize judgment accuracy, balancing safety and reliability with timely handling.
[0145] It should be noted that, further, the dynamic risk assessment step before maintaining the confirmation counter in this application has a deep closed-loop collaborative relationship with the step of calculating the current actual number of people (multi-target tracking) and the step of verifying the timing consistency.
[0146] On the one hand, the multi-target tracking trajectories (including historical position sequences, real-time speed, and direction of motion) upon which dynamic risk assessment relies are the intermediate data generated by trajectory status updates and lifecycle management in the process of calculating the current actual number of people. While completing the people count, the system deeply mines the kinematic characteristics of the tracking trajectories, and can calculate the overall speed variance and direction dispersion without adding a huge additional motion detection overhead, thus maximizing the utilization of the value of the tracking data.
[0147] On the other hand, the output of dynamic risk assessment directly determines the rigor of temporal consistency verification. When crowds gather and exhibit high velocity variance and high directional dispersion (characterizing dynamic high risks such as pushing and disorderly surges), the system dynamically reduces the minimum confirmation frame threshold, enabling the temporal verification and alarm modules to quickly pass verification and trigger alarms with fewer consecutive frames. When crowds are in a normal or low-risk gathering state, the system maintains or restores a higher confirmation frame threshold, requiring longer continuous verification. This collaborative mechanism achieves adaptive adjustment of verification duration driven by risk level. In high-risk scenarios, priority is given to ensuring response speed to gain processing time, while in low-risk scenarios, priority is given to ensuring judgment accuracy to filter out instantaneous interference. A dynamic balance is achieved between security and reliability, resolving the contradiction that traditional fixed-frame-count verification mechanisms cannot simultaneously address rapid response in high-risk situations and suppress false alarms in low-risk situations.
[0148] Reference Figure 4 S160, the steps of performing timing consistency verification based on the current frame aggregation determination result and outputting an alarm when the verification passes specifically include S410-S430:
[0149] S410 maintains a confirmation counter for each camera. When the current frame aggregation determination result is true, the count value of the confirmation counter is incremented by one; otherwise, it is reset to zero.
[0150] S420 compares the count value of the confirmation counter with the minimum confirmation frame threshold. When the count value is not less than the minimum confirmation frame threshold, the verification is deemed successful and an alarm is triggered.
[0151] S430 starts a cooling timer after an alarm is triggered, suppresses similar alarms within the cooling time threshold, and resumes normal detection after the cooling time threshold expires.
[0152] Specifically, for step S160, after determining the risk level and confirmation threshold, the system performs a timing consistency verification, maintaining an independent confirmation counter for each surveillance camera to count the number of frames that continuously meet the aggregation judgment conditions. After processing the aggregation judgment of each frame, if the judgment result of the current frame is true, the confirmation counter value of the corresponding camera is incremented by 1; if the judgment result of the current frame is false, the counter is cleared to zero and the accumulation starts again.
[0153] The current confirmation counter value is then compared with the minimum confirmation frame count threshold. When the counter value is greater than or equal to the minimum confirmation frame count threshold, it indicates that the crowd gathering state has been stable for multiple consecutive frames, the timing consistency verification is passed, and the system officially triggers the crowd gathering alarm. The alarm triggering judgment rule can be expressed as Alarm = (Counter ≥ Nconfirm), where Counter is the current count value of the confirmation counter and Nconfirm is the minimum confirmation frame count threshold. Through the frame count confirmation mechanism, the system can effectively filter false alarms caused by transient interference while ensuring response speed, thus improving the reliability of alarm results.
[0154] Once the alarm is officially triggered, the system immediately starts the cooling timer for the corresponding camera. Within the preset cooling time threshold T_cooldown, which is set to 30 seconds by default, the system will not repeatedly push the same type of alarm even if it continuously detects a clustering state. This avoids information redundancy caused by repeated alarms triggered by the same clustering event and reduces the information processing burden on the on-duty personnel.
[0155] Once the accumulated timer reaches the cooling time threshold, the system automatically deactivates the cooling state and resumes normal detection and alarm logic. If the gathering event continues or a new gathering event occurs at this time, the alarm can be triggered again. The cooling time can be flexibly configured according to the characteristics of personnel flow in the scene. Shorter cooling times can be set for scenes with fast personnel flow and short gathering durations, while longer cooling times can be appropriately extended for scenes with long-term gatherings such as large events.
[0156] Furthermore, in the process of multi-condition joint judgment and timing consistency verification, the system has specifically handled the following boundary cases:
[0157] (1) Empty detection result processing: When the system does not detect any personnel in the current frame, it directly clears the confirmation counter of the corresponding camera, does not trigger any alarm, and keeps the system in a ready state;
[0158] (2) Single person processing: When the system detects only a single person, the dense core cluster cannot be formed, and the dense core condition is automatically judged as a failure, and the aggregation condition is not met;
[0159] (3) Boundary overlap handling: When the personnel boundary boxes overlap or are extremely close, the system's calculation based on the center point distance is unaffected, and the dense core judgment is more stringent, thereby effectively identifying the real high-density clusters and avoiding false alarms.
[0160] Furthermore, to ensure real-time processing requirements, the system controls and optimizes the complexity of the two-layer spatial clustering algorithm. In the nearest neighbor statistics process of distance clustering and dense core clustering, the basic time complexity is O(n²), where n is the number of people, and the space complexity is O(n). To further reduce computational overhead, the system can introduce spatial index structures such as KD-trees to reduce the complexity of nearest neighbor search to O(nlogn). Simultaneously, leveraging inter-frame continuity, incremental updates are performed only on the changed parts, and the distance calculation process supports parallel processing, thus ensuring a single-frame processing time of less than 50ms, making it suitable for deployment on edge computing devices.
[0161] The system supports dynamic threshold configuration to adapt to the needs of different monitoring scenarios. Specifically, for narrow passage scenarios, the recommended threshold for the number of people in a cluster (Nthreshold) is 5-8, the recommended maximum clustering distance (dmax) is 0.18, and the recommended minimum confirmation frame count (Nconfirm) is 3 frames. For open plaza scenarios, the recommended thresholds are 15-20 people (Nthreshold), 0.25 (dmax), and 5 frames (Nconfirm). For waiting hall scenarios, the recommended thresholds are 10-15 people (Nthreshold), 0.22 (dmax), and 3 frames (Nconfirm). For security checkpoint scenarios, the recommended thresholds are 8-12 people (Nthreshold), 0.20 (dmax), and 3 frames (Nconfirm). These scenario-adaptive threshold configurations improve the system's usability and accuracy.
[0162] Based on the above method embodiments, the second embodiment of this application discloses a crowd gathering detection system. The crowd gathering detection system of this application embodiment can implement any of the above-described crowd gathering detection methods, and the specific working process of each module in the crowd gathering detection system can be referred to the corresponding process in the above method embodiments.
[0163] For ease of understanding, an example is as follows: A crowd gathering detection system includes:
[0164] The personnel detection and localization module is used to acquire input video frames and preprocess them, then perform personnel detection and localization on the preprocessed video frames to obtain personnel bounding boxes and their corresponding spatial positions.
[0165] The multi-target tracking and fusion module is used to track multiple targets based on the personnel bounding box and to calculate the current actual number of people by fusing the detection and tracking results.
[0166] The two-layer spatial clustering analysis module is used to perform two-layer spatial clustering analysis on people based on their spatial location. The two-layer spatial clustering analysis includes a first-layer clustering based on distance to obtain the largest cluster and the number of people, and a second-layer clustering based on dense cores to obtain the largest dense core cluster and the number of people.
[0167] The density calculation module is used to calculate the crowd density based on the largest cluster and the number of people; the joint determination module is used to perform multi-condition joint determination based on the current actual number of people, the largest cluster and the number of people, the largest dense core cluster and the number of people, and the crowd density, including the number of people, clustering conditions, dense core conditions, and density conditions, and obtain the current frame cluster determination result.
[0168] The timing verification and alarm module is used to perform timing consistency verification based on the current frame aggregation judgment result, and output an alarm when the verification is successful.
[0169] It is understood that, in addition to applications in fixed surveillance camera systems, the core solution described above can also be applied to intelligent security robots or patrol robots with autonomous mobility. Specific application examples are as follows:
[0170] The robot hardware configuration includes at least: a vision sensor (such as a monocular or binocular camera) for acquiring video frames in front, a chassis mechanism for supporting the robot's movement, and an edge computing processing unit for personnel detection, multi-target tracking, and two-layer spatial clustering and decision-making algorithms.
[0171] In application, the robot autonomously patrols complex large-scale scenarios such as shopping malls, exhibition halls, or industrial parks. Visual sensors capture real-time video frames of the surrounding environment, while edge computing units perform preprocessing and personnel detection and localization to obtain personnel bounding boxes and spatial positions. Since the robot's position is dynamic, the perspective angle of the captured images also changes with movement. The system still utilizes perspective distortion compensation steps to dynamically adjust the clustering distance threshold based on the vertical coordinate of the personnel's center point in the current image, ensuring the accuracy of clustering decisions from different perspectives. Subsequently, the system performs two-layer spatial clustering and multi-condition joint decision-making.
[0172] When the robot patrols an area and determines that a crowd has gathered, the system further retrieves trajectory data generated by multi-target tracking to calculate the overall velocity variance and directional dispersion of the crowd. If it is determined to be a dynamic high-risk gathering (such as a crowd disturbance or panicked evacuation), the system dynamically reduces the minimum confirmation frame threshold, controls the robot to immediately trigger the audible and visual alarm device, and sends the gathering location and risk level to the back-end command center via the communication module; if it is a regular gathering (such as queuing), it maintains normal patrol or remote recording.
[0173] Deploying this solution on a robot overcomes the limitations of fixed cameras, such as limited field of view and blind spots, enabling proactive patrols of large-scale, dynamic crowd gathering risks. The collaborative solution of perspective distortion compensation and dynamic risk assessment overcomes distance judgment deviations caused by changes in perspective during robot movement, ensuring detection accuracy in motion. This allows the robot to achieve accelerated "detection and warning" responses in high-risk, sudden crowd gathering events, improving the intelligence and timeliness of dynamic security scenarios.
[0174] Although this application has been described herein in conjunction with various embodiments, those skilled in the art, by reviewing the accompanying drawings, disclosure, and appended claims, will understand and implement other variations of the disclosed embodiments in carrying out the claimed application. In the claims, the word "comprising" does not exclude other components or steps, and "a" or "an" does not exclude a plurality. A single processor or other unit can implement several functions listed in the claims. While different dependent claims may recite certain measures, this does not mean that these measures cannot be combined to produce a good effect.
[0175] The above are all preferred embodiments of this application and are not intended to limit the scope of protection of this application. Any feature disclosed in this specification (including the abstract and drawings) may be replaced by other equivalent or similar features unless specifically stated otherwise. That is, unless specifically stated otherwise, each feature is only one example of a series of equivalent or similar features.
Claims
1. A method for detecting crowd aggregation, characterized in that, include: The system acquires and preprocesses input video frames, performs personnel detection and localization on the preprocessed video frames, and obtains personnel bounding boxes and their corresponding spatial positions. Multi-target tracking is performed based on the personnel bounding box, and the detection and tracking results are fused to calculate the current actual number of people; A two-layer spatial clustering analysis is performed on the personnel based on their spatial location. The two-layer spatial clustering analysis includes a first-layer clustering based on distance to obtain the largest cluster and the number of people, and a second-layer clustering based on dense cores to obtain the largest dense core cluster and the number of people. Calculate the crowd density based on the largest cluster and the number of people in it; Based on the current actual number of people, the largest cluster and number of people, the largest dense core cluster and number of people, and the crowd density, a multi-condition joint determination including the number of people, clustering conditions, dense core conditions, and density conditions is performed to obtain the current frame clustering determination result. Based on the current frame aggregation determination result, a timing consistency verification is performed, and an alarm is output when the verification passes.
2. The crowd gathering detection method according to claim 1, characterized in that, The specific steps for detecting and locating people in preprocessed video frames to obtain their bounding boxes and corresponding spatial positions include: Perform target detection on the preprocessed video frames to obtain the initial personnel bounding boxes and their corresponding confidence scores; Set a confidence threshold, filter and retain the initial personnel bounding boxes with a confidence level not less than the confidence threshold, and use them as the filtered personnel bounding boxes; The center point of the person is calculated based on the upper left and lower right corner coordinates of the filtered person bounding box, and is used as the spatial position of the person bounding box; Configure the coordinates of the polygon vertices to define the region of interest. Use the ray method to determine whether the center point of the person is within the region of interest. Only retain the bounding box of the person and the corresponding spatial position of the person located within the region of interest. The ray method involves emitting a horizontal ray to the right from the center point of the person and counting the number of intersections between the ray and the polygon boundary. If the number of intersections is odd, the person is determined to be within the region of interest; if it is even, the person is determined to be outside the region of interest.
3. The crowd gathering detection method according to claim 1, characterized in that, The steps of performing multi-target tracking based on the personnel bounding box and calculating the current actual number of people by fusing detection and tracking results specifically include: Assign a unique tracking identifier to the detected personnel, match the detection results of the current frame with historical trajectories, update the status of successfully matched trajectories, and handle the creation and deletion of trajectories; After processing the creation and deletion of tracks, the total number of tracks that are not yet expired is counted as the current number of active tracks; Obtain the number of people detected in the current frame, and take the maximum value between the number of people detected in the current frame and the number of active trajectories as the current actual number of people.
4. The crowd gathering detection method according to claim 1, characterized in that, The specific steps for performing two-level spatial clustering analysis on personnel based on their spatial location include: Extract the spatial locations of all personnel, construct adjacency relationships based on the maximum clustering distance threshold, identify all connected components through breadth-first search, and obtain the largest cluster containing the most personnel and the number of people. For each person, count the number of nearest neighbors, and filter out dense core points by combining the dense nearest neighbor distance threshold and the minimum nearest neighbor number threshold. Perform connectivity analysis between the dense core points to obtain the largest dense core cluster containing the most people and the number of people in it.
5. The crowd gathering detection method according to claim 1, characterized in that, The steps for calculating crowd density based on the largest cluster and the number of people specifically include: Calculate the bounding rectangle of the largest cluster, and obtain the minimum x-coordinate, maximum x-coordinate, minimum y-coordinate, and maximum y-coordinate of the bounding rectangle; Calculate the area of the circumscribed rectangle based on the extreme coordinates of the circumscribed rectangular region; The population density is calculated based on the largest cluster and the number of people in it, and the area of the circumscribed rectangle.
6. The method for detecting crowd gathering according to claim 1, characterized in that, The steps for obtaining the current frame clustering determination result by performing a multi-condition joint determination based on the current actual number of people, the largest cluster and number of people, the largest dense core cluster and number of people, and the crowd density, including the number of people condition, clustering condition, dense core condition, and density condition, specifically include: The current actual number of people is compared with the global minimum number of people threshold to obtain the number of people conditions; The clustering conditions are obtained by comparing the largest cluster and the number of people in it with the cluster size threshold. The dense core cluster and its number of people are compared with the minimum number of people threshold for the dense core cluster to obtain the dense core condition; The density condition is obtained by comparing the population density with the minimum density threshold. Perform a logical AND operation on the number of people condition, the clustering condition, the dense core condition, and the density condition to obtain the clustering determination result of the current frame.
7. The method for detecting crowd gathering according to claim 1, characterized in that, The steps of performing timing consistency verification based on the current frame aggregation determination result and outputting an alarm when the verification passes specifically include: A confirmation counter is maintained for each camera. When the current frame aggregation determination result is true, the count value of the confirmation counter is incremented by one; otherwise, it is reset to zero. The count value of the confirmation counter is compared with the minimum confirmation frame threshold. When the count value is not less than the minimum confirmation frame threshold, the verification is deemed successful and an alarm is triggered. After an alarm is triggered, a cooling timer is started to suppress similar alarms within a cooling time threshold, and normal detection is resumed after the cooling time threshold is reached.
8. The crowd gathering detection method according to claim 4, characterized in that, Before constructing adjacency relationships based on the maximum clustering distance threshold, the following steps are also included: Extract the vertical coordinate of the spatial position, and calculate the perspective distortion compensation coefficient based on the vertical coordinate, wherein the vertical coordinate represents the depth position of the person in the picture; The preset baseline clustering distance threshold and baseline dense nearest neighbor distance threshold are dynamically corrected based on the perspective distortion compensation coefficient to obtain the maximum clustering distance threshold and the dense nearest neighbor distance threshold. Wherein, the smaller the vertical coordinate of the spatial location, the farther away from the camera, and the perspective distortion compensation coefficient makes the corrected maximum clustering distance threshold and the dense nearest neighbor distance threshold decrease synchronously as the vertical coordinate decreases, so as to compensate for the visual distance compression effect of distant people.
9. The method for detecting crowd gathering according to claim 7, characterized in that, Before maintaining a confirmation counter for each camera, the following is also included: When the current frame aggregation determination result is true, the tracking trajectory of all personnel in the largest aggregation cluster is obtained, and the overall velocity variance and orientation dispersion of the largest aggregation cluster are calculated based on the tracking trajectory. When the overall velocity variance is greater than the velocity variance threshold and the directional dispersion is greater than the directional dispersion threshold, it is determined to be a dynamic high-risk cluster, and the preset baseline confirmation frame number threshold is dynamically reduced according to a preset ratio as the minimum confirmation frame number threshold. When the conditions for dynamic high-risk clustering are not met, it is determined to be a regular clustering, and the baseline confirmation frame number threshold is used as the minimum confirmation frame number threshold. The overall velocity variance and directional dispersion characterize the degree of pushing and disorderly movement within the crowd. The minimum confirmation frame threshold corresponding to the dynamic high-risk cluster is less than the minimum confirmation frame threshold corresponding to the regular cluster, so as to achieve accelerated response under high-risk conditions.
10. A crowd gathering detection system, characterized in that, Performing the crowd gathering detection method as described in any one of claims 1 to 9 includes: The personnel detection and localization module is used to acquire input video frames and preprocess them, then perform personnel detection and localization on the preprocessed video frames to obtain personnel bounding boxes and their corresponding spatial positions. The multi-target tracking and fusion module is used to perform multi-target tracking based on the personnel bounding box, and to fuse the detection and tracking results to calculate the current actual number of people. A two-layer spatial clustering analysis module is used to perform two-layer spatial clustering analysis on personnel based on the spatial location. The two-layer spatial clustering analysis includes a first-layer clustering based on distance to obtain the largest cluster and the number of people, and a second-layer clustering based on dense cores to obtain the largest dense core cluster and the number of people. The density calculation module is used to calculate the crowd density based on the largest cluster and the number of people. The joint determination module is used to perform a multi-condition joint determination based on the current actual number of people, the largest cluster and number of people, the largest dense core cluster and number of people, and the crowd density, including the number of people condition, clustering condition, dense core condition and density condition, to obtain the current frame clustering determination result; The timing verification and alarm module is used to perform timing consistency verification based on the current frame aggregation determination result, and output an alarm when the verification is successful.
