Fixing Python code that visualizes audio input - python

I found some code online that visualizes audio input into a graph. I have been working on it for a while but I keep getting different errors. If anyone could find the time to have a look at it and help me to get it to work it would be much appreciated.
import struct
import wave
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
import pyaudio
SAVE = 0.0
TITLE = ''
WIDTH = 1280
HEIGHT = 720
FPS = 25.0
nFFT = 512
BUF_SIZE = 4 * nFFT
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
def animate(i, line, stream, wf, MAX_y):
# Read n*nFFT frames from stream, n > 0
N = max(stream.get_read_available() / nFFT, 1) * nFFT
data = stream.read(N)
if SAVE:
wf.writeframes(data)
# Unpack data, LRLRLR...
y = np.array(struct.unpack("%dh" % (N * CHANNELS), data)) / MAX_y
y_L = y[::2]
y_R = y[1::2]
Y_L = np.fft.fft(y_L, nFFT)
Y_R = np.fft.fft(y_R, nFFT)
# Sewing FFT of two channels together, DC part uses right channel's
Y = abs(np.hstack((Y_L[-nFFT / 2:-1], Y_R[:nFFT / 2])))
line.set_ydata(Y)
return line,
def init(line):
# This data is a clear frame for animation
line.set_ydata(np.zeros(nFFT - 1))
return line,
def main():
dpi = plt.rcParams['figure.dpi']
plt.rcParams['savefig.dpi'] = dpi
plt.rcParams["figure.figsize"] = (1.0 * WIDTH / dpi, 1.0 * HEIGHT / dpi)
fig = plt.figure()
# Frequency range
x_f = 1.0 * np.arange(-nFFT / 2 + 1, nFFT / 2) / nFFT * RATE
ax = fig.add_subplot(111, title=TITLE, xlim=(x_f[0], x_f[-1]),
ylim=(0, 2 * np.pi * nFFT ** 2 / RATE))
ax.set_yscale('symlog', linthreshy=nFFT ** 0.5)
line, = ax.plot(x_f, np.zeros(nFFT - 1))
# Change x tick labels for left channel
def change_xlabel(evt):
labels = [label.get_text().replace(u'\u2212', '')
for label in ax.get_xticklabels()]
ax.set_xticklabels(labels)
fig.canvas.mpl_disconnect(drawid)
drawid = fig.canvas.mpl_connect('draw_event', change_xlabel)
p = pyaudio.PyAudio()
# Used for normalizing signal. If use paFloat32, then it's already -1..1.
# Because of saving wave, paInt16 will be easier.
MAX_y = 2.0 ** (p.get_sample_size(FORMAT) * 8 - 1)
frames = None
wf = None
if SAVE:
frames = int(FPS * SAVE)
wf = wave.open('temp.wav', 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=BUF_SIZE)
ani = animation.FuncAnimation(
fig, animate, frames,
init_func=lambda: init(line), fargs=(line, stream, wf, MAX_y),
interval=1000.0 / FPS, blit=True
)
if SAVE:
ani.save('temp.mp4', fps=FPS)
else:
plt.show()
stream.stop_stream()
stream.close()
p.terminate()
if SAVE:
wf.close()
if __name__ == '__main__':
main()
The error is:
File "C:\Users\Tonif\Documents\computer science\sound.py", line 26,
in animate data = stream.read(N)
TypeError: integer argument expected, got float

Related

Small unpacking buffer for wave.struct

