Created
July 31, 2014 13:25
-
-
Save Mikayex/d33f95a8e497707f53f1 to your computer and use it in GitHub Desktop.
Sound2Image and Image2Sound
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Encode image to sound | |
#Requirement : Python 2.5, Numpy, audiolab, PIL | |
import numpy as np | |
from scikits.audiolab import Format, Sndfile | |
import math | |
from PIL import Image | |
import sys | |
if len(sys.argv)!=2: | |
print('Syntax: input_file output_file') | |
sys.exit(1) | |
IMG=Image.open(sys.argv[1]) | |
IMGwidth=IMG.size[0] | |
IMGheight=IMG.size[1] | |
nframes=IMGheight*IMGwidth | |
data=np.zeros(nframes) | |
i=0 | |
for y in range(0, IMGheight): | |
for x in range(0, IMGwidth): | |
data[i]=IMG.getpixel((x, y)) | |
i=i+1 | |
sndData=(data/255)*2-1 | |
f=Sndfile(sys.argv[2], 'w', format=Format(), channels=1, samplerate=44100) #Samplerate may change but it is usually 44100 Hz | |
f.write_frames(sndData) | |
f.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Encode sound to image | |
#Requirement : Python 2.5, Numpy, audiolab, PIL | |
import numpy as np | |
from scikits.audiolab import Format, Sndfile | |
import math | |
from PIL import Image | |
import sys | |
if len(sys.argv)!=4: | |
print('Syntax: input_file image_width output_file') | |
sys.exit(1) | |
f=Sndfile(sys.argv[1], 'r') | |
data=f.read_frames(f.nframes) | |
#Generate image | |
IMGwidth=int(sys.argv[2]) | |
IMGheight=math.ceil(f.nframes/IMGwidth) | |
IMG=Image.new('L', (IMGwidth, IMGheight), 127) | |
pixels=((data+1)/2)*255 | |
x=0 | |
y=0 | |
for i in range(0, len(pixels)): | |
if x>=IMGwidth: | |
x=0 | |
y=y+1 | |
if y>=IMGheight: | |
break | |
IMG.putpixel((x, y), int(pixels[i])) | |
x=x+1 | |
IMG.save(sys.argv[3]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment