예제 #1
0
def to_midi(events_):
    midistream = MIDIFile(1)

    track = 0
    time = 0
    channel = 0
    volume = 100

    midistream.addTrackName(track, time, "Track")
    midistream.addTempo(track, time, 60)

    temp = []
    for index, event_ in enumerate(events_):
        if event_[0][0] == 144:  #key down
            temp = event_
        elif event_[0][0] == 128:  #key up
            duration = (event_[1] - temp[1]) / 1000
            pitch = event_[0][1]
            time = temp[1] / 1000
            midistream.addNote(track, channel, pitch, time, duration, volume)

    # And write it to disk.
    binfile = open("temp/user_output.mid", 'wb')
    midistream.writeFile(binfile)
    print(midistream)
    binfile.close()
예제 #2
0
def generate_midi(notes):
    # Create the MIDIFile Object
    MyMIDI = MIDIFile(1)

    # Add track name and tempo. The first argument to addTrackName and
    # addTempo is the time to write the event.
    track = 0
    time = 0
    MyMIDI.addTrackName(track, time, "Sample Track")
    MyMIDI.addTempo(track, time, 120)

    # Add a note. addNote expects the following information:
    channel = 0
    # pitch = 60
    # duration = 1
    volume = 100

    # Now add the note.
    for note in notes:
        MyMIDI.addNote(track, channel, note.pitch, time, note.duration, volume)
        time += note.duration

    # And write it to disk.
    binfile = open("./server_files/output.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
예제 #3
0
    def save_midi(self, instrument):
        # Create the MIDIFile Object with 1 track
        self.MIDIFile = MIDIFile(len(self.tracks))
        #self.MIDIFile.addProgramChange(0, 0, 0, instrument)

        for i, note_list in enumerate(self.tracks):

            # Tracks are numbered from zero. Times are measured in beats.
            track = i
            time = 0

            # Add track name, tempo and instrument change event
            self.MIDIFile.addTrackName(track, time, "Track %s" % i)
            self.MIDIFile.addTempo(track, time, self.tempo)
            self.MIDIFile.addProgramChange(track, 0, time, instrument)

            for n in note_list:
                if len(n) == 2:
                    note = n[0]
                    channel = n[1]
                else:
                    note = n
                    channel = 0
                self.add_note(track, channel, note)

        # And write it to disk.
        with open(self.outfile, 'wb') as binfile:
            self.MIDIFile.writeFile(binfile)
예제 #4
0
def create_midi(note_groups):
    midi = MIDIFile(1)

    track = 0
    time = 0
    channel = 0
    volume = 100

    midi.addTrackName(track, time, "Track")
    midi.addTempo(track, time, 140)

    for note_group in note_groups:
        duration = None
        for note in note_group:
            note_type = note.sym
            if note_type == "1":
                duration = 4
            elif note_type == "2":
                duration = 2
            elif note_type == "4,8":
                duration = 1 if len(note_group) == 1 else 0.5
            pitch = note.pitch
            midi.addNote(track, channel, pitch, time, duration, volume)
            time += duration

    #midi.addNote(track,channel,pitch,time,4,0)
    # And write it to disk.
    binfile = open("output.mid", 'wb')
    midi.writeFile(binfile)
    binfile.close()
예제 #5
0
    def save_midi(self):
        # Create the MIDIFile Object with 1 track
        self.MIDIFile = MIDIFile(len(self.tracks))

        for i, note_list in enumerate(self.tracks):

            # Tracks are numbered from zero. Times are measured in beats.
            track = i
            time = 0

            # Add track name and tempo.
            self.MIDIFile.addTrackName(track, time, "Track 1")
            self.MIDIFile.addTempo(track, time, self.tempo)

            for n in note_list:
                if len(n) == 2:
                    note = n[0]
                    channel = n[1]
                else:
                    note = n
                    channel = 0
                self.add_note(track, channel, note)

        # And write it to disk.
        binfile = open(self.outfile, 'wb')
        self.MIDIFile.writeFile(binfile)
        binfile.close()
예제 #6
0
 def save_song(self, output="my_file.mid"):
     self.song = MIDIFile(len(self.tracks_list))
     for t in self.tracks_list:
         self.song.addTempo(self.actual_track, t.start, t.tempo)
         self.add_pitches(t)
         self.actual_track += 1
     with open(output, "wb") as output_file:
         self.song.writeFile(output_file)
예제 #7
0
def create_midi(tempo, data):
    print('Converting to MIDI.')
    song = MIDIFile(1)
    song.addTempo(0, 0, tempo)

    grouped = [(note, sum(1 for i in g)) for note, g in groupby(data)]
    time = 0
    for note, duration in grouped:
        add_note(song, 0, note, time, duration)
        time += duration
    return song
def GeneratePiece(voices, voiceSize, instRange, ratios):
	print("Enter the name of a file with a melody in it")
	filename = sys.stdin.readline()
	melodyFile = open(filename[:-1], 'r')
	C = (instRange - voiceSize)//voices #the interval of imitation
	retval = MIDIFile(voices)
	#there are voices voices, numbered from bottom up
	#set tempi
	track = 0
	for r in ratios:
		retval.addTempo(track, 0, r * 240)
		track+=1
	#generate taleae, talea[0] is the top octave's talea, talea[1] is the next highest, etc.
	talea = [[]]
	for i in range(0, random.randint(3, 5)):
		talea[0].append(random.randint(1,5))
	#each other talea is the same number of notes, with each note lengths incremented 1 or 2 times
	for m in range(1, math.floor(voiceSize//12)):
		talea.append([])
		for i in range(0, len(talea[0])):
			talea[m].append(talea[m-1][i] + random.randint(1, 2))
	print(talea)
	#calculate the length of the piece (in half steps)
	length = 1
	temp = 0
	for m in range(0, len(talea)):
		temp = 0
		for i in range(0, len(talea[m])):
			temp += talea[m][i]
		length = lcm(length, temp)
	print(length)
	#figure out where each voice enters
	entrances = []
	for m in range(0, len(ratios)):
		temp = (ratios[0]-ratios[m]) * length
		entrances.append(temp)
	
	#write a melody for each octave of a single voice
	melody = GenerateMelody(talea, melodyFile)
	#write the melody to the midi file in each voice
	currentTime = 0
	for n in range(0, voices):
		for m in range(0, voiceSize//12):
			currentTime = entrances[n]
			i = 0
			while currentTime < length:
				i += 1
				i %= len(talea[m])
				retval.addNote(n, 0, bottom + melody[m][i] + (C * n), currentTime, talea[m][i]/2, 100)
				currentTime+=talea[m][i]
			
	return retval
예제 #9
0
def save_midi(offset,
              iois,
              pitches,
              path,
              click_track=False,
              click_track_phase=0,
              accent_downbeat=False,
              period=0,
              pulse=1,
              bpm=240,
              channel=0,
              velocity=100):
    '''
    bpm means grid-units per second in this case
    '''

    track = 0

    mf = MIDIFile(1)

    mf.addTrackName(track, 0, "Sample Track")
    mf.addTempo(track, 0, bpm)

    if click_track:

        duration = offset + sum(iois)
        write_click_track(mf,
                          duration,
                          phase=click_track_phase,
                          period=period,
                          pulse=pulse,
                          velocity=velocity,
                          accent_downbeat=accent_downbeat)

    write_notes(mf,
                offset,
                iois,
                pitches,
                track=track,
                channel=channel,
                velocity=velocity)

    with open(path, 'wb') as midi_file:
        mf.writeFile(midi_file)
예제 #10
0
 def __init__(self, partition, tempo):
     # Définition des paramètres MIDI.
     piste = 0
     temps = 0
     self.sortieMidi = MIDIFile(1)
     # Nom de la piste.
     self.sortieMidi.addTrackName(piste, temps, "Gregorien")
     # Tempo.
     self.sortieMidi.addTempo(piste, temps, tempo)
     # Instrument (74 : flûte).
     self.sortieMidi.addProgramChange(piste, 0, temps, 74)
     # À partir des propriétés de la note, création des évènements
     # MIDI.
     for note in partition:
         channel = 0
         pitch = note.hauteur
         duree = note.duree
         volume = 127
         self.sortieMidi.addNote(piste, channel, pitch, temps, duree,
                                 volume)
         temps += duree
예제 #11
0
def midiSing(sheet, instruments, key, ticktime, filename):
    offset = NOTES.index(key) + 60  # Middle C is MIDI note #60
    midi = MIDIFile(len(sheet))
    replaceprint('Creating midi...')
    for t in range(0, len(sheet)):
        midi.addTrackName(t, 0, "Track %s" % t)
        midi.addTempo(t, 0, 60000 / (ticktime))
        sheet[t] = sheet[t][1:] + [(sheet[t][0], 0)]
        tracklen = len(sheet[t])
        for n in range(0, tracklen - 1):
            time, note = sheet[t][n]
            duration = sheet[t][(n + 1) % tracklen][0] - time
            midi.addNote(
                t, 0, offset + note, time, duration,
                100)  #MyMIDI.addNote(track,channel,pitch,time,duration,volume)
    replaceprint('Writing to file...')
    binfile = open(filename + ".mid", 'wb')
    midi.writeFile(binfile)
    binfile.close()
    replaceprint('Synth complete!')
    print("\nMID output to: \"" + filename + ".mid\"")
예제 #12
0
 def __init__(self, partition, tempo):
     # Définition des paramètres MIDI.
     piste = 0
     temps = 0
     self.sortieMidi = MIDIFile(1)
     # Nom de la piste.
     self.sortieMidi.addTrackName(piste, temps, TITRE)
     # Tempo.
     self.sortieMidi.addTempo(piste, temps, tempo)
     # Instrument (74 : flûte).
     self.sortieMidi.addProgramChange(piste, 0, temps, 74)
     # À partir des propriétés de la note, création des évènements
     # MIDI.
     for neume in partition.musique:
         for note in (notes for notes in neume if type(notes) == Note):
             channel = 0
             pitch = note.hauteur + partition.transposition
             duree = note.duree
             volume = 127
             self.sortieMidi.addNote(piste, channel, pitch, temps, duree,
                                     volume)
             temps += duree
예제 #13
0
파일: main.py 프로젝트: phewitt/SheetVision
    for r in staff_boxes:
        r.draw(img, (0, 0, 255), 2)
    for r in sharp_recs:
        r.draw(img, (0, 0, 255), 2)
    flat_recs_img = img.copy()
    for r in flat_recs:
        r.draw(img, (0, 0, 255), 2)
        
    cv2.imwrite('res.png', img)
 
   
    for note_group in note_groups:
        print([ note.note + " " + note.sym for note in note_group])

    midi = MIDIFile(1)
     
    track = 0   
    time = 0
    channel = 0
    volume = 100
    
    midi.addTrackName(track, time, "Track")
    midi.addTempo(track, time, 140)

    for note_group in note_groups:
        duration = None
        for note in note_group:
            note_type = note.sym
            if note_type == "1":
                duration = 4
예제 #14
0
############################################################################
# A sample program to create a single-track MIDI file, add a note,
# and write to disk.
############################################################################

#Import the library
from midiutil.MidiFile3 import MIDIFile

import csv

track1 = 0
track2 = 1
time = 0

MyMIDI = MIDIFile(2)
MyMIDI.addTrackName(track1, time, "Temperature MusicHI")
time = time + 1
MyMIDI.addTrackName(track2, time, "Temperature MusicLOW")
time = time + 1
MyMIDI.addTempo(track1, time, 540)
time = time + 1
MyMIDI.addTempo(track2, time, 540)

time = time + 1
MyMIDI.addProgramChange(track1, 0, time, 1)
time = time + 1
MyMIDI.addProgramChange(track2, 1, time, 2)

time = time + 1

#f = open("climate2010.txt")
from pythagorean_tuning import *

my_root = 30
pyts = IntervalScale(7, 12, my_root)
scale2 = IntervalScale(7, 7, my_root)
scale3 = IntervalScale(1, 12, my_root)
scale4 = MinorScale(my_root)
scale5 = MajorPentatonicScale(my_root)
scale6 = MajorScale(my_root)
#use_scale = pyts
#use_scale = PythagoreanScale(my_root)
use_scale = scale5
#use_scale = pythagorean_tuning.MinorScale(my_root)

from midiutil.MidiFile3 import MIDIFile
mf1 = MIDIFile(1)

from my_midi_utils import GetTicksPerBeat
ticks_per_beat = GetTicksPerBeat(mf1)

duration = 0.25
velocity = 100

#fname = 'A000010 - euler_phi.txt'
#pathname = 'source_txt/'
##fname = '3x plus 1 - A006577.txt'
##fname = 'Karl Aage Rasmussen - build up - ascending - A056239.txt'
##fname = 'fractal - A025480 - other_version.txt'
#import numpy as np
#seq = np.loadtxt(pathname+fname,dtype=np.int)
#
    def play(self):
        ''' Play Method
                Generates the MIDI tracks necessary to play the composition
                Plays the composition using pygame module
        '''
        # Create two MIDI tracks
        midi = MIDIFile(2)
        # Piano right hand track
        track = 0
        time = 0
        midi.addTrackName(track, time, "Piano Right Hand")
        midi.addTempo(track, time, self.tempo)
        track = 1
        midi.addTrackName(track, time, "Piano Left Hand")
        midi.addTempo(track, time, self.tempo)
        while (self.boolean):
            # Create new progressions as long as self.boolean is True
            progression = self.progressionf()
            proglength = len(progression)
            flag = 0
            # If the length of the progression is greater than self.totalbeats,
            # the composition will last longer than the user-input duration
            # Therefore, try 10 more times to generate a progression shorter
            # than self.totalbeats.
            while self.totalbeats <= proglength:
                progression = self.progressionf()
                proglength = len(progression)
                flag += 1
                if flag == 10:
                    break
            # If the length of the progression is suitable, add it to self.compprog
            if self.totalbeats >= proglength:
                self.compprog.extend(progression)
                # Subtract length of progression from self.totalbeats (so that
                # self.totalbeats keeps track of number of beats left in the
                # composition)
                self.totalbeats -= proglength
                track = 0
                channel = 0
                volume = 100
                # Create rhythmlist
                temprlist = self.rhythmgen(progression)
                rhythmlist = []
                for r in temprlist:
                    for el in r:
                        rhythmlist.append(el)
                # Create melodylist using rhythmlist
                melodylist = self.melodygen(progression, temprlist, self.scale,
                                            5)
                rllength = len(rhythmlist)
                # Add each note to the piano right hand track
                for n in range(rllength):
                    pitch = melodylist[n]
                    duration = rhythmlist[n]
                    midi.addNote(track, channel, pitch, self.time1, duration,
                                 volume)
                    self.time1 += rhythmlist[n]
            # If program fails to generate a progression shorter than self.totalbeats,
            # add the tonic to self.compprog and end the composition
            else:
                self.compprog.append(self.tonic)
                self.boolean = False
        # Piano left hand track
        track = 1
        channel = 0
        duration = 0.25
        volume = 80
        # For every harmony in self.compprog, add the alberti bass line
        for n in range(len(self.compprog)):
            a = self.albertibass(
                harmony(self.compprog[n], self.roots, self.reverse_labels), 4)
            if n == len(self.compprog) - 1:
                pitch = a[0]
                duration = 0.5
                midi.addNote(track, channel, pitch, self.time2, duration,
                             volume)
            else:
                for iter in range(2):
                    for tone in range(4):
                        pitch = a[tone]
                        midi.addNote(track, channel, pitch, self.time2,
                                     duration, volume)
                        self.time2 += 0.25
        # Write a midi file
        file = "composition.mid"
        with open(file, 'wb') as binfile:
            midi.writeFile(binfile)
        # Play the midi file using pygame
        pygame.init()
        pygame.mixer.init()
        pygame.mixer.music.load(file)
        pygame.mixer.music.play()

        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
예제 #17
0
def create_midi_from_progression(progression):
    """
	Given a chord progression in the form of a list of chord instances,
	creates a MIDI file as an output.
	"""
    MyMIDI = MIDIFile(4)
    track = 0
    time = 0
    MyMIDI.addTrackName(track, time, "Soprano")
    MyMIDI.addTempo(track, time, 60)
    track += 1
    MyMIDI.addTrackName(track, time, "Alto")
    MyMIDI.addTempo(track, time, 60)
    track += 1
    MyMIDI.addTrackName(track, time, "Tenor")
    MyMIDI.addTempo(track, time, 60)
    track += 1
    MyMIDI.addTrackName(track, time, "Bass")
    MyMIDI.addTempo(track, time, 60)

    channel = 0
    duration = 1
    volume = 100

    for index, chord in enumerate(progression):
        track = 3
        for note in chord.get_notes():
            pitch = note.get_midi_number()
            MyMIDI.addNote(track, channel, pitch, time, duration, volume)
            track -= 1
        time += 1
        if index == len(progression) - 2:
            duration = 2
    binfile = open("output_individual_voices.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()

    MyMIDI = MIDIFile(2)
    track = 0
    time = 0
    MyMIDI.addTrackName(track, time, "Upper Voices")
    MyMIDI.addTempo(track, time, 60)
    track += 1
    MyMIDI.addTrackName(track, time, "Lower Voices")
    MyMIDI.addTempo(track, time, 60)

    duration = 1

    for index, chord in enumerate(progression):
        track = 1
        count = 0
        for note in chord.get_notes():
            pitch = note.get_midi_number()
            MyMIDI.addNote(track, channel, pitch, time, duration, volume)
            if count % 2 == 1:
                track -= 1
            count += 1
        time += 1
        if index == len(progression) - 2:
            duration = 2
    binfile = open("output_two_hands.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
예제 #18
0
 def __init__(self, max_tracks, filename):
     self.midi = MIDIFile(max_tracks)
예제 #19
0
# indexes to elements of data row
windDirection = 7
windSpeed = 6
precipitation = 1
yearColumn = 4
weatherColumn = 8
weatherYear = "1950"
stormCenter = 1

pitch = 60
highTempAdjustment = 30
lowTempAdjustment = 30

# Create the MIDIFile Object with 3 tracks plus names of tracks

MyMIDI = MIDIFile(3)
MyMIDI.addTrackName(track1, time, "Year Changes")
time = time + 1
MyMIDI.addTrackName(track2, time, "Percussion")
time = time + 1
#MyMIDI.addTrackName(track3,time,"Misc")
#time = time +1
MyMIDI.addTempo(track1, time, beats)
time = time + 1
MyMIDI.addTempo(track2, time, beats)
#time = time +1
#MyMIDI.addTempo(track3,time, beats)

# set voice (sound) to be played on tracks
#  we used General Midi sounds ( see General Midi docs )
time = time + 1
예제 #20
0
def image_process_2():
    image = cv2.imread('temp/src_image.jpg', 0)
    list_ = image.tolist()
    if max(map(max, list_)) > 225:
        thresh_1 = 0.66 * max(map(max, list_))
        thresh_2 = 0.70 * max(map(max, list_))
        thresh_3 = 0.72 * max(map(max, list_))
    elif max(map(max, list_)) < 200:
        thresh_1 = 0.65 * max(map(max, list_))
        thresh_2 = 0.75 * max(map(max, list_))
        thresh_3 = 0.84 * max(map(max, list_))
    else:
        thresh_1 = 0.66 * max(map(max, list_))
        thresh_2 = 0.72 * max(map(max, list_))
        thresh_3 = 0.75 * max(map(max, list_))

    ret, img_gray1 = cv2.threshold(dstImg, thresh_1, 255, cv2.THRESH_BINARY)
    ret, img_gray2 = cv2.threshold(dstImg, thresh_2, 255, cv2.THRESH_BINARY)
    ret, img_gray3 = cv2.threshold(dstImg, thresh_3, 255, cv2.THRESH_BINARY)

    img_gray = 255 * np.ones(shape=[780, 551], dtype=np.uint8)

    # cv2.namedWindow("img_gray", cv2.WINDOW_AUTOSIZE)
    # cv2.imshow("img_gray", img_gray)

    for i in range(780):
        for j in range(551):
            if img_gray1[i][j] == 0 and img_gray2[i][j] == 0 and img_gray3[i][
                    j] == 0:
                img_gray[i][j] = 0
            elif img_gray1[i][j] == 0 or img_gray2[i][j] == 0:
                if img_gray3[i][j] == 0:
                    img_gray[i][j] = 0
            elif img_gray1[i][j] == 0 or img_gray3[i][j] == 0:
                if img_gray2[i][j] == 0:
                    img_gray[i][j] = 0
            elif img_gray2[i][j] == 0 or img_gray3[i][j] == 0:
                if img_gray1[i][j] == 0:
                    img_gray[i][j] = 0

    img = img_gray

    # height, width = img.shape[:2]
    # img_width, img_height = img_gray.shape[::-1]

    # <<找五線譜
    staff_recs = locate_images(img_gray, staff_imgs, staff_lower, staff_upper,
                               staff_thresh)
    staff_recs = [j for i in staff_recs for j in i]
    heights = [r.y for r in staff_recs] + [0]
    histo = [heights.count(i) for i in range(0, max(heights) + 1)]
    avg = np.mean(list(set(histo)))
    staff_recs = [r for r in staff_recs if histo[r.y] > avg]
    staff_recs = merge_recs(staff_recs, 0.01)
    # staff_recs_img = img.copy()
    # for r in staff_recs:
    #     r.draw(staff_recs_img, (0, 0, 255), 2)
    # >>

    #  <<找五線譜的模板
    resul = []
    resul.append(staff_recs[0])
    for index, item in enumerate(staff_recs):
        if abs(resul[-1].y - item.y) > 100:
            resul.append(item)
        else:
            continue
    # print("resul", resul)
    # >>

    # <<找五線譜的y座標
    staff = []
    line_axis = []
    for item in resul:
        # print("item.y", item.y)
        line_axis.append(item.y)
        y_project = []
        line_ = []
        for i in range(int(item.h)):
            count = 0
            for j in range(int(item.w)):
                if img[item.y + i, item.x + j] == 0:
                    count += 1
                else:
                    continue
            y_project.append(count)
        # print("y_project(count)", y_project)

        i = 1
        while i < len(y_project):
            if (y_project[i] == 0):
                i += 1
                continue
            elif (y_project[i] > 0 and y_project[i + 1] > 0
                  and y_project[i + 2] > 0):
                line = (i + i + 1 + i + 2) // 3
                line_.append(line + item.y)
                i += 3
            elif (y_project[i] > 0 and y_project[i + 1] > 0):
                line = (i + i + 1) // 2
                line_.append(line + item.y)
                i += 2
            else:
                line = i
                line_.append(line + item.y)
                i += 1
                continue
        staff.append(line_)
    # print("line_axis", line_axis)   #每行譜的五條線的最上面那條
    # print("staff", staff)   #每行譜的五條線
    # >>

    ##### 第一行對x投影
    x_range = [102] * (len(resul))
    x_range[0] = 120
    # print('ra_list',ra_list)
    quarter_recs = []
    half_recs = []
    for x_range_index, x_range_ in enumerate(x_range):
        x_project1 = []
        for x in range(x_range_, 485):
            count = 0
            for y in range(staff[x_range_index][0] - 15,
                           staff[x_range_index][4] + 15):
                if img[y, x] == 0:
                    count += 1
                else:
                    continue
            x_project1.append(count)

        # <<音符的x範圍
        note_xposition = []
        one_note = []
        next_to = False
        for index, item in enumerate(x_project1):
            if item > 8 and next_to == False:  #找到第一個大於9的x
                one_note.append(index)
                next_to = True  #觸發next_to等於True
            elif item > 8 and next_to == True:  #next_to等於True的情況下如果還是大於九則不做理會
                continue
            elif item < 8 and next_to == True:  #next_to等於True的情況下如果小於九則存入one_note
                one_note.append(index - 1)
                if one_note[1] - one_note[
                        0] > 5:  #one_note[0]是起始x,one_note[1]是結束的x,間距要超過5才會把它存入note_xposition
                    # print("index" ,index)
                    note_xposition.append(one_note)
                one_note = []
                next_to = False  #next_to等於False
        # print("note_xposition", note_xposition)
        # print('xpo', time.time() - start_time)
        # 音符的x範圍>>

        # <<音符的y範圍
        note_yposition = []
        note_xpos_yproject = []
        # for index__ in note_xposition:
        # note_xpos_yproject = []
        for r in range(len(note_xposition)):
            for j in range(staff[x_range_index][0] - 15,
                           staff[x_range_index][4] + 15):
                count = 0
                for i in range(note_xposition[r][0] + x_range_,
                               note_xposition[r][1] + x_range_):
                    if img[j, i] == 0:
                        count += 1
                    else:
                        continue
                note_xpos_yproject.append(count)

            one_note_ = []
            next_to_ = False
            for index_, item in enumerate(note_xpos_yproject):
                if item > 3 and next_to_ == False:  #找到第一個大於3的y
                    one_note_.append(index_)
                    next_to_ = True  #觸發next_to_等於True
                elif item > 3 and next_to_ == True:  #next_to_等於True的情況下如果還是大於3則不做理會
                    continue
                elif item < 3 and next_to_ == True:  #next_to_等於True的情況下如果小於3則存入one_note_
                    one_note_.append(index_ - 1)
                    if one_note_[1] - one_note_[
                            0] > 6:  #one_note_[0]是起始y,one_noteY[1]是結束的y,間距要超過6才會把它存入note_xposition
                        note_yposition.append(one_note_)
                    one_note_ = []
                    next_to_ = False  #next_to等於False
            # print("note_xpos_yproject", note_xpos_yproject)
            note_xpos_yproject = []
        # print("note_yposition", note_yposition)
        # 音符的y範圍>>

        # fingers = []
        # for i in range(len(note_xposition)):
        #     crop_img = img[staff[x_range_index][4]+15 : staff[x_range_index][4]+30, x_range[x_range_index] + note_xposition[i][0] : x_range[x_range_index] + note_xposition[i][1]]
        #     if i == 1:
        #         print("crop_img", crop_img)
        #     # 找finger1
        #     finger1_recs = locate_images(crop_img, finger1_imgs, finger1_lower, finger1_upper, finger1_thresh)

        #     # finger1_recs = finger1_recs[0]
        #     finger1_recs = merge_recs([j for i in finger1_recs for j in i], 0.5)
        #     finger1_recs_img = img.copy()
        #     if i == 1:
        #         print("finger1_recs", len(finger1_recs))
        #     for r in finger1_recs:
        #         r.draw(finger1_recs_img, (0, 0, 255), 2)
        # cv2.imwrite('finger1_recs_img.png', finger1_recs_img)
        # open_file('finger1_recs_img.png')

        global recs
        recs = []
        for r in range(len(note_xposition)):
            count = 0
            for j in range(staff[x_range_index][0] - 15 + note_yposition[r][0],
                           staff[x_range_index][0] - 15 +
                           note_yposition[r][1]):
                for i in range(note_xposition[r][0] + x_range_,
                               note_xposition[r][1] + x_range_):
                    if img[j, i] == 0:
                        count += 1
                    else:
                        continue
            # print(count/((note_xposition[r][1]-note_xposition[r][0])*(note_yposition[r][1]-note_yposition[r][0])))
            if (count /
                ((note_xposition[r][1] - note_xposition[r][0]) *
                 (note_yposition[r][1] - note_yposition[r][0])) > 0.64):
                rec = Rectangle(
                    note_xposition[r][0] + x_range_,
                    staff[x_range_index][0] - 15 + note_yposition[r][0],
                    note_xposition[r][1] - note_xposition[r][0],
                    note_yposition[r][1] - note_yposition[r][0])
                quarter_recs.append(rec)
                recs.append(rec)
            elif (count /
                  ((note_xposition[r][1] - note_xposition[r][0]) *
                   (note_yposition[r][1] - note_yposition[r][0])) <= 0.64):
                rec = Rectangle(
                    note_xposition[r][0] + x_range_,
                    staff[x_range_index][0] - 15 + note_yposition[r][0],
                    note_xposition[r][1] - note_xposition[r][0],
                    note_yposition[r][1] - note_yposition[r][0])
                half_recs.append(rec)
                recs.append(rec)

    # print("quarter_recs", quarter_recs)
    # print("half_recs", half_recs)
    # print("quarter_recs", len(quarter_recs))
    # print("half_recs", len(half_recs))
    l = recs
    # print("rec", rec)
    with open("temp/output.txt", "wb") as fp:  #Pickling
        pickle.dump(l, fp)

    # with open("test.txt", "rb") as fp:   # Unpickling
    #     b = pickle.load(fp)

    staff_boxes = [
        Rectangle(x_range[r], staff[r][2] - 33, 485 - x_range[r], 68)
        for r in range(len(staff))
    ]
    # staff_boxes_img = img.copy()
    # for r in staff_boxes:
    #     r.draw(staff_boxes_img, (0, 0, 255), 2)
    # cv2.imwrite('staff_boxes_img.png', staff_boxes_img)
    # open_file('staff_boxes_img.png')

    # objects_img = staff_boxes_img

    # 畫四分音符
    # quarter_recs_img = img.copy()
    # for r in quarter_recs:
    #     r.draw(quarter_recs_img, (0, 0, 255), 2)
    # cv2.imwrite('quarter_recs_img.png', quarter_recs_img)
    # open_file('quarter_recs_img.png')

    # 畫二分音符
    # half_recs_img = img.copy()
    # for r in half_recs:
    #     r.draw(half_recs_img, (0, 0, 255), 2)
    # cv2.imwrite('half_recs_img.png', half_recs_img)
    # open_file('half_recs_img.png')

    staff_notes = []
    note_groups = []
    for box in staff_boxes:
        staff_sharps = []
        staff_flats = []
        quarter_notes = [
            Note(r, "4,8", box, staff_sharps, staff_flats)
            for r in quarter_recs
            if abs(r.middle[1] - box.middle[1]) < box.h * 5.0 / 8.0
        ]
        half_notes = [
            Note(r, "2", box, staff_sharps, staff_flats) for r in half_recs
            if abs(r.middle[1] - box.middle[1]) < box.h * 5.0 / 8.0
        ]

        staff_notes = quarter_notes + half_notes

        staff_notes.sort(key=lambda n: n.rec.x)
        staffs = [r for r in staff_recs if r.overlap(box) > 0]
        staffs.sort(key=lambda r: r.x)
        note_color = (randint(0, 255), randint(0, 255), randint(0, 255))
        note_group = []
        i = 0
        j = 0
        while (i < len(staff_notes)):
            if j < len(staffs):
                if staff_notes[i].rec.x > staffs[j].x:
                    r = staffs[j]
                    j += 1
                    if len(note_group) > 0:
                        note_groups.append(note_group)
                        note_group = []
                    note_color = (randint(0,
                                          255), randint(0,
                                                        255), randint(0, 255))
                else:
                    note_group.append(staff_notes[i])
                    # staff_notes[i].rec.draww(img, note_color, 2)
                    i += 1
            else:
                note_group.append(staff_notes[i])
                # staff_notes[i].rec.draww(img, note_color, 2)
                i += 1
        note_groups.append(note_group)

    # for r in staff_boxes:
    #     r.draw(img, (0, 0, 255), 2)

    # cv2.imwrite('res.png', img)
    # open_file('res.png')

    # for note_group in note_groups:
    #     print([ note.note + " " + note.sym for note in note_group])

    midi = MIDIFile(1)

    track = 0
    time = 0
    channel = 0
    volume = 100

    midi.addTrackName(track, time, "Track")
    midi.addTempo(track, time, 60)

    for note_group in note_groups:
        duration = None
        for note in note_group:
            note_type = note.sym
            if note_type == "1":
                duration = 4
            elif note_type == "2":
                duration = 2
            elif note_type == "4,8":
                # duration = 1 if len(note_group) == 1 else 0.5
                duration = 1
            pitch = note.pitch
            midi.addNote(track, channel, pitch, time, duration, volume)
            time += duration

    # And write it to disk.
    binfile = open("temp/output.mid", 'wb')
    midi.writeFile(binfile)
    binfile.close()
예제 #21
0
############################################################################
# A sample program to create a single-track MIDI file, add a note,
# and write to disk.
############################################################################

#Import the library
from midiutil.MidiFile3 import MIDIFile

import csv
f = open("airports.dat")
for row in csv.reader(f):
    print(row[1])
# Create the MIDIFile Object
MyMIDI = MIDIFile(1)

# Add track name and tempo. The first argument to addTrackName and
# addTempo is the time to write the event.
track = 0
time = 0
MyMIDI.addTrackName(track, time, "Sample Track")
MyMIDI.addTempo(track, time, 120)

# Add a note. addNote expects the following information:
channel = 0
pitch = 60
duration = 1
volume = 100

# Now add the note.
MyMIDI.addNote(track, channel, pitch, time, duration, volume)