3

I have a 2D array of spectrogram data which I am scaling with scikit-image for display in a web browser. I would like to scale the array logarithmically in the y-axis."

I can plot the data logarithmically in the y-axis using Matplotlib, but I want access to the 2D array representation of this newly scaled image, but Matplotlib only provides the original, unscaled array. Scikit-image scales 2D arrays linearly, but not logarithmically.

# 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)
anchoress
  • 113
  • 7
  • Why can't you just apply log on this array to get the desired values? Why extract the data from the image? Also, Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Sheldore Jun 27 '19 at 22:41

1 Answers1

1

Let's start with some example data:

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)');

Here is a graph with log(y) as vertical axis. The sampling along y is then non uniform (the data are unchanged, they are only drawn on a deformed grid):

graph after

In order to get deformed data on a regular grid, an interpolation is performed between log(y) and a new regular y grid:

# 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

Now, the grid is regular but the data are deformed, new_z_grid can be exported as an image.

xdze2
  • 3,986
  • 2
  • 12
  • 29