I am building a SSTV programm, that can convert 180x136 picture into the sound with the RGB component. But when I try to read data from microphone, it gives me
struct.error: unpack requires a buffer of 400 bytes
when I use only 200 bytes.
I expected the output as decoded microphone out (in short: microphone -> decode signal -> image).
I tried to use chunk*2 but it gave me same error:
struct.error: unpack requires a buffer of 800 bytes
Here is the code for decoder:
import numpy as np
import pyaudio
import wave
from tkinter import *
root = Tk()
c = Canvas(root, width=90*8, height=68*8, bg='white')
c.pack()
def pix(x, y, rr, rg, rb): # r + (r/g/b) is raw rgb because we are decoding frequency
if rr < 0:
r = 0
if rg < 0:
g = 0
if rb < 0:
b = 0
try:
r = min(255,round(rr * (255 / 1124)))
except:
r = 0
try:
g = min(255,round(rg * (255 / 1124)))
except:
g = 0
try:
b = min(255,round(rb * (255 / 1124)))
except:
b = 0
if r < 0:
r = 0
if g < 0:
g = 0
if b < 0:
b = 0
print(r,g,b)
n = hex(r).replace("0x","")
rh = (2 - len(n)) * "0" + n
n = hex(g).replace("0x", "")
gh = (2 - len(n)) * "0" + n
n = hex(b).replace("0x", "")
bh = (2 - len(n)) * "0" + n
c.create_line(x, y, x + 4, y, fill=f"#{rh}{gh}{bh}")
c.create_line(x, y+1, x + 4, y+1, fill=f"#{rh}{gh}{bh}")
c.create_line(x, y+2, x + 4, y+2, fill=f"#{rh}{gh}{bh}")
c.create_line(x, y+3, x + 4, y+3, fill=f"#{rh}{gh}{bh}")
chunk = 100
# open up a wave
wf = wave.open('input.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
# use a Blackman window
window = np.blackman(chunk)
# open stream
p = pyaudio.PyAudio()
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = RATE,
output = True)
microphone = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = RATE,
input = True)
# read some data
data = wf.readframes(chunk)
#print(len(data))
#print(chunk*swidth)
pc = 0
x = 0
e = [255,252]
totaly = 0
rrgb = [255, 255, 255] # raw rgb
# play stream and find the frequency of each chunk
while True:
data = microphone.read(chunk)
# write data out to the audio stream
stream.write(data)
indata = np.array(wave.struct.unpack("%dh"%((len(data))/swidth),data))*window#"%dh"%((len(data)-1)/swidth)
# Take the fft and square each value
fftData=abs(np.fft.rfft(indata))**2
# find the maximum
which = fftData[1:].argmax() + 1
# use quadratic interpolation around the max
if which != len(fftData)-1:
y0,y1,y2 = np.log(fftData[which-1:which+2:])
x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
# find the frequency and output it
thefreq = (which+x1)*RATE/chunk
if thefreq>3030 or totaly==540:
#print("PING!",f"The freq is %f Hz. {pc}" % (thefreq))
if pc==0:
totaly = x
pc+=4
x=0
root.update()
else:
#print(f"The freq is %f Hz. min {min(e)} max {max(e)}, {x//4}" % (thefreq), end=" ")
if x//4 % 3 == 0:
pix(x / 3, pc, rrgb[0], rrgb[1], rrgb[2]) # /0.77039274924
rrgb[0] = thefreq
#print("R")
elif x//4 % 3 == 1:
rrgb[1] = thefreq
#print("G")
elif x//4 % 3 == 2:
rrgb[2] = thefreq
#print("B")
#e.append(thefreq)
#pix()
x+=4#print("The freq is %f Hz." % (thefreq))
else:
thefreq = which*RATE/chunk
#print("The freq is %f Hz." % (thefreq))
# read some more data
data = microphone.read(chunk)
if data:
stream.write(data)
stream.close()
p.terminate()
root.mainloop()
Here is the code for encoder:
import numpy as np
# Importing Image from PIL package
from PIL import Image
# creating a image object
im = Image.open(r"original.bmp")
px = im.load()
arx = []
art = []
pix = ()
pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
print(pixels)
for ypos in range(0,136):
for xpos in range(0,180):
pix = pixels[ypos][xpos]
#gray = ((pix[0])+(pix[1])+(pix[2]))/3
rgb = (pix[0],pix[1],pix[2])
arx.append(rgb)
arx.append(406)
art.append(arx)
rate = 44100 # samples per second
T = 3 # sample duration (seconds)
slowdown = int(input("Speed in Hz:"))
f = 100.0/slowdown # sound frequency (Hz)
print("speed multiplier is",slowdown)
encoding = "ansi"
total = []
xpos2 = 0
c = 0
for ypos in art:
for xpos in ypos:
#print(xpos)
t = np.linspace(0, 0.01, (slowdown), endpoint=False)
if xpos==406:
sig = np.sin(2 * np.pi * f * 500 * t)
total.extend(sig)
sig = np.sin(2 * np.pi * f * 700 * t)
total.extend(sig)
continue
sig = np.sin(2 * np.pi * f * xpos[0] * t)
total.extend(sig)
sig = np.sin(2 * np.pi * f * xpos[1] * t)
total.extend(sig)
sig = np.sin(2 * np.pi * f * xpos[2] * t)
total.extend(sig)
print(xpos)
sig = np.sin(2 * np.pi * f * 300 * t)
break
import wavio
wavio.write("input.wav", total, rate, sampwidth=2)
input("done, saved as \'input.wav\'")

