跳至内容

在终端中查看推理结果

终端中图像的 Sixel 示例

图片来自libsixel网站。

动机

当连接到远程机器时,通常无法实现图像结果的可视化,或者需要将数据移动到带有图形用户界面的本地设备上。VSCode 集成终端可直接渲染图像。下面简要演示如何将其与 ultralytics预测结果.

警告

仅与 Linux 和 MacOS 兼容。检查 VSCode 知识库检查 问题状态文献资料 以获取有关 Windows 支持在终端中使用 sixel.

使用集成终端查看图像的 VSCode 兼容协议有 sixeliTerm.本指南将演示如何使用 sixel 协议。

过程

  1. 首先,您必须启用设置 terminal.integrated.enableImagesterminal.integrated.gpuAcceleration 在 VSCode 中。

    "terminal.integrated.gpuAcceleration": "auto" # "auto" is default, can also use "on"
    "terminal.integrated.enableImages": false
    

VSCode 启用终端图像设置

  1. 安装 python-sixel 库。这是一个 分叉PySixel 该图书馆已不再维护。

    pip install sixel
    
  2. 导入相关库

    import io
    
    import cv2 as cv
    
    from ultralytics import YOLO
    from sixel import SixelWriter
    
  3. 加载模型并执行推理,然后绘制结果并存储在变量中。有关推理参数和处理结果的更多信息,请参阅预测模式页面。

    from ultralytics import YOLO
    
    # Load a model
    model = YOLO("yolov8n.pt")
    
    # Run inference on an image
    results = model.predict(source="ultralytics/assets/bus.jpg")
    
    # Plot inference results
    plot = results[0].plot() #(1)!
    
    1. 请参阅绘图方法参数,了解可能使用的参数。
  4. 现在,使用 OpenCV 将 numpy.ndarraybytes 数据。然后使用 io.BytesIO 来制作一个 "类文件 "对象。

    # Results image as bytes
    im_bytes = cv.imencode(
        ".png", #(1)!
        plot,
        )[1].tobytes() #(2)!
    
    # Image bytes as a file-like object
    mem_file = io.BytesIO(im_bytes)
    
    1. 也可以使用其他图像扩展名。
    2. 只有位于索引 1 需要返回。
  5. 创建一个 SixelWriter 实例,然后使用 .draw() 方法在终端中绘制图像。

    # Create sixel writer object
    w = SixelWriter()
    
    # Draw the sixel image in the terminal
    w.draw(mem_file)
    

推理结果示例

在终端中查看图像

危险

本示例尚未经过与视频或 GIF 动画帧一起使用的测试。请自行承担风险。

完整代码示例

import io

import cv2 as cv

from ultralytics import YOLO
from sixel import SixelWriter

# Load a model
model = YOLO("yolov8n.pt")

# Run inference on an image
results = model.predict(source="ultralytics/assets/bus.jpg")

# Plot inference results
plot = results[0].plot() #(3)!

# Results image as bytes
im_bytes = cv.imencode(
    ".png", #(1)!
    plot,
    )[1].tobytes() #(2)!

mem_file = io.BytesIO(im_bytes)
w = SixelWriter()
w.draw(mem_file)
  1. 也可以使用其他图像扩展名。
  2. 只有位于索引 1 需要返回。
  3. 请参阅绘图方法参数,了解可能使用的参数。

提示

您可能需要使用 clear 以 "擦除 "终端中的图像视图。



创建于 2024-03-09,更新于 2024-04-27
作者:glenn-jocher(1),Burhan-Q(1)

评论