【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.应用

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

相关推荐
mit6.82410 小时前
[手机AI开发sdk] 模型冻结&解冻.pb | `aidlite`加速AI模型
人工智能·智能手机
落798.10 小时前
基于 GitCode 云端环境的 CANN ops-math 算子库深度测评:Ascend NPU 上的数学引擎解析
人工智能·gitcode
九河云10 小时前
华为云ECS与Flexus云服务器X实例:差异解析与选型指南
大数据·运维·服务器·网络·人工智能·华为云
AI优秘企业大脑10 小时前
如何提升自动化业务流程的效率?
大数据·人工智能
这张生成的图像能检测吗10 小时前
(论文速读)视觉语言模型的无遗忘学习
人工智能·深度学习·计算机视觉·clip·持续学习·灾难性遗忘
杰克逊的日记10 小时前
LLM(大语言模型)
人工智能·语言模型·自然语言处理
夏文强10 小时前
HarmonyOS开发-系统AI视觉能力-图片识别
人工智能·华为·harmonyos
胡耀超10 小时前
通往AGI的模块化路径:一个可能的技术架构(同时解答微调与RAG之争)
人工智能·python·ai·架构·大模型·微调·agi
说私域10 小时前
定制开发AI智能名片S2B2C商城小程序的发展与整合资源策略研究
人工智能·小程序
落羽的落羽10 小时前
【C++】现代C++的新特性constexpr,及其在C++14、C++17、C++20中的进化
linux·c++·人工智能·学习·机器学习·c++20·c++40周年