社交距离的应用¶
引言¶
在本教程中,我们将通过一个简单的使用案例来检查 有人违反了社交距离规则.
请注意,本教程的目的是帮助您熟悉 BrainFrame的推断能力的使用. 案子比这本剧本要复杂得多.
在这个剧本中,我们只有两个规则:
- 两个
person检测界限框不能重叠 - 两个人检测的边界框之间的距离 必须大于500像素 (默认可配置).
您可以在我们的 GitHub存储库.
设置环境¶
环境设置与我们在 [微信通知][wechat_tutorial] 您可以参考它,设置 环境.
在本教程中,我们将使用的API功能是:
api.set_stream_configuration(...)api.set_zone(...)api.get_zone_status_stream()api.set_plugin_option_vals(...)
帮助功能¶
首先,进口依赖性:
import math
from argparse import ArgumentParser
from pathlib import Path
from brainframe.api import BrainFrameAPI, bf_codecs
为了使脚本更可读,我们会提前定义两个辅助功能.
首先检查两个边界框是否重叠:
# Help function to check if two detections are overlapped
def is_overlapped(det1: bf_codecs.Detection,
det2: bf_codecs.Detection) -> bool:
"""
:param det1: First Detection
:param det2: Second Detection
:return: If the two Detections' bboxes are overlapped
"""
# Sort the x, y in ascending order
coords1_sorted_x = sorted([c[0] for c in det1.coords])
coords2_sorted_x = sorted([c[0] for c in det2.coords])
coords1_sorted_y = sorted([c[1] for c in det1.coords])
coords2_sorted_y = sorted([c[1] for c in det2.coords])
# Return False if the rects do not overlap horizontally
if coords1_sorted_x[0] > coords2_sorted_x[-1] \
or coords2_sorted_x[0] > coords1_sorted_x[-1]:
return False
# Return False if the rects do not overlap vertically
if coords1_sorted_y[0] > coords2_sorted_y[-1] \
or coords2_sorted_y[0] > coords1_sorted_y[-1]:
return False
# Otherwise, the two rects must overlap
return True
根据第二个辅助函数, 两个边界框:
# Helper function to calculate the distance between the center points of two
# detections
def get_distance(det1: bf_codecs.Detection,
det2: bf_codecs.Detection) -> float:
"""
:param det1: First Detection
:param det2: First Detection
:return: Distance between the center of the two Detections
"""
return math.hypot(det1.center[0] - det2.center[0],
det1.center[1] - det2.center[1])
从本地文件创建一个新的流¶
首先,启动API实例并连接到服务器.
# Initialize the API
api = BrainFrameAPI("http://localhost")
然后,我们想开始视频流,你可以在我们的 教程库.
# Upload the local file to the database and get its storage ID
storage_id = api.new_storage(
data=Path("../videos/social_distancing.mp4").read_bytes(),
mime_type="application/octet-stream"
)
# Create a Stream Configuration referencing the new storage ID
new_stream_config = bf_codecs.StreamConfiguration(
# The display name on the client side
name="Demo",
# This stream will be from a file
connection_type=bf_codecs.StreamConfiguration.ConnType.FILE,
# The storage ID of the file
connection_options={
"storage_id": storage_id,
},
runtime_options={},
premises_id=None,
)
# Tell the server to connect to that stream configuration
new_stream_config = api.set_stream_configuration(new_stream_config)
接下来,我们将配置一些算法胶囊选项,而不是使用默认的选项 我们之前定义过了一些错误的检测.
# Filter out duplicate detections
api.set_plugin_option_vals(
plugin_name="detector_people_and_vehicles_fast",
stream_id=new_stream_config.id,
option_vals={
# If one bounding box is overlapped >80% with another bounding box, we
# assume that they are really the same detection and ignore them.
"max_detection_overlap": 0.8,
"threshold": 0.9
}
)
最后,不要忘记告诉"BrainFrame"开始分析/预制推断 在河流上.
# Start analysis on the stream
api.start_analyzing(new_stream_config.id)
检查社会距离规则¶
接下来,类似于 微信通知教程, 我们将得到区域状态代器. 检查我们上述规定的社会距离规则.
在微信通知教程中, 在这篇教程中,我们将重组 为了让我们的计算更容易.
# Verify that there is at least one connected stream
assert len(api.get_stream_configurations()), \
"There should be at least one stream already configured!"
# Get the inference stream.
for zone_status_packet in api.get_zone_status_stream():
# Organize detections results as a dictionary of
# {stream_id: [Detections]}.
detections_per_stream = {
stream_id: zone_status.within
for stream_id, zone_statuses in zone_status_packet.items()
for zone_name, zone_status in zone_statuses.items()
if zone_name == "Screen"
}
# Iterate over each stream_id/detections combination
for stream_id, detections in detections_per_stream.items():
# Filter out Detections that are not people
detections = [detection for detection in detections
if detection.class_name == "person"]
# Skip stream frame if there are no person detections
if len(detections) == 0:
continue
# Compare the distance between each detections.
for i, current_detection in enumerate(detections):
violating = False
for j in range(i + 1, len(detections)):
target_detection = detections[j]
current_detection: bf_codecs.Detection
target_detection: bf_codecs.Detection
# If the bbox representing two people are overlapped, the
# distance is 0, otherwise it's the distance between the
# center of these two bbox.
if is_overlapped(current_detection, target_detection):
distance = 0
else:
distance = get_distance(current_detection, target_detection)
if distance < min_distance:
print(f"People are violating the social distancing rules, "
f"current distance: {distance}, location: "
f"{current_detection.coords}, "
f"{target_detection.coords}")
violating = True
break
if violating:
break
现在,每当人们违反我们的社会距离规则, 信息,包括它们在框架中位置.
People are violating the social distancing rules, current distance: 499.8899878973373, location: [[30, 340], [411, 340], [411, 926], [30, 926]], [[571, 238], [828, 238], [828, 742], [571, 742]]