Are there any obvious errors why the S measurements won't switch

In my lab, we're trying to automate a keysight VNA to take measurements of the microwave cavity we're using. We're trying to get readings for S21, S22, and S11. However, when we run the program, the switch from S21 to S11 isn't happening. My job is to debug this, but I can't see any obvious errors. This is the snippet of the code that controls the measurement switch, and I was wondering if you all could take a look and give suggestions/make note of errors. There's also. library that we wrote for this particular instrument, so the error could possibly be in there. Thanks!
# Sweep over vna modes
for mode in mode_list:
vnass.s21_mode()
s21_sweep = vnass.sweep(mode) # Do a sweep with these parameters
fcent = mode[0]
fspan = mode[1]
bandwidth = mode[2]
npoints = int(mode[3])
naverages = mode[4]
power = mode[5]
# Processing Starts here
freq_data = gen.get_frequency_space(fcent, fspan, npoints) # Generate list of frequencies
fig.clf()
ax = fig.add_subplot(111)
ax.set_title("ato_pos = %.1f, f = %.3f GHz" % (ato_pos, fcent / 1e9), fontsize=16)
ax.plot(freq_data / 1e9, gen.complex_to_dB(s21_sweep), "g")
ax.set_ylabel(r'$S_{21}$ [dB]')
ax.set_xlabel('Frequency [GHz]')
plt.axis('tight')
plt.draw()
plt.pause(0.1)
if list(mode_list).index(mode) == 0:
s21_data = np.transpose(s21_sweep)
else:
s21_data = np.vstack((s21_data, np.transpose(s21_sweep)[1:]))
vnass.s11_mode()
s11_sweep = vnass.sweep(mode) # Do a sweep with these parameters
if list(mode_list).index(mode) == 0:
s11_data = np.transpose(s11_sweep)
else:
s11_data = np.vstack((s11_data, np.transpose(s11_sweep)[1:]))
vnass.s22_mode()
s22_sweep = vnass.sweep(mode) # Do a sweep with these parameters
if list(mode_list).index(mode) == 0:
s22_data = np.transpose(s22_sweep)
else:
s22_data = np.vstack((s22_data, np.transpose(s22_sweep)[1:]))
#t = datetime.now(timezone('Australia/Perth')).strftime(fmt)
with h5py.File(filepath / p(exp_name + '.hdf5'), 'a') as f:
try:
if f[str(ato_pos)]:
del (f[str(ato_pos)])
except:
None
full_freq = np.linspace(mode_list[0][0] - fspan // 2, fcent + fspan // 2,
s21_data.shape[0]) # freq list in Hz
dset_s21 = f.create_dataset(str(ato_pos)+'_s21', data=s21_data, compression='gzip', compression_opts=6) # VNA dset
dset_s11 = f.create_dataset(str(ato_pos)+ '_s11', data=s11_data, compression='gzip', compression_opts=6)
dset_s22 = f.create_dataset(str(ato_pos)+ '_s22', data=s22_data, compression='gzip', compression_opts=6) # VNA dset
# VNA dset
try:
f['Freq']
except:
fdset = f.create_dataset('Freq', data=full_freq, compression='gzip', compression_opts=6)
fdset.attrs['f_start'] = mode_list[0][0] # this is from the mode map / next freq
fdset.attrs['f_final'] = fcent
fdset.attrs['vna_pow'] = power
fdset.attrs['vna_span'] = fspan
fdset.attrs['vna_pts'] = npoints
fdset.attrs['vna_ave'] = naverages
fdset.attrs['vna_rbw'] = fspan / (npoints - 1)
fdset.attrs['vna_ifb'] = bandwidth
fdset.attrs['nmodes'] = mode_list.shape[0]
#fdset.attrs['ato_voltage'] = setVoltage['x']
#fdset.attrs['ato_freq'] = setFreq['x']
fdset.attrs['ato_step'] = ato_step
fdset.attrs['total_steps'] = total_steps
dset_s21.attrs['ato_pos'] = ato_pos
#dset.attrs['temp'] = temperature
#dset.attrs['time'] = t
if idx % 5 == 0 and idx != 0:
fig1.clf()
ax1 = fig1.add_subplot(111)
mag_data_db, freq, ato_positions = ato_hdf5_parser(filepath / p(exp_name + '.hdf5'))
phi = ato_positions // ato_step
colour = ax1.imshow(mag_data_db, extent=[phi[0], phi[-1], freq[0], freq[-1]],
aspect=(0.8 * (phi[-1] - phi[0]) / (freq[-1] - freq[0])),
cmap=plt.cm.get_cmap('viridis'), origin='lower', norm=Normalize(vmin=db_min, vmax=db_max))
ax1.set_xlabel(r'Phi (Steps)')
ax1.set_ylabel(r'Frequency (GHz)')
cb = fig1.colorbar(colour, ax=ax1, fraction=0.0325, pad=0.04)
cb.set_label('$|S_{21}|$ [dB]')
cm.ScalarMappable()
plt.title(exp_name)
plt.draw()

