python - 如何更改图像大小以允许更长的音频(wav 到 png)
问题描述
想知道是否有人可以帮助我做一些简单的事情。我正在运行一个将 WAV 文件转换为 PNG 的脚本,我遇到的问题是我无法加载超过 1 秒的 WAV 文件。
我需要更改 imageSize = math.sqrt(44100) 以增加允许的图像大小,但我不确定如何去做。我想加载一个 60 秒的 WAV 文件。
我试过 math.sqrt(44100*60) 但我仍然得到一个 55KB 的输出 PNG。(60秒的音频文件为5MB)代码:
from PIL import Image
import wave, struct, sys, math
##
# Collect input
##
if sys.argv[1][-4:] != '.wav':
sys.exit("First argument should be a .wav file")
if sys.argv[2][-4:] != '.png':
sys.exit("Second argument should be a .png file")
##
# Conversion:
##
# Wave file needs to be 16 bit mono
waveFile = wave.open(sys.argv[1], 'r')
if waveFile.getnchannels() != 1:
sys.exit("ERROR: The wave file should be single channel (mono)")
if waveFile.getframerate() != 44100:
sys.exit("ERROR: The samplerate should be 44,100")
imageRgbArray = list()
waveLength = waveFile.getnframes()
# Create the image size (based on the length)
imageSize = math.sqrt(44100)
# Loop through the wave file
for i in range(0, 44100):
# Try to read frame, if not possible fill with 0x0
try:
waveData = waveFile.readframes(1)
data = struct.unpack("<h", waveData) # This loads the wave bit
convertedData = int(data[0]) + 32768 # This adds 16bit/2 (=32768) to the data
except:
convertedData = 0
pass
# This converts the number into a hex value.
convertedDataHex = hex(convertedData)
# convert the value to a string and strips first two characters
hexString = str(convertedDataHex)[2:]
# Check how much the string should be prefixed to get the color hex length (= 6 char)
count = 6 - len(hexString)
# Prefix with a zero
while (count > 0):
hexString = "0" + hexString
count -= 1
# Convert into RGB value
rgbData = tuple(int(hexString[i:i + 6 // 3], 16) for i in range(0, 6, 6 // 3)) # Convert to RGB data
# Add the RGB value to the image array
imageRgbArray.append(rgbData)
# Create new image
im = Image.new('RGB', (int(imageSize), int(imageSize)))
# Add image data
im.putdata(imageRgbArray)
# Save image
im.save(sys.argv[2])
完整的项目(不是我的): https ://github.com/bobvanluijt/audio-convolutional-neural-network
解决方案
我通过更改这几行来让它工作,sqrt 的问题是它给出了浮点数并且向下舍入,所以图像没有足够的像素,我们可以通过使用天花板函数来防止这种情况。
...
waveLength = waveFile.getnframes()
# Create the image size (based on the length)
imageSize = math.ceil(math.sqrt(waveLength))
# Loop through the wave file
for i in range(waveLength):
...
这种方法的一个好处是我们不再受限于给定比特率的样本,因此您可以删除。
if waveFile.getframerate() != 44100:
sys.exit("ERROR: The samplerate should be 44,100")
推荐阅读
- amazon-web-services - 是否有与 www.example.com 等效的 S3 存储桶名称?
- amazon-web-services - 适用于 JavaScript CloudWatch Logs 的 AWS 开发工具包 - GetLogEventsCommand 未获取日志,可能是由于日志流大小问题?
- list - 在嵌套列表中使用 Set 删除重复数据 (Dart)
- modbus - Pymodbus 读取保持和输入寄存器:IllegalAddress
- reactjs - React Material UI 折叠多个重新渲染
- django - 如何在 OAuth 页面上自动检查 Google 批准的范围?
- java - 使用 CSVWriter 编写字符串数组 - 有些带引号,有些不带
- macos-big-sur - AXObserverAddNotification 在 Big Sur OSX 11.5 中失败
- javascript - 通过javascript激活href
- javascript - 从数组中获取项目并将其删除,直到 Discord JS bot 的数组为空