forked from despoisj/DeepAudioClassification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sliceSpectrogram.py
43 lines (35 loc) · 1.41 KB
/
sliceSpectrogram.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Import Pillow:
from PIL import Image
import os.path
from config import spectrogramsPath, slicesPath
#Slices all spectrograms
def createSlicesFromSpectrograms(desiredSize, desiredHeight):
for filename in os.listdir(spectrogramsPath):
if filename.endswith(".png"):
sliceSpectrogram(filename,desiredSize, desiredHeight)
#Creates slices from spectrogram
#TODO Improvement - Make sure we don't miss the end of the song
def sliceSpectrogram(filename, desiredSize, desiredHeight):
genre = filename.split("_")[0] #Ex. Dubstep_19.png
# Load the full spectrogram
img = Image.open(spectrogramsPath+filename)
#Compute approximate number of 128x128 samples
width, height = img.size
nbSamples = int(width/desiredSize)
width - desiredSize
#Create path if not existing
slicePath = slicesPath+"{}/".format(genre);
if not os.path.exists(os.path.dirname(slicePath)):
try:
os.makedirs(os.path.dirname(slicePath))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
#For each sample
for i in range(nbSamples):
print "Creating slice: ", (i+1), "/", nbSamples, "for", filename
#Extract and save 128x128 sample
startPixel = i*desiredSize
#imgTmp = img.crop((startPixel, 1, startPixel + desiredSize, desiredSize + 1))
imgTmp = img.crop((startPixel, 1, startPixel + desiredSize, desiredHeight+1))
imgTmp.save(slicesPath+"{}/{}_{}.png".format(genre,filename[:-4],str(i).zfill(5)))