Python 从figure matplotlib返回blit-able numpy数组
我正试图找到一种方法来返回一个可以在pygame屏幕上显示的numpy数组。以下是迄今为止的代码:Python 从figure matplotlib返回blit-able numpy数组,python,matplotlib,pygame,Python,Matplotlib,Pygame,我正试图找到一种方法来返回一个可以在pygame屏幕上显示的numpy数组。以下是迄今为止的代码: 这是该图的示例图像: 我希望能够使用这样的图形不断更新PyGame窗口。您可以使用来操纵PyGame表面上的单个像素 下面是一个基于pyaudio输入捕获的简单示例: import pygame import pyaudio import struct import numpy as np import samplerate # initialise audio capture CHUNK
这是该图的示例图像: 我希望能够使用这样的图形不断更新PyGame窗口。您可以使用来操纵PyGame表面上的单个像素 下面是一个基于
pyaudio
输入捕获的简单示例:
import pygame
import pyaudio
import struct
import numpy as np
import samplerate
# initialise audio capture
CHUNK = 4000
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 42000
p = pyaudio.PyAudio()
chosen_device_index = -1
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input_device_index=chosen_device_index,
input=True,
output=False,
frames_per_buffer=CHUNK,
)
pygame.init()
width = 320
height = 240
clock = pygame.time.Clock()
screen = pygame.display.set_mode([width, height])
pygame.display.set_caption("Audio Input")
pixels = pygame.PixelArray(screen)
done = False
while not done:
# Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# capture data
data = struct.unpack(str(CHUNK) + "h", stream.read(CHUNK))
samples = samplerate.resample(data, width / len(data))
# need to rescale from 0 (top) to height (bottom)
norm = ((samples / 2 ** 15) + 1) / 2 # normalise to 0 - 1
rescaled = (1 - norm) * height
screen.fill(pygame.Color("black"))
for x in range(len(samples)):
y = int(rescaled[x])
pixels[x][y] = pygame.Color("green")
pygame.display.update()
clock.tick(60)
pygame.quit()
p.terminate()
这将显示如下内容:
捕获的块将重新采样以匹配窗口的宽度。根据,这是对音频重新采样的最佳方法,而不是基本的线性插值
然后将信号的幅度缩放到窗口高度。
将屏幕尺寸更改为800x400如下所示:
您可能希望通过修改垂直缩放来调整增益
编辑:要消除间隙,请使用pygame.draw.aaline(…)
在连续点之间绘制抗锯齿线。例如,用黑色填充屏幕后:
# draw lines between each point
for x in range(1, len(samples)):
y0 = int(rescaled[x-1])
y1 = int(rescaled[x])
pygame.draw.aaline(screen, pygame.Color("turquoise"), (x-1, y0), (x, y1))
然后,您将看到如下内容:
这是否回答了您的问题?谢谢这工作得相当好-我将不得不玩它一些更多!不客气,如果有什么需要澄清的,请告诉我
# draw lines between each point
for x in range(1, len(samples)):
y0 = int(rescaled[x-1])
y1 = int(rescaled[x])
pygame.draw.aaline(screen, pygame.Color("turquoise"), (x-1, y0), (x, y1))