RuntimeError ,Error opening ,System error ,when reading wav file

At first,I am a python beginner. I need to read my clean.wav(cut to 50 slices to haha0~haha49 .wav) and noise.wav ,doing a snr [5,10,15]. Then output the before and after's waveform and Spectrogram. But,teriminal always tell me RuntimeError: Error opening 'D:\python\pythonnoisy\add_white\haha0_white_snr5.wav': System error. However, I can see this file in my folder.
import os
import re
import sys
import wave
import librosa
import matplotlib
import numpy as np
import pylab as pl
import soundfile as sf
import matplotlib.pyplot as plt
from scipy.fftpack import fft
wavedir = r"D:\python"
noisydir = wavedir+"\\pythonnoisy"
noisedir = wavedir+"\\pythonnoise"
cleandir = wavedir+"\\pythonclean"
def add_noise(noisydir, noisedir, cleandir, snr): # noisy
noisewav = "white.wav"
noise, fs = sf.read(noisedir+"\\"+noisewav) # 讀取白雜訊.wav
noisy_splitdir = noisydir+"\\"+"add_"+noisewav[:-4]+"\\"
# 迴圈取原始wav檔資料夾裡所有檔案
for cleanwav in os.listdir(cleandir):
clean, Fs = sf.read(cleandir+"\\"+cleanwav) # 讀取原始.wav檔
# 取樣頻率:原始音檔==白雜訊&&時長:原始音檔<白雜訊
if fs == Fs and len(clean) <= len(noise):
cleanenergy = np.sum(np.power(clean, 2)) # 原始音檔Power(=振幅^2)
# 1<隨機生成長度<noise長-clean長+1
ind = np.random.randint(1, len(noise) - len(clean) + 1)
noiselen = noise[ind:len(clean) + ind]
noiseenergy = np.sum(np.power(noiselen, 2)) # 白雜訊Power
ratio2 = np.sqrt(
(cleanenergy / noiseenergy) / (np.power(10, snr * 0.1)))
noisyAudio = clean + noiselen * ratio2 # 混音振幅
# 混音路徑+檔名
noisywavname = noisy_splitdir + \
cleanwav[:-4]+"_"+noisewav[:-4]+"_snr"+str(snr)+".wav"
sf.write(noisywavname, noisyAudio, 44100) # 生成混音.wav
def draw_clean(cleandir, j):
f = wave.open(
r"D:\python\pythonclean\haha" + str(j) + ".wav", "rb")
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
str_data = f.readframes(nframes)
f.close()
wave_data = np.fromstring(str_data, dtype=np.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
time = np.arange(0, nframes) * (1.0 / framerate)
plt.subplot(4, 2, 7)
plt.plot(time, wave_data[0])
plt.xlabel("time(s)")
plt.subplot(4, 2, 8)
plt.specgram(wave_data[0], Fs=framerate)
plt.xlabel("time(s)")
def draw_noisy(noisydir, j):
noisydirr = noisydir+"\\add_white\\haha"
for k in range(5, 20, 5):
f = wave.open(r"D:\python\pythonnoisy\add_white\haha" +
str(j)+"_white_snr"+str(k)+".wav", "rb")
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
str_data = f.readframes(nframes)
wave_data = np.fromstring(str_data, dtype=np.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
time = np.arange(0, nframes) * (1.0 / framerate)
plt.subplot(4, 2, k/5*2-1)
plt.plot(time, wave_data[0])
plt.subplot(4, 2, k/5*2)
plt.specgram(wave_data[0], Fs=framerate)
wavedir = r"D:\python"
noisydir = wavedir+"\\pythonnoisy"
noisedir = wavedir+"\\pythonnoise"
cleandir = wavedir+"\\pythonclean"
level = [5, 10, 15]
for snr in level:
add_noise(noisydir, noisedir, cleandir, snr)
for j in range(0, 51):
draw_clean(cleandir, j)
draw_noisy(noisydir, j)
picture = noisydir+"\picture\hahawhite"+str(j)+".png"
plt.savefig(picture)
plt.close()
file location
terminal

Why is a 1D k-means clustering slower than a k-means initialized mixture model fit?

My timing shows that k-means consistently loses out on timing, compared to a mixture model, initialized using k-means.
What's the explanation for this? Is the GMM using a different k-means algorithm? Am I misunderstanding how it works? Does it use a differently sized dataset (smaller than I'm drawing from?).
import sklearn.cluster
import sklearn.mixture
import numpy as np
import time
import matplotlib.pyplot as plt
k = 3
N = 100
def clust():
m = sklearn.cluster.KMeans(n_clusters = k)
m.fit(X.reshape(-1, 1))
return m.cluster_centers_
def fit():
m = sklearn.mixture.GaussianMixture(n_components = k, init_params = "kmeans")
m.fit(X.reshape(-1, 1))
return m.means_
duration_clust = []
duration_fit = []
ctrs_clust = []
ctrs_fit = []
for i in range(N):
_1 = np.random.normal(0.25, 0.15, 50)
_2 = np.random.normal(0.50, 0.15, 50)
_3 = np.random.normal(0.75, 0.15, 50)
X = np.concatenate((_1, _2, _3)).reshape(-1, 1)
ts = time.time()
c = clust()
te = time.time()
time_clust = (te - ts) * 1e3
ts = time.time()
f = fit()
te = time.time()
time_fit = (te - ts) * 1e3
duration_clust.append(time_clust)
duration_fit.append(time_fit)
ctrs_clust.append(c)
ctrs_fit.append(f)
bins0 = np.arange(0, 20, 1)
bins1 = np.linspace(0,1,30)
fig, ax = plt.subplots(nrows = 2)
ax[0].hist(duration_clust, label = "Kmeans", bins = bins0, alpha = 0.5)
ax[0].hist(duration_fit, label = "GMM with Kmeans", bins = bins0, alpha = 0.5)
ax[0].set_xlabel("duration (ms)")
ax[0].legend(loc = "upper right")
ax[1].hist(np.ravel(ctrs_clust), label = "Kmeans centers", bins = bins1, alpha = 0.5)
ax[1].hist(np.ravel(ctrs_fit), label = "GMM centers", bins = bins1, alpha = 0.5)
ax[1].set_xlabel("Center location")
ax[1].axvline([0.25], label = "Truth", color = "black")
ax[1].axvline([0.50], color = "black")
ax[1].axvline([0.75], color = "black")
ax[1].legend(loc = "upper right")
plt.tight_layout()
plt.show()

Matplotlib imshow, dynamically resample based on zoom

I'm trying to replicate the behavior of MATLAB imagesc() call in matplotlib - specifically:
- for very large images, decimate the image
- as the user zooms in, show the image with less decimation.
I've written a class that will do it, but my solution seems overly complex. Does anybody know a better way?
Thanks in advance,
Brian
answer by OP, edited out of the question:
Here's my solution:
The basic idea is:
Catch a xlim_changed or ylim_changed event
Calculate a desired stride based on image size and desired num pixels
Draw
https://github.com/flailingsquirrel/cmake_scipy_ctypes_example/blob/master/src/python/FastImshow.py
#!/usr/bin/env python
'''
Fast Plotter for Large Images - Resamples Images to a target resolution on each zoom.
Example::
sz = (10000,20000) # rows, cols
buf = np.arange(sz[0]*sz[1]).reshape(sz)
extent = (100,150,1000,2000)
fig = plt.figure()
ax = fig.add_subplot(111)
im = FastImshow(buf,extent,ax)
im.show()
plt.show()
'''
import numpy as np
import matplotlib.pyplot as plt
class FastImshow:
'''
Fast plotter for large image buffers
Example::
sz = (10000,20000) # rows, cols
buf = np.arange(sz[0]*sz[1]).reshape(sz)
extent = (100,150,1000,2000)
fig = plt.figure()
ax = fig.add_subplot(111)
im = FastImshow(buf,extent,ax)
im.show()
plt.show()
'''
def __init__(self,buf,ax,extent=None,tgt_res=512):
'''
[in] img buffer
[in] extent
[in] axis to plot on
[in] tgt_res(default=512) : target resolution
'''
self.buf = buf
self.sz = self.buf.shape
self.tgt_res = tgt_res
self.ax = ax
# Members required to account for mapping extent to buf coordinates
if extent:
self.extent = extent
else:
self.extent = [ 0, self.sz[1], 0, self.sz[0] ]
self.startx = self.extent[0]
self.starty = self.extent[2]
self.dx = self.sz[1] / (self.extent[1] - self.startx ) # extent dx
self.dy = self.sz[0] / (self.extent[3] - self.starty ) # extent dy
# end __init__
def get_strides( self,xstart=0, xend=-1, ystart=0, yend=-1, tgt_res=512 ):
'''
Get sampling strides for a given bounding region. If none is provided,
use the full buffer size
'''
# size = (rows,columns)
if xend == -1:
xend = self.sz[1]
if yend == -1:
yend = self.sz[0]
if (xend-xstart) <= self.tgt_res:
stridex = 1
else:
stridex = max(int((xend - xstart) / self.tgt_res),1)
if (yend-ystart) <= self.tgt_res:
stridey = 1
else:
stridey = max(int((yend - ystart) / self.tgt_res),1)
return stridex,stridey
# end get_strides
def ax_update(self, ax):
'''
Event handler for re-plotting on zoom
- gets bounds in img extent coordinates
- converts to buffer coordinates
- calculates appropriate strides
- sets new data in the axis
'''
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Get the range for the new area
xstart, ystart, xdelta, ydelta = ax.viewLim.bounds
xend = xstart + xdelta
yend = ystart + ydelta
xbin_start = int(self.dx * ( xstart - self.startx ))
xbin_end = int(self.dx * ( xend - self.startx ))
ybin_start = int(self.dy * ( ystart - self.starty ))
ybin_end = int(self.dy * ( yend - self.starty ))
# Update the image object with our new data and extent
im = ax.images[-1]
stridex,stridey = self.get_strides( xbin_start,xbin_end,ybin_start,ybin_end)
im.set_data( self.buf[ybin_start:ybin_end:stridey,xbin_start:xbin_end:stridex] )
im.set_extent((xstart, xend, ystart, yend))
ax.figure.canvas.draw_idle()
# end ax_update
def show(self):
'''
Initial plotter for buffer
'''
stridex, stridey = self.get_strides()
self.ax.imshow( buf[::stridex,::stridey],extent=self.extent,origin='lower',aspect='auto' )
self.ax.figure.canvas.draw_idle()
self.ax.callbacks.connect('xlim_changed', self.ax_update)
self.ax.callbacks.connect('ylim_changed', self.ax_update)
# end show
# end ImgDisplay
if __name__=="__main__":
sz = (10000,20000) # rows, cols
buf = np.arange(sz[0]*sz[1]).reshape(sz)
extent = (100,150,1000,2000)
fig = plt.figure()
ax = fig.add_subplot(111)
im = FastImshow(buf,ax,extent=extent,tgt_res=1024)
im.show()
plt.show()

Categories

Resources