【CV】使用 matplotlib 画统计图,并用 OpenCV 显示静图和动图

1. 效果

静图


动图

2.思路

  • 准备数据
  • 使用 pyplot 画统计图
  • 图片写入流,流转图(numpy)
  • matplotlib 颜色 RGB 转 OpenCV 颜色 BRG

4. 静图

代码过程有注释,很简单的实现。注意 matplotlib RGB 转 OpenCV BGR image = image[:, :, ::-1] ,否则颜色不一致。

python 复制代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""
@Create  :   2024/01/15 16:22:44
@Author  :   Yuan Mingzhuo
"""

import cv2
import numpy as np
import math
import random

# 统计图
import io
from PIL import Image
import matplotlib.pyplot as plt


# 尺寸: 960x480
plt.figure(figsize=(9.6, 4.8))


def draw_charts():
    """
    画图
    """
    # 数据
    values = [random.random() for i in range(150)]
    # 清空
    plt.clf()
    # 线条
    plt.plot(values, linewidth=1, color="deepskyblue")
    plt.axis((0, 200, 0, 1))
    plt.axhline(y=(sum(values) / len(values)), linewidth=1, color="r")
    # 图写入流
    buffer = io.BytesIO()
    plt.savefig(buffer)
    # 流转图片
    image = Image.open(buffer)
    image = np.asarray(image)
    image = image[:, :, :3]
    # matplotlib RGB 转 OpenCV BGR
    image = image[:, :, ::-1]
    cv2.imwrite("test.jpg", image)

if __name__ == "__main__":
    draw_charts()

5. 动图

思路,更新数据时,重新绘制统计图。

  • x 轴不变,数据集 values 保持 x 轴的数量即可,自行实现;
  • x 轴变化,数据集 values 的数量变化而变化;

代码过程有注释,很简单的实现。注意 matplotlib RGB 转 OpenCV BGR image = image[:, :, ::-1] ,否则颜色不一致。

python 复制代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""
@Create  :   2024/01/15 16:22:44
@Author  :   Yuan Mingzhuo
"""

import cv2
import numpy as np
import math
import random

# 统计图
import io
from PIL import Image
import matplotlib.pyplot as plt


# 尺寸: 960x480
plt.figure(figsize=(9.6, 4.8))


def draw_chart(values):
    """
    画图
    """
    buffer = io.BytesIO()
    # 清空
    plt.clf()
    plt.plot(values, linewidth=1, color="deepskyblue")
    axis_x = math.ceil(len(values) / 100) * 100
    plt.axis((0, axis_x, 0, 200))
    plt.axhline(y=(sum(values) / len(values)), linewidth=1, color="r")
    plt.savefig(buffer)
    # 获取图
    image = Image.open(buffer)
    image = np.asarray(image)
    image = image[:, :, :3]
    # matplotlib RGB 转 OpenCV BGR
    image = image[:, :, ::-1]
    # print(image.shape)
    # cv2.imwrite("test.jpg", image)
    return image

if __name__ == "__main__":
    # 数据
    values = []
    for i in range(1800):
        # 更新数据
        values.append(random.random() * 180)
        # 重新画图
        image = draw_chart(values)
        # 显示
        cv2.imshow("test", image)
        cv2.waitKey(100)

6. 多图

效果

代码

python 复制代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""
@Create  :   2024/01/15 16:22:44
@Author  :   Yuan Mingzhuo
"""

import cv2
import numpy as np
import math
import random

# 统计图
import io
from PIL import Image
import matplotlib.pyplot as plt


# 尺寸: 960x480
plt.figure(figsize=(9.6, 4.8))


def draw_charts():
    """
    画图
    """
    # 数据
    values_a = [random.random() for i in range(150)]
    values_b = [random.random() for i in range(150)]
    values = [values_a, values_b]
    # 清空
    plt.clf()
    # 线条
    for value in values:
        plt.plot(value, linewidth=1)
    # 坐标轴
    plt.axis((0, 200, 0, 1))
    # 辅助线
    plt.axhline(y=0.5, linewidth=1, color="r")
    # 图写入流
    buffer = io.BytesIO()
    plt.savefig(buffer)
    # 流转图片
    image = Image.open(buffer)
    image = np.asarray(image)
    image = image[:, :, :3]
    # matplotlib RGB 转 OpenCV BGR
    image = image[:, :, ::-1]
    cv2.imwrite("test.jpg", image)
  

if __name__ == "__main__":
    draw_charts()

7.应用

视觉计算时,可直接显示变化过程,减少先保存数据再绘制图的过程

相关推荐
图特摩斯科技7 小时前
本体智能应用案例实践分享:汽车零部件库存优化与召回应急保障
人工智能·汽车·palantir·ontology·ontoflow·ontoos
专业工业电源打工人7 小时前
F0505S-2WR3 适配优选 钡特电源 DF2-05S05LS|2W 隔离 DC-DC 模块电源5V转5V硬件选型参数规格解析
大数据·网络·人工智能
a1117767 小时前
三色软糖坠落玻璃池 THreeJS kimi
前端·人工智能·threejs
xian_wwq8 小时前
【学习笔记】解剖 Claude Code —— Anthropic 的 Harness 参考实现-09/15
人工智能·笔记·学习
Black_Rock_br8 小时前
打通 PyTorch Monarch 与 ROCm:单 Controller 架构的异构算力实战
人工智能·pytorch·python·开源
其实防守也摸鱼8 小时前
Kimi K3深度测评:长文本之外的真实力
运维·开发语言·网络·人工智能·python·学习·安全
wu8587734578 小时前
从 Prompt 到 Loop:拆解 AI 工程化四范式的演进逻辑与落地边界
人工智能·ai·prompt·aigc·ai编程
爱查宝小二8 小时前
爱查宝 AIGC 检测与改写实效评测
人工智能·aigc
AI新角度8 小时前
增量测试与影响分析:只跑受变更波及的用例
人工智能
FII工业富联科技服务8 小时前
从85% AI应用覆盖到规模化运营:制造企业灯塔AI转型架构与落地方法解析
人工智能·架构·制造