Skip to content

Instantly share code, notes, and snippets.

@agar3s
Last active December 9, 2016 20:53
Show Gist options
  • Save agar3s/6170918 to your computer and use it in GitHub Desktop.
Save agar3s/6170918 to your computer and use it in GitHub Desktop.
This script creates a midi file using an image as the source of inspiration
#!/usr/bin/python
import sys
import Image
from midiutil.MidiGenerator import MidiGenerator
from midiutil.TrackGen import LoopingArray
filename = sys.argv[1]
midifilename = filename[0:filename.find('.')]+'.midi'
#load the image and get it's dimensions
im = Image.open(filename)
pix = im.load()
width, height = im.size
#one list for each color channel rgb
red = []
green = []
blue = []
last_g = 50
#go over the image pixel by pixel
for y in range(0, height):
for x in range(0, width):
r, g, b = pix[x, y]
red.append([r, g, b]) #get the notes
green.append(((g+16)/255.0, last_g/255.0)) #get the duration of each note
last_g = b+16
blue.append(b) #velocities
duration = 25
from_note = len(red)/2-duration
to_note = from_note+duration
le_red = red[from_note:to_note]
le_green = green[from_note:to_note]
le_blue = blue[from_note:to_note]
#create the midi file
midiGenerator = MidiGenerator(filename=midifilename, tempo=150)
notes = LoopingArray(le_red)
beats = LoopingArray(le_green)
velocities = LoopingArray(le_blue)
#use the midigenerator to create the track with the image's pixel data
midiGenerator.add_track(0, 0, beat=beats, notes=notes, velocities=velocities, length=duration)
midiGenerator.write()
@agar3s
Copy link
Author

agar3s commented Aug 7, 2013

Requirements

To use it just type:

python converter.py image.png 

This is the result of the week 6 of the weekly project Synesthesia (http://aweeklyproject.tumblr.com/tagged/week-6)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment