使用Python对数缩放2D数组

时间:2019-06-27 21:25:05

标签: python image numpy matplotlib scikit-image

我有一个二维频谱图数据数组,我正在用scikit-image缩放以显示在Web浏览器中。我想在y轴上对数地缩放数组。”

我可以使用Matplotlib在y轴上对数绘制数据,但是我想访问此新缩放图像的2D数组表示形式,但是Matplotlib仅提供原始的未缩放数组。 Scikit图像可线性缩放二维数组,但不能对数缩放。

# plot a log-scaled z
w, h = z.shape
fig, ax = plt.subplots()
ax.set_yscale('symlog')
mesh = ax.pcolormesh(np.arange(h+1), np.arange(w+1), z)
# get the array of z
logimg = mesh.get_array().reshape(mesh._meshHeight, mesh._meshWidth)

1 个答案:

答案 0 :(得分:0)

让我们从一些示例数据开始:

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pylab as plt

# some 2D example data
x, y = np.arange(30)+1, np.arange(20)+1
x_grid, y_grid = np.meshgrid(x, y)
z_grid = np.cos(2*np.pi*x_grid/10) + np.sin(2*np.pi*y_grid/4)

# Graph 1
plt.pcolormesh(x, np.log(y), z_grid);
plt.xlabel('x'); plt.ylabel('log(y) (non regular spacing)');

这里是以log(y)为纵轴的图。这样,沿y的采样就变得不均匀(数据不变,它们仅在变形的网格上绘制):

graph after

为了在常规网格上获取变形数据,在log(y)和新的常规y网格之间执行插值:

# Interpolation of the transformed data on a regular new y axis
ylog_interpolation = interp1d(np.log(y), z_grid.T)
new_y = np.linspace(min(np.log(y)), max(np.log(y)), len(y))
new_z_grid = ylog_interpolation(new_y).T

# axis
plt.pcolormesh(x, new_y, new_z_grid);
plt.xlabel('x'); plt.ylabel('new y (regular spacing)');

after interolation

现在,网格是规则的,但是数据变形了,new_z_grid可以作为图像导出。