我在 Yolov8 模型中跟踪对象时,使用 opencv 在图像中绘制了一个多边形。当带有我想要的标签的对象进入我绘制的区域时,我想打印“警告”输出。我该怎么做?
我查看了 YouTube 视频和资源,但找不到我想要的资源。
一种解决方案是使用包 Shapely,它能够计算几何图形之间的相互作用。
如果您从 YOLOv8 创建“停留区域”和检测框作为 Shapely Polygon 对象,那么计算交集很容易。
这是一个简单的 Python 示例。蓝色多边形将是“待出区域”,方框将是 YOLOv8 检测。
import matplotlib.pyplot as plt
from shapely.geometry import box, Polygon
import shapely.plotting
def color_intersection(polygon_0: Polygon, polygon_1: Polygon) -> str:
"""
If polygons intersect, set color red else set color green.
:param polygon_0: First polygon
:param polygon_1: Second polygon
:return: Color string
"""
return 'red' if polygon_0.intersection(polygon_1) else 'green'
stay_out = Polygon(
[
(0, 0),
(0, 7),
(5, 10),
(10, 10),
(7, 0),
])
detections = (
box(5, 0, 10, 5),
box(15, 0, 20, 20),
)
fig, ax = plt.subplots()
shapely.plotting.plot_polygon(stay_out, ax=ax, color='blue')
for detection in detections:
shapely.plotting.plot_polygon(
detection,
ax=ax,
color=color_intersection(stay_out, detection),
)
fig.suptitle('Shapely Intersection Example')
fig.tight_layout()
fig.show()
YOLOv8 通过属性
Results
进行推理后返回一个 boxes
对象,这是一个 Boxes
对象。 Boxes
对象具有属性“cls”,其中包含检测的预测类别的整数。在此张量中搜索您感兴趣的类 ID,然后创建您的消息。
from ultralytics import YOLO
# Define model: YOLO
model = YOLO(<path_to_trained_YOLOv8_model_weights.pt>)
# Perform inference: List[Results]
results = model(<path_to_image(s)_source>)
# First image results: Results
results[0]
# Mapping of class ID to name: Dict[int, str]
results[0].names
# Detections: Boxes
results[0].boxes
# Detection classes: torch.Tensor
results[0].boxes.cls
# Check if dog class (ID = 14) in detections
for result in results:
if 14 in result.boxes.cls:
<generate notification>