在之前的一篇博客 —— 将一维时间序列转化成二维图片中,我翻译了一篇文章,说的是将一个时间序列信号转换成二维图片:

img

然后在文章的最后发了一个 Github 代码,这个代码是原文作者的代码,有人反应代码不能跑起来。

这里我使用 Python 的一个第三方库 pyts,参考官方文档,改写了一下。测试了一下,可以在 Pyhon3.7 上成功运行。官方上说明的是 Python 版本应该不小于 3.5,代码已经上传至 GitHub.

1/ 安装 pyts 库

打开命令行,使用 pip 命令安装:pip install pyts

2/ 准备一维时间序列

我使用 MATLAB 生成了一个 sin x 的时间序列图,plot 出来是这样的:

在这里插入图片描述

总共有 512 个点,也就是最大能够生成 512 × 512 512\times 512 512×512 的图片。

要把生成的图片保存为 .csv 文件:

在这里插入图片描述

3/ 转换成图片

接下来就是简单地转换成二维图片了,先贴代码吧,或者可以在我的 GitHub 上下载,里面有批量处理和保存 GAF 图片的代码:

使用新版本的 pyts,版本如下,这也是目前 GitHub 里面版本的代码:

# Author: strongnine (WeChat: strongnine)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import image
from pyts.image import GramianAngularField

sin_data = np.loadtxt('./data/sinx.csv', delimiter=",", skiprows=0).reshape(1, -1)  # 加载数据 (load the source data)
image_size = 28  # 生成的 GAF 图片的大小 (the size of each GAF image)

# `method` 的可选参数有:`summation` and `difference`
# The optional parameters of argument `method`: `summation` and `difference`
gasf = GramianAngularField(image_size=image_size, method='summation')
sin_gasf = gasf.fit_transform(sin_data)

gadf = GramianAngularField(image_size=image_size, method='difference')
sin_gadf = gadf.fit_transform(sin_data)
imges = [sin_gasf[0], sin_gadf[0]]
titles = ['Summation', 'Difference']

# 两种方法的可视化差异对比
# Comparison of two different methods
fig, axs = plt.subplots(1, 2, constrained_layout=True)
for img, title, ax in zip(imges, titles, axs):
    ax.imshow(img)
    ax.set_title(title)
fig.suptitle('GramianAngularField', y=0.94, fontsize=16)
plt.margins(0, 0)
plt.savefig("./GramianAngularField.pdf", pad_inches=0)
plt.show()

image.imsave("./images/GAF_of_Sin.png", sin_gasf[0])  # 保存图片 (save image)
np.savetxt("./images/GAF_of_Sin.csv", sin_gasf[0], delimiter=',')  # 保存数据为 csv 文件

运行,出来的效果是这样的:

在这里插入图片描述

文中的 .csv 文件和代码都放在我的仓库中,如果对你有帮助,可以在 GitHub 中给我个 Star,这会是对我的一份鼓励与肯定!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