跳至内容

分析使用Ultralytics YOLOv8

导言

本指南全面介绍了三种基本的数据可视化类型:折线图、条形图和饼图。每一部分都包含如何使用Python 创建这些可视化数据的分步说明和代码片段。

视觉样本

折线图 条形图 饼图
折线图 条形图 饼图

图表为何重要

  • 折线图是跟踪短期和长期变化以及比较同一时期多组变化的理想工具。
  • 条形图则适用于比较不同类别的数量,并显示类别与其数值之间的关系。
  • 最后,饼图可以有效地说明不同类别之间的比例,并显示整体的各个部分。

分析实例

import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")

cap = cv2.VideoCapture("Path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

out = cv2.VideoWriter("line_plot.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(
    type="line",
    writer=out,
    im0_shape=(w, h),
    view_img=True,
)
total_counts = 0
frame_count = 0

while cap.isOpened():
    success, frame = cap.read()

    if success:
        frame_count += 1
        results = model.track(frame, persist=True, verbose=True)

        if results[0].boxes.id is not None:
            boxes = results[0].boxes.xyxy.cpu()
            for box in boxes:
                total_counts += 1

        analytics.update_line(frame_count, total_counts)

        total_counts = 0
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")

cap = cv2.VideoCapture("Path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
out = cv2.VideoWriter("multiple_line_plot.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(
    type="line",
    writer=out,
    im0_shape=(w, h),
    view_img=True,
    max_points=200,
)

frame_count = 0
data = {}
labels = []

while cap.isOpened():
    success, frame = cap.read()

    if success:
        frame_count += 1

        results = model.track(frame, persist=True)

        if results[0].boxes.id is not None:
            boxes = results[0].boxes.xyxy.cpu()
            track_ids = results[0].boxes.id.int().cpu().tolist()
            clss = results[0].boxes.cls.cpu().tolist()

            for box, track_id, cls in zip(boxes, track_ids, clss):
                # Store each class label
                if model.names[int(cls)] not in labels:
                    labels.append(model.names[int(cls)])

                # Store each class count
                if model.names[int(cls)] in data:
                    data[model.names[int(cls)]] += 1
                else:
                    data[model.names[int(cls)]] = 0

        # update lines every frame
        analytics.update_multiple_lines(data, labels, frame_count)
        data = {}  # clear the data list for next frame
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")

cap = cv2.VideoCapture("Path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

out = cv2.VideoWriter("pie_chart.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(
    type="pie",
    writer=out,
    im0_shape=(w, h),
    view_img=True,
)

clswise_count = {}

while cap.isOpened():
    success, frame = cap.read()
    if success:
        results = model.track(frame, persist=True, verbose=True)
        if results[0].boxes.id is not None:
            boxes = results[0].boxes.xyxy.cpu()
            clss = results[0].boxes.cls.cpu().tolist()
            for box, cls in zip(boxes, clss):
                if model.names[int(cls)] in clswise_count:
                    clswise_count[model.names[int(cls)]] += 1
                else:
                    clswise_count[model.names[int(cls)]] = 1

            analytics.update_pie(clswise_count)
            clswise_count = {}

        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")

cap = cv2.VideoCapture("Path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

out = cv2.VideoWriter("bar_plot.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(
    type="bar",
    writer=out,
    im0_shape=(w, h),
    view_img=True,
)

clswise_count = {}

while cap.isOpened():
    success, frame = cap.read()
    if success:
        results = model.track(frame, persist=True, verbose=True)
        if results[0].boxes.id is not None:
            boxes = results[0].boxes.xyxy.cpu()
            clss = results[0].boxes.cls.cpu().tolist()
            for box, cls in zip(boxes, clss):
                if model.names[int(cls)] in clswise_count:
                    clswise_count[model.names[int(cls)]] += 1
                else:
                    clswise_count[model.names[int(cls)]] = 1

            analytics.update_bar(clswise_count)
            clswise_count = {}

        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")

cap = cv2.VideoCapture("path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

out = cv2.VideoWriter("area_plot.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(
    type="area",
    writer=out,
    im0_shape=(w, h),
    view_img=True,
)

clswise_count = {}
frame_count = 0

while cap.isOpened():
    success, frame = cap.read()
    if success:
        frame_count += 1
        results = model.track(frame, persist=True, verbose=True)

        if results[0].boxes.id is not None:
            boxes = results[0].boxes.xyxy.cpu()
            clss = results[0].boxes.cls.cpu().tolist()

            for box, cls in zip(boxes, clss):
                if model.names[int(cls)] in clswise_count:
                    clswise_count[model.names[int(cls)]] += 1
                else:
                    clswise_count[model.names[int(cls)]] = 1

        analytics.update_area(frame_count, clswise_count)
        clswise_count = {}
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()

论据 Analytics

下面的表格显示了 Analytics 争论:

名称 类型 默认值 说明
type str None 数据或对象类型。
im0_shape tuple None 初始图像的形状。
writer cv2.VideoWriter None 用于写入视频文件的对象。
title str ultralytics 可视化标题。
x_label str x X 轴的标签。
y_label str y y 轴的标签。
bg_color str white 背景颜色
fg_color str black 前景色
line_color str yellow 线条的颜色
line_width int 2 线条的宽度。
fontsize int 13 文本字体大小。
view_img bool False 显示图像或视频的标志。
save_img bool True 标记保存图像或视频。
max_points int 50 对于多条线,在删除初始点之前,在框架上绘制的总点数。
points_width int 15 线点的宽度突出显示。

论据 model.track

名称 类型 默认值 说明
source im0 None 图像或视频的源目录
persist bool False 帧与帧之间的持久轨迹
tracker str botsort.yaml 跟踪方法 "bytetrack "或 "botsort
conf float 0.3 置信度阈值
iou float 0.5 借据阈值
classes list None 按类别筛选结果,即 classes=0,或 classes=[0,2,3]
verbose bool True 显示物体跟踪结果

结论

了解何时以及如何使用不同类型的可视化数据对于有效的数据分析至关重要。折线图、柱状图和饼图是基本工具,可以帮助您更清晰、更有效地传达数据信息。

常见问题

如何使用Ultralytics YOLOv8 Analytics 创建折线图?

要使用Ultralytics YOLOv8 Analytics 创建折线图,请按照以下步骤操作:

  1. 加载YOLOv8 模型并打开视频文件。
  2. 初始化 Analytics 类,类型设置为 "行"。
  3. 迭代视频帧,用相关数据更新折线图,如每帧的对象计数。
  4. 保存显示折线图的输出视频。

例如

import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")
cap = cv2.VideoCapture("Path/to/video/file.mp4")
out = cv2.VideoWriter("line_plot.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(type="line", writer=out, im0_shape=(w, h), view_img=True)

while cap.isOpened():
    success, frame = cap.read()
    if success:
        results = model.track(frame, persist=True)
        total_counts = sum([1 for box in results[0].boxes.xyxy])
        analytics.update_line(frame_count, total_counts)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

有关配置 Analytics 课程,请访问 使用Ultralytics YOLOv8 进行分析 📊 节。

使用Ultralytics YOLOv8 绘制条形图有什么好处?

使用Ultralytics YOLOv8 创建条形图有几个好处:

  1. 实时数据可视化:将目标检测结果无缝集成到条形图中,实现动态更新。
  2. 易用性:简单的应用程序接口和功能使其能够直接实施和可视化数据。
  3. 自定义:自定义标题、标签、颜色等,以满足您的特定要求。
  4. 效率:有效处理大量数据,并在视频处理过程中实时更新绘图。

使用下面的示例生成条形图:

import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")
cap = cv2.VideoCapture("Path/to/video/file.mp4")
out = cv2.VideoWriter("bar_plot.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(type="bar", writer=out, im0_shape=(w, h), view_img=True)

while cap.isOpened():
    success, frame = cap.read()
    if success:
        results = model.track(frame, persist=True)
        clswise_count = {
            model.names[int(cls)]: boxes.size(0)
            for cls, boxes in zip(results[0].boxes.cls.tolist(), results[0].boxes.xyxy)
        }
        analytics.update_bar(clswise_count)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

要了解更多信息,请访问指南中的条形图部分。

为什么要在数据可视化项目中使用Ultralytics YOLOv8 创建饼图?

Ultralytics YOLOv8 是创建饼图的最佳选择,因为

  1. 与对象检测集成:直接将对象检测结果整合到饼图中,以便立即获得洞察力。
  2. 用户友好的应用程序接口:只需最少的代码即可轻松设置和使用。
  3. 可定制:颜色、标签等多种定制选项。
  4. 实时更新:实时处理和可视化数据,是视频分析项目的理想选择。

这里有一个简单的例子:

import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")
cap = cv2.VideoCapture("Path/to/video/file.mp4")
out = cv2.VideoWriter("pie_chart.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(type="pie", writer=out, im0_shape=(w, h), view_img=True)

while cap.isOpened():
    success, frame = cap.read()
    if success:
        results = model.track(frame, persist=True)
        clswise_count = {
            model.names[int(cls)]: boxes.size(0)
            for cls, boxes in zip(results[0].boxes.cls.tolist(), results[0].boxes.xyxy)
        }
        analytics.update_pie(clswise_count)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

有关详细信息,请参阅指南中的饼图部分。

Ultralytics YOLOv8 可用于跟踪物体和动态更新可视化效果吗?

是的,Ultralytics YOLOv8 可用于跟踪对象并动态更新可视化效果。它支持实时跟踪多个对象,并能根据跟踪对象的数据更新各种可视化效果,如折线图、条形图和饼图。

跟踪和更新折线图的示例:

import cv2

from ultralytics import YOLO, solutions

model = YOLO("yolov8s.pt")
cap = cv2.VideoCapture("Path/to/video/file.mp4")
out = cv2.VideoWriter("line_plot.avi", cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

analytics = solutions.Analytics(type="line", writer=out, im0_shape=(w, h), view_img=True)

while cap.isOpened():
    success, frame = cap.read()
    if success:
        results = model.track(frame, persist=True)
        total_counts = sum([1 for box in results[0].boxes.xyxy])
        analytics.update_line(frame_count, total_counts)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

要了解完整的功能,请参阅 "跟踪"部分。

Ultralytics YOLOv8 与 OpenCV 和TensorFlow 等其他对象检测解决方案有何不同?

Ultralytics YOLOv8 从 OpenCV 和TensorFlow 等其他物体检测解决方案中脱颖而出,原因是多方面的:

  1. 最先进的准确性:YOLOv8 在物体检测、分割和分类任务中提供了卓越的准确性。
  2. 易于使用:用户友好的应用程序接口允许快速实施和集成,无需大量编码。
  3. 实时性能:针对高速推理进行了优化,适合实时应用。
  4. 应用多样:支持多种任务,包括多目标跟踪、自定义模型训练以及导出为不同格式,如ONNX 、TensorRT 和CoreML 。
  5. 全面的文档:广泛的文档博客资源可指导用户完成每个步骤。

有关更详细的比较和使用案例,请浏览我们的Ultralytics 博客



创建于 2024-05-23,更新于 2024-07-05
作者:glenn-jocher(4)、IvorZhu331(1)、RizwanMunawar(3)

评论