Spaces:
Running
on
Zero
Running
on
Zero
drscotthawley
commited on
Commit
•
6dfde8b
1
Parent(s):
caabda6
added more code
Browse files- app.py +35 -0
- find_min_max_notes.py +44 -0
- img2midi.py +51 -0
- midi2img.py +88 -0
- pianoroll.py +634 -0
- rect_to_square.py +26 -0
- square_to_rect.py +31 -0
app.py
CHANGED
@@ -25,6 +25,41 @@ from torchvision import transforms
|
|
25 |
import k_diffusion as K
|
26 |
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
def greet(name):
|
29 |
return "Hello " + name + "!!"
|
30 |
|
|
|
25 |
import k_diffusion as K
|
26 |
|
27 |
|
28 |
+
from .pianoroll import regroup_lines, img_file_2_midi_file, square_to_rect, rect_to_square
|
29 |
+
from .square_to_rect import square_to_rect
|
30 |
+
|
31 |
+
|
32 |
+
|
33 |
+
def infer_mask_from_init_img(img, mask_with='grey'):
|
34 |
+
"note, this works whether image is normalized on 0..1 or -1..1, but not 0..255"
|
35 |
+
assert mask_with in ['blue','white','grey']
|
36 |
+
"given an image with mask areas marked, extract the mask itself"
|
37 |
+
if not torch.is_tensor(img):
|
38 |
+
img = ToTensor()(img)
|
39 |
+
print("img.shape: ", img.shape)
|
40 |
+
# shape of mask should be img shape without the channel dimension
|
41 |
+
if len(img.shape) == 3:
|
42 |
+
mask = torch.zeros(img.shape[-2:])
|
43 |
+
elif len(img.shape) == 2:
|
44 |
+
mask = torch.zeros(img.shape)
|
45 |
+
print("mask.shape: ", mask.shape)
|
46 |
+
if mask_with == 'white':
|
47 |
+
mask[ (img[0,:,:]==1) & (img[1,:,:]==1) & (img[2,:,:]==1)] = 1
|
48 |
+
elif mask_with == 'blue':
|
49 |
+
mask[img[2,:,:]==1] = 1 # blue
|
50 |
+
if mask_with == 'grey':
|
51 |
+
mask[ (img[0,:,:] != 0) & (img[0,:,:]==img[1,:,:]) & (img[2,:,:]==img[1,:,:])] = 1
|
52 |
+
return mask*1.0
|
53 |
+
|
54 |
+
|
55 |
+
def count_notes_in_mask(img, mask):
|
56 |
+
"counts the number of new notes in the mask"
|
57 |
+
img_t = ToTensor()(img)
|
58 |
+
new_notes = (mask * (img_t[1,:,:] > 0)).sum() # green channel
|
59 |
+
return new_notes.item()
|
60 |
+
|
61 |
+
|
62 |
+
|
63 |
def greet(name):
|
64 |
return "Hello " + name + "!!"
|
65 |
|
find_min_max_notes.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
|
3 |
+
# this routine reads in many image files which are 128 pixels high
|
4 |
+
# and finds the lowest and highest non-black pixels across all images
|
5 |
+
import sys
|
6 |
+
from PIL import Image
|
7 |
+
from control_toys.data import fast_scandir
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
if __name__ == "__main__":
|
11 |
+
if len(sys.argv) < 2:
|
12 |
+
print(f"Usage: {sys.argv[0]} <image-dirs>")
|
13 |
+
sys.exit(1)
|
14 |
+
|
15 |
+
img_dirs = sys.argv[1:]
|
16 |
+
|
17 |
+
img_files = []
|
18 |
+
for imgdir in img_dirs:
|
19 |
+
i_subdirs, imfile = fast_scandir(imgdir, ['png', 'jpg', 'jpeg'])
|
20 |
+
if imfile != []: img_files = img_files + imfile
|
21 |
+
|
22 |
+
# remove any files with the 'transpose' in the name
|
23 |
+
img_files = [f for f in img_files if 'transpose' not in f]
|
24 |
+
|
25 |
+
if len(img_files) == 0:
|
26 |
+
print(f"No image files found in {img_dirs}")
|
27 |
+
sys.exit(1)
|
28 |
+
|
29 |
+
min_note = 128
|
30 |
+
max_note = 0
|
31 |
+
for img_file in tqdm(img_files):
|
32 |
+
img = Image.open(img_file)
|
33 |
+
img = img.convert('L')
|
34 |
+
for y in range(img.size[-1]):
|
35 |
+
for x in range(img.size[0]):
|
36 |
+
val = img.getpixel((x,y))
|
37 |
+
if val > 0:
|
38 |
+
if y < min_note: min_note = y
|
39 |
+
if y > max_note: max_note = y
|
40 |
+
break
|
41 |
+
print(f"min_note = {min_note}, max_note = {max_note}")
|
42 |
+
transpose_max = 12
|
43 |
+
print(f"So with transpostion of +/-{transpose_max}, the range is", min_note-transpose_max, "to", max_note+transpose_max)
|
44 |
+
sys.exit(0)
|
img2midi.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#! /usr/bin/env python3
|
2 |
+
|
3 |
+
# This script takes piano roll image files and converts them to MIDI
|
4 |
+
# It was intended for the P909 dataset
|
5 |
+
# It will create a directory of images for each MIDI file, where each image is a frame of the MIDI file
|
6 |
+
|
7 |
+
import os
|
8 |
+
import sys
|
9 |
+
import pretty_midi
|
10 |
+
import argparse
|
11 |
+
from multiprocessing import Pool, cpu_count
|
12 |
+
from tqdm import tqdm
|
13 |
+
from control_toys.data import fast_scandir
|
14 |
+
from functools import partial
|
15 |
+
from control_toys.pianoroll import img_file_2_midi_file
|
16 |
+
|
17 |
+
if __name__ == '__main__':
|
18 |
+
p = argparse.ArgumentParser(description=__doc__,
|
19 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
20 |
+
# use --no-onsets to disable requirment of onsets
|
21 |
+
p.add_argument('--diff', default='', help='diff against this background image, new notes go in instrument 2')
|
22 |
+
p.add_argument('--onsets', action=argparse.BooleanOptionalAction, default=True)
|
23 |
+
p.add_argument('--separators', default=0, type=int, help='draw separators every this many pixels. (0=none)')
|
24 |
+
p.add_argument("img_dirs", nargs='+', help="directories containing image files")
|
25 |
+
p.add_argument("output_dir", help="output directory")
|
26 |
+
args = p.parse_args()
|
27 |
+
#print('args = ',args)
|
28 |
+
|
29 |
+
img_dirs = args.img_dirs
|
30 |
+
output_dir = args.output_dir
|
31 |
+
|
32 |
+
|
33 |
+
if not os.path.exists(output_dir):
|
34 |
+
os.makedirs(output_dir)
|
35 |
+
|
36 |
+
img_files = []
|
37 |
+
if os.path.isfile(img_dirs[0]):
|
38 |
+
img_files = img_dirs
|
39 |
+
else:
|
40 |
+
for imgdir in img_dirs:
|
41 |
+
i_subdirs, imfile = fast_scandir(imgdir, ['png', 'jpg', 'jpeg'])
|
42 |
+
if imfile != []: img_files = img_files + imfile
|
43 |
+
if len(img_files) == 0:
|
44 |
+
print(f"No image files found in {img_dirs}")
|
45 |
+
sys.exit(1)
|
46 |
+
|
47 |
+
process_one = partial(img_file_2_midi_file, output_dir=output_dir, require_onsets=args.onsets,
|
48 |
+
separators=args.separators, diff_img_file=args.diff)
|
49 |
+
cpus = cpu_count()
|
50 |
+
with Pool(cpus) as p:
|
51 |
+
list(tqdm(p.imap(process_one, img_files), total=len(img_files), desc='Processing image files'))
|
midi2img.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#! /usr/bin/env python3
|
2 |
+
|
3 |
+
# This script takes a directory of MIDI files and converts them to images
|
4 |
+
# It was intended for the P909 dataset
|
5 |
+
# It will create a directory of images for each MIDI file, where each image is a frame of the MIDI file
|
6 |
+
|
7 |
+
# if you want to use the chord extractor, you need to run chord extractor on all the files, and then output
|
8 |
+
# a list of all the unique chord names to all_chords.txt e.g.
|
9 |
+
# $ cat ~/datasets/jsb_chorales_midi/*/*_chords.txt | awk -F'\t' '{print $3}' | sort | uniq -c | awk '{print $2}' > all_chords.txt
|
10 |
+
# cat midis/*_chords.txt | awk -F'\t' '{print $3}' | sort | uniq -c | awk '{print $2}' > all_chords.txt
|
11 |
+
# find midis -name '*_chords.txt' -exec cat {} + | awk -F'\t' '{print $3}' | sort | uniq -c | awk '{print $2}' > all_chords.txt
|
12 |
+
|
13 |
+
import os
|
14 |
+
import sys
|
15 |
+
from multiprocessing import Pool, cpu_count, set_start_method
|
16 |
+
from tqdm import tqdm
|
17 |
+
from control_toys.data import fast_scandir
|
18 |
+
from functools import partial
|
19 |
+
import argparse
|
20 |
+
from control_toys.pianoroll import midi_to_pr_img
|
21 |
+
from control_toys.chords import simplify_chord, POSSIBLE_CHORDS
|
22 |
+
|
23 |
+
def wrapper(args, midi_file, all_chords=None):
|
24 |
+
return midi_to_pr_img(midi_file, args.output_dir, show_chords=args.chords, all_chords=all_chords,
|
25 |
+
chord_names=args.chord_names, filter_mp=args.filter_mp, add_onsets=args.onsets,
|
26 |
+
remove_leading_silence=(not args.silence))
|
27 |
+
|
28 |
+
|
29 |
+
if __name__ == '__main__':
|
30 |
+
p = argparse.ArgumentParser(description=__doc__,
|
31 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
32 |
+
p.add_argument('-c','--chords', action='store_true', help='infer chords and add markers')
|
33 |
+
p.add_argument('--chord-names', action='store_true', help='Add text for chord names')
|
34 |
+
p.add_argument('--filter-mp', default=True, help='filter out non-piano, non-melody instruments')
|
35 |
+
#p.add_argument('--onsets', default=True, type=bool, help='add onset markers')
|
36 |
+
p.add_argument('--onsets', default=True, action=argparse.BooleanOptionalAction, help='Produce onset markers') # either --onsets or --no-onsets, default is...?
|
37 |
+
p.add_argument('--silence', default=True, action=argparse.BooleanOptionalAction, help='Leave silence at start of song (True) or remove it (False)')
|
38 |
+
p.add_argument('--start-method', type=str, default='fork',
|
39 |
+
choices=['fork', 'forkserver', 'spawn'],
|
40 |
+
help='the multiprocessing start method')
|
41 |
+
p.add_argument('--simplify', action='store_true', help='Simplify chord types, e.g. remove 13s')
|
42 |
+
p.add_argument('--skip-versions', default=True, help='skip extra versions of the same song')
|
43 |
+
p.add_argument("midi_dirs", nargs='+', help="directories containing MIDI files")
|
44 |
+
p.add_argument("output_dir", help="output directory")
|
45 |
+
args = p.parse_args()
|
46 |
+
print("args = ",args)
|
47 |
+
|
48 |
+
set_start_method(args.start_method)
|
49 |
+
midi_dirs, output_dir = args.midi_dirs, args.output_dir
|
50 |
+
|
51 |
+
if not os.path.exists(output_dir):
|
52 |
+
os.makedirs(output_dir)
|
53 |
+
|
54 |
+
if os.path.isdir(midi_dirs[0]):
|
55 |
+
midi_files = []
|
56 |
+
for mdir in midi_dirs:
|
57 |
+
m_subdirs, mf = fast_scandir(mdir, ['mid', 'midi'])
|
58 |
+
if mf != []: midi_files = midi_files + mf
|
59 |
+
elif os.path.isfile(midi_dirs[0]):
|
60 |
+
midi_files = midi_dirs
|
61 |
+
|
62 |
+
|
63 |
+
if args.skip_versions:
|
64 |
+
midi_files = [f for f in midi_files if '/versions/' not in f]
|
65 |
+
print("len(midi_files) = ",len(midi_files)) # just a check for debugging
|
66 |
+
|
67 |
+
if args.chords:
|
68 |
+
# TODO: this is janky af but for now...
|
69 |
+
# Get a list of all unique chords from a premade text file list of possible chords
|
70 |
+
# to make the file in bash, assuming you've already run extract_chords.py: (leave sort alphabetical, don't sort in order of freq)
|
71 |
+
# cat */*_chords.txt | awk -F'\t' '{print $3}' | sort | uniq -c | awk '{print $2}' > all_chords.txt
|
72 |
+
#with open('all_chords.txt') as f:
|
73 |
+
# all_chords = f.read().splitlines()
|
74 |
+
# use possible chords as all chords
|
75 |
+
all_chords = POSSIBLE_CHORDS # now we just generate these
|
76 |
+
if args.simplify:
|
77 |
+
all_chords = list(set([simplify_chord(c) for c in all_chords]))
|
78 |
+
print("len(all_chords) = ",len(all_chords))
|
79 |
+
print("all_chords = ",all_chords) # just a check for debugging
|
80 |
+
else:
|
81 |
+
all_chords = None
|
82 |
+
|
83 |
+
process_one = partial(wrapper, args, all_chords=all_chords)
|
84 |
+
num_cpus = cpu_count()
|
85 |
+
with Pool(num_cpus) as p:
|
86 |
+
list(tqdm(p.imap(process_one, midi_files), total=len(midi_files), desc='Processing MIDI files'))
|
87 |
+
|
88 |
+
print("Finished")
|
pianoroll.py
ADDED
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
|
3 |
+
"""
|
4 |
+
various routines for converting midi files to piano roll images and back
|
5 |
+
Unless otherwise noted: Author: Scott H. Hawley, Feb-March 2024
|
6 |
+
"""
|
7 |
+
|
8 |
+
import os
|
9 |
+
import torch
|
10 |
+
import torchvision
|
11 |
+
import torchvision.transforms as transforms
|
12 |
+
from PIL import Image, ImageOps, ImageDraw, ImageFont
|
13 |
+
import numpy as np
|
14 |
+
import pretty_midi
|
15 |
+
import matplotlib.pyplot as plt
|
16 |
+
from .chords import chord_num_to_color, simplify_chord, CHORD_BORDER
|
17 |
+
from .utils import rect_to_square, square_to_rect
|
18 |
+
|
19 |
+
ONSET_STYLE = 'new' # 'old'=onset markers on pixels before notes, 'new'=onset markers are part of notes
|
20 |
+
|
21 |
+
def plot_piano_roll(pr_array):
|
22 |
+
plt.figure(figsize=(8, 8))
|
23 |
+
plt.imshow(np.flipud(pr_array), aspect='auto')
|
24 |
+
plt.show()
|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
def piano_roll_to_pretty_midi(piano_roll, fs=8, program=0):
|
29 |
+
# this routine copied from https://github.com/jsleep/pretty-midi/blob/ba7d01e5796fedf3ca0a3528e48b5242d9d2ccc3/examples/reverse_pianoroll.py
|
30 |
+
'''Convert a Piano Roll array into a PrettyMidi object
|
31 |
+
with a single instrument.
|
32 |
+
|
33 |
+
Parameters
|
34 |
+
----------
|
35 |
+
piano_roll : np.ndarray, shape=(128,frames), dtype=int
|
36 |
+
Piano roll of one instrument
|
37 |
+
fs : int
|
38 |
+
Sampling frequency of the columns, i.e. each column is spaced apart
|
39 |
+
by ``1./fs`` seconds.
|
40 |
+
program : int
|
41 |
+
The program number of the instrument.
|
42 |
+
|
43 |
+
Returns
|
44 |
+
-------
|
45 |
+
midi_object : pretty_midi.PrettyMIDI
|
46 |
+
A pretty_midi.PrettyMIDI class instance describing
|
47 |
+
the piano roll.
|
48 |
+
|
49 |
+
'''
|
50 |
+
notes, frames = piano_roll.shape
|
51 |
+
#print("piano_roll.T[piano_roll.T != 0] = ",piano_roll.T[piano_roll.T != 0],flush=True)
|
52 |
+
pm = pretty_midi.PrettyMIDI()
|
53 |
+
instrument = pretty_midi.Instrument(program=program)
|
54 |
+
|
55 |
+
# pad 1 column of zeros so we can acknowledge inital and ending events
|
56 |
+
piano_roll = np.pad(piano_roll, [(0, 0), (1, 1)], 'constant')
|
57 |
+
|
58 |
+
# use changes in velocities to find note on / note off events
|
59 |
+
velocity_changes = np.nonzero(np.diff(piano_roll).T)
|
60 |
+
|
61 |
+
# keep track on velocities and note on times
|
62 |
+
prev_velocities = np.zeros(notes, dtype=int)
|
63 |
+
note_on_time = np.zeros(notes)
|
64 |
+
|
65 |
+
for time, note in zip(*velocity_changes):
|
66 |
+
# use time + 1 because of padding above
|
67 |
+
velocity = np.clip(piano_roll[note, time + 1], 0, 127)
|
68 |
+
#print("piano_roll[note, time + 1], velocity = ",piano_roll[note, time + 1], velocity,flush=True)
|
69 |
+
time = time / fs
|
70 |
+
if velocity > 0:
|
71 |
+
if prev_velocities[note] == 0:
|
72 |
+
note_on_time[note] = time
|
73 |
+
prev_velocities[note] = velocity
|
74 |
+
else:
|
75 |
+
pm_note = pretty_midi.Note(
|
76 |
+
velocity=prev_velocities[note],
|
77 |
+
pitch=note,
|
78 |
+
start=note_on_time[note],
|
79 |
+
end=time)
|
80 |
+
instrument.notes.append(pm_note)
|
81 |
+
prev_velocities[note] = 0
|
82 |
+
pm.instruments.append(instrument)
|
83 |
+
return pm
|
84 |
+
|
85 |
+
|
86 |
+
|
87 |
+
#### beginning of code copied from midi2img.py
|
88 |
+
|
89 |
+
def find_first_note_start(midi):
|
90 |
+
"""find the start time of the first note in the midi file
|
91 |
+
used to help alignment to beats/bars
|
92 |
+
"""
|
93 |
+
first_start = 10000.0
|
94 |
+
for instrument in midi.instruments:
|
95 |
+
for note in instrument.notes:
|
96 |
+
if note.start < first_start:
|
97 |
+
first_start = note.start
|
98 |
+
return first_start
|
99 |
+
|
100 |
+
|
101 |
+
def get_piano_rolls(midi, fs, remove_leading_silence=True, add_onsets=True, debug=False):
|
102 |
+
"""Converts a pretty_midi object to a piano roll for each instrument"""
|
103 |
+
duration = midi.get_end_time() # find out duration of the midi file
|
104 |
+
n_frames = int(np.ceil(duration * fs)) # calculate the number of frames
|
105 |
+
|
106 |
+
# create a piano roll for each instrument
|
107 |
+
# TODO: currently this is only setup for POP909 dataset, need to generalize for other datasets
|
108 |
+
piano_rolls = {'PIANO': np.zeros((128, n_frames)),
|
109 |
+
'MELODY': np.zeros((128, n_frames)),
|
110 |
+
'TOTAL': np.zeros((128, n_frames))}
|
111 |
+
if remove_leading_silence:
|
112 |
+
first_start = find_first_note_start(midi)
|
113 |
+
|
114 |
+
for instrument in midi.instruments:
|
115 |
+
name = instrument.name.upper()
|
116 |
+
if name in ['MELODY', 'PIANO']:
|
117 |
+
if debug: print(f"get_piano_rolls: instrument.name = {name}")
|
118 |
+
for note in instrument.notes:
|
119 |
+
if remove_leading_silence:
|
120 |
+
note.start -= first_start
|
121 |
+
note.end -= first_start
|
122 |
+
start = int(np.round(note.start * fs)) # quantize start time to nearest 16th note
|
123 |
+
dur = (note.end - note.start)*fs # quantize duration (Tip: don't separately quantize start & end; that can lead to "double-rounding" errors)
|
124 |
+
#end = int(np.round(note.end * fs))
|
125 |
+
end = start + int(np.round(dur)) # round means some notes will get held a bit too long, but "floor" would err on the side of extra staccatto notes which I don't want
|
126 |
+
if end==start: end = start+1 # make sure note is at least 1 pixel long
|
127 |
+
piano_rolls[name][note.pitch, start:end] = note.velocity ## value of piano roll array for these pixels will be the note velocity. end+1 so that "end" index gets covered
|
128 |
+
piano_rolls['TOTAL'][note.pitch, start:end] = note.velocity
|
129 |
+
#if note.velocity in [65,59,49,100]: print("note = ",note)
|
130 |
+
|
131 |
+
# extra fun: make sure all note onsets pop
|
132 |
+
piano_rolls[name][note.pitch, start-1] = 0
|
133 |
+
piano_rolls['TOTAL'][note.pitch, start-1] = 0
|
134 |
+
|
135 |
+
# if remove_leading_silence and add_onsets: # we need to add one pixel for the red onset dot at the start
|
136 |
+
# for instrument in piano_rolls:
|
137 |
+
# piano_rolls[instrument] = np.insert(piano_rolls[instrument], 0, 0, axis=1)
|
138 |
+
|
139 |
+
return piano_rolls
|
140 |
+
|
141 |
+
|
142 |
+
def piano_roll_to_img(pr_frame, # this is an array of shape (128, n_frames)
|
143 |
+
output_dir, midi_name, instrument,
|
144 |
+
start_col=None, add_onsets=True, chords=None, chord_names=False, debug=False,
|
145 |
+
onset_style=ONSET_STYLE, # 'new' or 'old'
|
146 |
+
):
|
147 |
+
os.makedirs(f"{output_dir}/{midi_name}", exist_ok=True)
|
148 |
+
filename = f"{output_dir}/{midi_name}/{midi_name}_{instrument}.png"
|
149 |
+
if start_col is not None:
|
150 |
+
filename = filename.replace(".png",f"_{str(start_col).zfill(5)}.png")
|
151 |
+
#if debug: print("pr_frame.T[pr_frame.T != 0] = ",pr_frame.T[pr_frame.T != 0])
|
152 |
+
#scaling_factor = 65 / 18 # found empiracally by lots of checking
|
153 |
+
#pr_frame = np.round(pr_frame * scaling_factor).astype(np.uint8)
|
154 |
+
|
155 |
+
scale_factor = 2 # velocity only goes up to 127, but colors go up to 255
|
156 |
+
green_channel = np.clip(np.round(pr_frame*scale_factor), 0, 255).astype(np.uint8)
|
157 |
+
rgb_image = np.dstack((np.zeros_like(green_channel), green_channel, np.zeros_like(green_channel)))
|
158 |
+
img = Image.fromarray(rgb_image,'RGB')
|
159 |
+
|
160 |
+
if add_onsets: # add little onset markers (red dots)
|
161 |
+
if onset_style=='old':
|
162 |
+
# any black pixel that has a green pixel to its right is an onset. color it red
|
163 |
+
# note that x any are flipped from what you'd think, e.g. "img.size = (2352, 128)"
|
164 |
+
for y in range(img.size[-1]):
|
165 |
+
for x in range(img.size[0]-1):
|
166 |
+
if img.getpixel((x,y)) == (0,0,0) and img.getpixel((x+1,y)) != (0,0,0):
|
167 |
+
img.putpixel((x,y), (255,0,0))
|
168 |
+
elif onset_style=='new':
|
169 |
+
# New version:
|
170 |
+
# any green pixel with a black pixel on its left becomes a red pixel. or if first pixel on row is green, make it red (matchinf velocity)
|
171 |
+
# Thus red pixel counts as both onset and first part of note, so shortest notes (16ths) will appear as only red with no green
|
172 |
+
# btw this seems to agree w/ polyffusion's approach (??)
|
173 |
+
for y in range(img.size[-1]):
|
174 |
+
x = 0
|
175 |
+
pxl = img.getpixel((x,y))
|
176 |
+
r,g,b = pxl
|
177 |
+
if is_green(*pxl):
|
178 |
+
img.putpixel((0,y), (g,0,0)) # make the first pixel of the note red, matching the green intensity
|
179 |
+
for x in range(1, img.size[0]):
|
180 |
+
pxl = img.getpixel((x,y))
|
181 |
+
r,g,b = pxl
|
182 |
+
if is_green(*pxl) and is_black(*img.getpixel((x-1,y))):
|
183 |
+
img.putpixel((x,y), (g,0,0))
|
184 |
+
else:
|
185 |
+
print(f"Error: Unrecognized onset_style = {onset_style}. Exiting.")
|
186 |
+
return
|
187 |
+
|
188 |
+
img = img.transpose(Image.FLIP_TOP_BOTTOM) # flip it vertically for display purposes
|
189 |
+
|
190 |
+
|
191 |
+
if chords is not None: # add the chord colors for each time as a rectangles at the top and bottom
|
192 |
+
if chord_names:
|
193 |
+
font_size = 7
|
194 |
+
try:
|
195 |
+
myFont = ImageFont.truetype("arial.ttf", 7) #mac
|
196 |
+
except:
|
197 |
+
myFont = ImageFont.load_default(size=font_size)
|
198 |
+
|
199 |
+
|
200 |
+
for c in chords:
|
201 |
+
color = chord_num_to_color(c['chord_num'])
|
202 |
+
img.paste(color, (int(c['start']), img.size[-1]-CHORD_BORDER, int(c['end']), img.size[-1]))
|
203 |
+
img.paste(color, (int(c['start']), 0, int(c['end']), CHORD_BORDER))
|
204 |
+
if chord_names:
|
205 |
+
chord_name = c['chord_name'].replace(':','')
|
206 |
+
if debug: print(f"chord_name = {chord_name}, chord_num = {c['chord_num']}")
|
207 |
+
xpos = int(c['start'])
|
208 |
+
I1 = ImageDraw.Draw(img)
|
209 |
+
I1.text((xpos, 0), chord_name, font=myFont, fill=(255, 255, 255))
|
210 |
+
|
211 |
+
if debug: print("img.size = ",img.size)
|
212 |
+
if 0 in img.size:
|
213 |
+
print(f"Error: img.size = {img.size}. Skipping this file.")
|
214 |
+
return
|
215 |
+
|
216 |
+
# # just make sure all blue is gone:
|
217 |
+
# img_array = np.array(img)
|
218 |
+
# img_array[:, :, 2] = 0
|
219 |
+
# img = Image.fromarray(img_array)
|
220 |
+
|
221 |
+
img.save(filename)
|
222 |
+
|
223 |
+
|
224 |
+
|
225 |
+
def check_for_melody_piano(midi: pretty_midi.PrettyMIDI, debug=False):
|
226 |
+
has_melody, has_piano = False, False
|
227 |
+
if debug:
|
228 |
+
print("check_for_melody_piano: midi.instruments = ",midi.instruments)
|
229 |
+
for i, instrument in enumerate(midi.instruments):
|
230 |
+
if debug: print(f"check_for_melody_piano: instrument = [{instrument.name.upper()}]")
|
231 |
+
if instrument.name.upper() == 'MELODY': has_melody = True
|
232 |
+
if instrument.name.upper() == 'PIANO': has_piano = True
|
233 |
+
# if theres only one instrument with no name, name it PIANO
|
234 |
+
if len(midi.instruments) == 1 and midi.instruments[0].name == '':
|
235 |
+
has_piano = True
|
236 |
+
midi.instruments[0].name = 'PIANO'
|
237 |
+
return has_melody, has_piano
|
238 |
+
|
239 |
+
|
240 |
+
|
241 |
+
def midi_to_pr_img(midi_file, output_dir,
|
242 |
+
show_chords=None, # to show chords or not
|
243 |
+
all_chords=None, # list of all possible chords
|
244 |
+
add_onsets=True, # add red dots for note onsets
|
245 |
+
chord_names=False, # to show chord names or not
|
246 |
+
filter_mp=True, # filter midi & piano
|
247 |
+
remove_leading_silence=True, # remove silence at start of song
|
248 |
+
simplify_chords=False, # simplify chord names
|
249 |
+
debug=False,): # show debugging info
|
250 |
+
"""Converts a MIDI file to a piano roll image"""
|
251 |
+
if debug: print(f"midi_to_pr_img: Processing {midi_file}")
|
252 |
+
if '/versions/' in midi_file and args.skip_versions: return
|
253 |
+
midi = pretty_midi.PrettyMIDI(midi_file)
|
254 |
+
|
255 |
+
if not check_for_melody_piano(midi):
|
256 |
+
print(f"Not ok: File {midi_file} does not have melody and piano. Skipping")
|
257 |
+
return
|
258 |
+
else:
|
259 |
+
if debug: print(f"Ok: File {midi_file} has melody and piano. Processing")
|
260 |
+
|
261 |
+
### Normalize tempo to 120bpm
|
262 |
+
tempo_changes = midi.get_tempo_changes()
|
263 |
+
start_tempo = tempo_changes[1][0]
|
264 |
+
bps = start_tempo / 60.0
|
265 |
+
fs = bps * 4.0 * 2
|
266 |
+
if debug: print("start_tempo, fs = ", start_tempo, fs)
|
267 |
+
|
268 |
+
chords=None
|
269 |
+
if show_chords and all_chords is not None:
|
270 |
+
# read the chord timing file, but note that those times have not yet been normalized to 120bpm
|
271 |
+
# this file has column-separated format "start_time end_time chord"
|
272 |
+
chords_path = midi_file.replace('.mid', '_chords.txt')
|
273 |
+
with open(chords_path) as f:
|
274 |
+
chords = f.read().splitlines()
|
275 |
+
# split each line of text into a dict 3 values {'start':, 'end':, 'chord':}:
|
276 |
+
chords = [dict(zip(['start', 'end', 'chord'], c.split('\t'))) for c in chords]
|
277 |
+
|
278 |
+
for c in chords:
|
279 |
+
c['start'] = int(np.floor(float(c['start']) * fs))
|
280 |
+
c['end'] = int(np.ceil(float(c['end']) * fs))
|
281 |
+
c['chord_name'] = simplify_chord(c['chord']) if simplify_chords else c['chord']
|
282 |
+
c['chord_num'] = all_chords.index(c['chord_name'])
|
283 |
+
|
284 |
+
if filter_mp: # remove non-piano, non-melody instruments
|
285 |
+
midi.instruments = [instrument for instrument in midi.instruments if instrument.name.upper() in ['MELODY', 'PIANO']]
|
286 |
+
|
287 |
+
piano_rolls = get_piano_rolls(midi, fs, remove_leading_silence=remove_leading_silence, add_onsets=add_onsets)
|
288 |
+
if debug:
|
289 |
+
for p in piano_rolls.keys():
|
290 |
+
print(f"p {p}.shape =",piano_rolls[p].shape)
|
291 |
+
#print(f"piano_rolls[{p}][piano_rolls[p] != 0] = ",piano_rolls[p][piano_rolls[p] != 0])
|
292 |
+
|
293 |
+
midi_name = os.path.basename(midi_file).split('.')[0] # get the midi filename w/o parent dirs or file extension
|
294 |
+
|
295 |
+
for instrument in piano_rolls: # save each instrument's piano roll as a single image
|
296 |
+
if debug: print("saving piano roll for ",instrument)
|
297 |
+
piano_roll_to_img(piano_rolls[instrument], output_dir, midi_name, instrument, chords=chords, chord_names=chord_names,
|
298 |
+
add_onsets=add_onsets, debug=debug)
|
299 |
+
|
300 |
+
return
|
301 |
+
|
302 |
+
#### end of code copied from midi2img.py
|
303 |
+
|
304 |
+
|
305 |
+
#### below code originally in img2midi.py
|
306 |
+
|
307 |
+
def blockout_topbottom_arr(arr, border=CHORD_BORDER):
|
308 |
+
"set the top and bottom border pixels to black"
|
309 |
+
arr2 = arr.copy()
|
310 |
+
arr2[:border, :] = 0
|
311 |
+
arr2[-border:, :] = 0
|
312 |
+
return arr2
|
313 |
+
|
314 |
+
def filter_by_velocity(midi, thresh=20):
|
315 |
+
"filter out notes with velocities below a certain threshold"
|
316 |
+
for instrument in midi.instruments:
|
317 |
+
notes = [note for note in instrument.notes if note.velocity > thresh]
|
318 |
+
instrument.notes = notes
|
319 |
+
return midi
|
320 |
+
|
321 |
+
def img2midi(img, draw_sep=512, debug=False):
|
322 |
+
# operates on a single image
|
323 |
+
# flip the image vertically because numpy and PIL have different ideas of what the first row is
|
324 |
+
# if image vertical dimension is more than 128, then cut it into strips of 128 and concatenate them horizontally
|
325 |
+
if debug: print(f"img2midi: img.size = {img.size}")
|
326 |
+
if img.size[1] > 128:
|
327 |
+
arr = np.concatenate([np.array(img.crop((0, i, img.size[0], i+128))) for i in range(0, img.size[1], 128)], axis=1)
|
328 |
+
else:
|
329 |
+
arr = np.array(img)
|
330 |
+
if debug: print("0: arr.T[arr.T != 0] = ",arr.T[arr.T != 0])
|
331 |
+
arr = blockout_topbottom_arr(arr)
|
332 |
+
|
333 |
+
scale_factor = 0.5 # rgb down to velocity values
|
334 |
+
piano_roll_array = np.array(arr*scale_factor, dtype=np.int32)
|
335 |
+
piano_roll_array = np.flip(piano_roll_array, axis=0) # numpy as PIL are upside down relative to each other
|
336 |
+
if debug:
|
337 |
+
print(f"piano_roll_array.shape = {piano_roll_array.shape}, piano_roll_array.dtype = {piano_roll_array.dtype}")
|
338 |
+
print("1: piano_roll_array[piano_roll_array != 0] = ",piano_roll_array[piano_roll_array != 0])
|
339 |
+
|
340 |
+
# draw a vertical line every 128/256/512 pixels
|
341 |
+
if draw_sep > 0:
|
342 |
+
line_every = draw_sep
|
343 |
+
for i in range(0, piano_roll_array.shape[-1], line_every):
|
344 |
+
if i>0: piano_roll_array[35:-35,i] = 30
|
345 |
+
piano_roll_array = np.clip(piano_roll_array, 0, 127) # make sure velocities aren't out of bounds
|
346 |
+
midi = piano_roll_to_pretty_midi(piano_roll_array)
|
347 |
+
midi = filter_by_velocity(midi)
|
348 |
+
return midi
|
349 |
+
|
350 |
+
|
351 |
+
def flip_bottom_half_and_attach(sub_img):
|
352 |
+
"takes one 256x256 and returns on 512x128 image with the bottom half reversed and attached on the right"
|
353 |
+
h, w = sub_img.size
|
354 |
+
new_img = Image.new(sub_img.mode, (w*2, h//2))
|
355 |
+
new_img.paste(sub_img.crop((0, 0, w, h//2)), (0, 0))
|
356 |
+
new_img.paste(sub_img.crop((0, h//2, w, h)).transpose(Image.FLIP_LEFT_RIGHT), (w, 0))
|
357 |
+
return new_img
|
358 |
+
|
359 |
+
|
360 |
+
def square_to_rect(img):
|
361 |
+
#"""just an alias for flip_bottom_half_and_attach"""
|
362 |
+
return flip_bottom_half_and_attach(img)
|
363 |
+
|
364 |
+
def rect_to_square(img):
|
365 |
+
"takes a 512x128 image and returns a 256x256 image with the bottom half reversed"
|
366 |
+
w, h = img.size
|
367 |
+
new_img = Image.new(img.mode, (w//2, h*2))
|
368 |
+
new_img.paste(img.crop((0, 0, w//2, h)), (0, 0))
|
369 |
+
new_img.paste(img.crop((w//2, 0, w, h)).transpose(Image.FLIP_LEFT_RIGHT), (0, h))
|
370 |
+
return new_img
|
371 |
+
|
372 |
+
def regroup_lines(img, debug=False):
|
373 |
+
"""
|
374 |
+
large images come in as an 8x8 grid of 256x256 images, in which the bottom half of each 256x256 is horizontally backwards
|
375 |
+
we will rebuild this grid by first flipping the bottom half of each 256x256 image
|
376 |
+
"""
|
377 |
+
img2 = Image.new('RGB', img.size)
|
378 |
+
if debug: print(f"regroup_lines: img.size = {img.size}")
|
379 |
+
|
380 |
+
if img.size[0] == 256:
|
381 |
+
img2 = Image.new('RGB', (512,128))
|
382 |
+
elif img.size[0] != 2048:
|
383 |
+
if debug: print("regroup_lines: unexpected image size, returning image unchanged")
|
384 |
+
return img # no op, hope all's well
|
385 |
+
imnum = 0
|
386 |
+
for row in range(0, img.size[0], 256):
|
387 |
+
for col in range(0, img.size[1], 256):
|
388 |
+
imnum += 1
|
389 |
+
sub_img = img.crop((col, row, col+256, row+256))
|
390 |
+
sub_img = square_to_rect(sub_img)
|
391 |
+
paste_x, paste_y = (imnum-1) % 4 * 512, (imnum-1) // 4 * 128
|
392 |
+
if debug: print(f"imnum = {imnum}, paste_x = {paste_x}, paste_y = {paste_y}")
|
393 |
+
img2.paste(sub_img, (paste_x, paste_y))
|
394 |
+
if debug: img2.show()
|
395 |
+
return img2
|
396 |
+
|
397 |
+
|
398 |
+
def is_red(r,g,b, thresh=20, debug=False):
|
399 |
+
result = r > thresh and g < thresh and b < thresh
|
400 |
+
if debug: print("is_red: r,g,b = ",r,g,b,", result = ",result)
|
401 |
+
return result
|
402 |
+
|
403 |
+
def is_green(r,g,b, thresh=20):
|
404 |
+
return r < thresh and g > thresh and b < thresh
|
405 |
+
|
406 |
+
def is_black(r,g,b, thresh=20):
|
407 |
+
return r < thresh and g < thresh and b < thresh
|
408 |
+
|
409 |
+
def filter_redgreen(img:Image,
|
410 |
+
require_onsets=True, # only keep green lines that start with a red pixel on the left
|
411 |
+
thresh=20, # minimum amount of red or green to count
|
412 |
+
onset_style=ONSET_STYLE, # 'new' or 'old
|
413 |
+
debug=False):
|
414 |
+
# filter: only keep black points, and green lines that start with a red pixel on the left.
|
415 |
+
# i.e. only green points that have red or green to their left are valid notes
|
416 |
+
# intended for img2midi
|
417 |
+
img.save('rgfilter_in.png')
|
418 |
+
img2 = img.copy()
|
419 |
+
if debug: print("img.size = ",img.size,", require_onsets = ",require_onsets," (not require_onsets) =",(not require_onsets)," thresh = ",thresh)
|
420 |
+
w, h = img.size
|
421 |
+
for y in range(CHORD_BORDER,h-CHORD_BORDER):
|
422 |
+
note_on = False
|
423 |
+
for x in range(w): # scan from right to left
|
424 |
+
r,g,b = img2.getpixel((x,y)) # pixel under consideration
|
425 |
+
if debug and (r,g,b)!=(0,0,0): print(f"x, y: {x}, {y}: r, g, b = {r},{g},{b}, note_on = {note_on}, is_red = {is_red(r,g,b, thresh)}, is_green = {is_green(r,g,b, thresh)}")
|
426 |
+
if is_red(r,g,b, thresh):
|
427 |
+
note_on = True
|
428 |
+
if onset_style == 'new': # keep the note but change the red to green
|
429 |
+
img2.putpixel((x,y), (0,r,0))
|
430 |
+
elif is_green(r,g,b, thresh) and require_onsets and note_on:
|
431 |
+
img2.putpixel((x,y), (r,g,b)) # keep the note
|
432 |
+
elif is_green(r,g,b, thresh) and (not require_onsets):
|
433 |
+
img2.putpixel((x,y), (r,g,b)) # keep the note
|
434 |
+
note_on = True
|
435 |
+
else:
|
436 |
+
note_on = False
|
437 |
+
img2.putpixel((x,y), (0,0,0)) # zero it out
|
438 |
+
|
439 |
+
img2.save('rgfilter_out.png') # debugging always on here
|
440 |
+
return img2
|
441 |
+
|
442 |
+
def arr_check(img, tag=''):
|
443 |
+
img = img.convert("RGB")
|
444 |
+
arr = np.array(img)[:,:,1]
|
445 |
+
print(tag,": arr.shape = ",arr.shape, flush=True)
|
446 |
+
print(tag,": arr.T[arr.T != 0] = ",arr.T[arr.T != 0], flush=True)
|
447 |
+
|
448 |
+
def img2midi_multi(img, require_onsets=True, separators=512, debug=False):
|
449 |
+
"can operate on a grid of images"
|
450 |
+
img = img.convert('RGB')
|
451 |
+
img = regroup_lines(img)
|
452 |
+
img = filter_redgreen(img, require_onsets=require_onsets)
|
453 |
+
#img = img.convert('L') # convert to grayscale
|
454 |
+
red_arr = np.array(img.split()[0])
|
455 |
+
green_arr = np.array(img.split()[1])
|
456 |
+
combined_arr = red_arr + green_arr
|
457 |
+
if debug: arr_check(img, '1')
|
458 |
+
img = Image.fromarray(combined_arr, mode="L")
|
459 |
+
if debug: arr_check(img, '2')
|
460 |
+
return img2midi(img, draw_sep=separators)
|
461 |
+
|
462 |
+
def infer_mask_from_init_img(img, mask_with='grey', debug=True):
|
463 |
+
"note, this works whether image is normalized on 0..1 or -1..1, but not 0..255"
|
464 |
+
assert mask_with in ['blue','white','grey']
|
465 |
+
"given an image with mask areas marked, extract the mask itself"
|
466 |
+
img = np.array(img)
|
467 |
+
mask = np.zeros(img.shape[:2])
|
468 |
+
if debug: print("infer: img.shape, mask.shape = ",img.shape, mask.shape)
|
469 |
+
if mask_with == 'white':
|
470 |
+
mask[ (img[0,:,:]==1) & (img[1,:,:]==1) & (img[2,:,:]==1)] = 1
|
471 |
+
elif mask_with == 'blue':
|
472 |
+
mask[img[2,:,:]==1] = 1 # blue
|
473 |
+
if mask_with == 'grey':
|
474 |
+
mask[ (img[:,:,0] != 0) & (img[:,:,0] > -1) & (img[:,:,0]==img[:,:,1]) & (img[:,:,2]==img[:,:,1])] = 1
|
475 |
+
return mask*1.0
|
476 |
+
|
477 |
+
def img_file_2_midi_file(img_file, output_dir='', require_onsets=True, separators=512,
|
478 |
+
diff_img_file='', debug=True):
|
479 |
+
"Converts an image file to a midi file"
|
480 |
+
if debug: print(f"Processing {img_file}", flush=True)
|
481 |
+
img = Image.open(img_file)
|
482 |
+
if debug: arr_check(img, '0')
|
483 |
+
midi = img2midi_multi(img, require_onsets=require_onsets, separators=separators)
|
484 |
+
|
485 |
+
if diff_img_file != '': # put new notes on new instrument.
|
486 |
+
bg_img = rect_to_square(Image.open(diff_img_file))
|
487 |
+
mask = infer_mask_from_init_img(bg_img, mask_with='grey')
|
488 |
+
# tile mask to 3 color channels
|
489 |
+
mask = np.stack([mask]*3, axis=-1)
|
490 |
+
if debug:
|
491 |
+
print("mask.shape = ",mask.shape, flush=True)
|
492 |
+
print("mask.min(), mask.max(), mask.sum() = ",mask.min(), mask.max(), mask.sum(), flush=True)
|
493 |
+
if bg_img.size[0] > img.size[0]:
|
494 |
+
bg_img = rect_to_square(bg_img)
|
495 |
+
bg_midi = img2midi_multi(bg_img, require_onsets=require_onsets, separators=separators)
|
496 |
+
# grab just the pixels in the mask of img
|
497 |
+
arr = np.array(img)
|
498 |
+
if debug:
|
499 |
+
print("arr.shape, mask.shape = ",arr.shape, mask.shape, flush=True)
|
500 |
+
print("arr.min(), arr.max(), arr.sum() = ",arr.min(), arr.max(), arr.sum(), flush=True)
|
501 |
+
new_arr = np.zeros_like(arr)
|
502 |
+
new_arr[mask > 0] = 1*255# arr[mask > 0]
|
503 |
+
new_arr = np.where(mask>0, arr, 0)
|
504 |
+
# new_arr[:,:,0] = arr[:,:,0] * mask
|
505 |
+
# new_arr[:,:,1] = arr[:,:,1] * mask
|
506 |
+
# new_arr[:,:,2] = arr[:,:,2] * mask
|
507 |
+
new_img = Image.fromarray(new_arr, 'RGB')
|
508 |
+
square_to_rect(new_img).save('new_img.png')
|
509 |
+
new_midi = img2midi_multi(new_img, require_onsets=require_onsets, separators=separators)
|
510 |
+
bg_midi.instruments.append(new_midi.instruments[0])
|
511 |
+
midi = bg_midi
|
512 |
+
|
513 |
+
midi_file = os.path.basename(img_file).replace('.png', '.mid')
|
514 |
+
if output_dir is not None and output_dir != '':
|
515 |
+
midi_file = os.path.join(output_dir, midi_file)
|
516 |
+
midi.write(midi_file)
|
517 |
+
return midi_file
|
518 |
+
|
519 |
+
|
520 |
+
|
521 |
+
#### end of code copied from img2midi.py
|
522 |
+
|
523 |
+
|
524 |
+
|
525 |
+
### dataset routines, called from train.h
|
526 |
+
|
527 |
+
class RandomVerticalShift(torch.nn.Module):
|
528 |
+
"""
|
529 |
+
Update: UNUSED. Instead we do all transposing as pre-processing to facilitate chord detection.
|
530 |
+
Randomly shift the image vertically by up to max_shift pixels, which correspond to semitones.
|
531 |
+
"""
|
532 |
+
def __init__(self, max_shift=12):
|
533 |
+
super().__init__()
|
534 |
+
self.max_shift = max_shift
|
535 |
+
|
536 |
+
def __call__(self, img):
|
537 |
+
shift = torch.randint(-self.max_shift, self.max_shift, (1,))
|
538 |
+
return self.vertical_shift(img, shift.item())
|
539 |
+
|
540 |
+
def vertical_shift(self, img, shift):
|
541 |
+
img = ImageOps.exif_transpose(img) # Handle EXIF Orientation
|
542 |
+
img = img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, shift), fillcolor=0)
|
543 |
+
return img
|
544 |
+
|
545 |
+
|
546 |
+
|
547 |
+
class RandomBarCrop(torch.nn.Module):
|
548 |
+
"""
|
549 |
+
Given a PIL image of a piano roll (non-square!), do random cropping the level of measures, i.e. bars, i.e. 16 16th-note pixels
|
550 |
+
NOTE: might be nice if piano roll images have initial silence pre-removed -- assuming the first note is supposed to start on the first beat
|
551 |
+
"""
|
552 |
+
def __init__(self, bar_length=16, window_length=512):
|
553 |
+
super().__init__()
|
554 |
+
self.bl = bar_length # in 16th notes (16 pixels)
|
555 |
+
self.wl = window_length # in pixels
|
556 |
+
self.bic = self.wl // self.bl # bars in crop
|
557 |
+
|
558 |
+
def __call__(self, img: Image, debug=False):
|
559 |
+
bars_in_image = img.size[0] // self.bl # number of bars in full image
|
560 |
+
if self.bic >= bars_in_image: # pad horizontal end of image with zeros if needed
|
561 |
+
pad = self.wl - img.size[0] + 1
|
562 |
+
img = ImageOps.expand(img, (0, 0, pad, 0), fill=0)
|
563 |
+
bars_in_image = img.size[0] // self.bl
|
564 |
+
try:
|
565 |
+
start_ind = torch.randint(0, bars_in_image - self.bic+1, (1,)).item() # start index of crop
|
566 |
+
except Exception as e:
|
567 |
+
print(f"***MY ERROR: {e}. bars_in_image = {bars_in_image}, self.bic = {self.bic}")
|
568 |
+
assert False
|
569 |
+
start_pixel = start_ind * self.bl # start pixel of crop
|
570 |
+
new_img = img.crop((start_pixel, 0, start_pixel + self.wl, img.size[1]))
|
571 |
+
assert new_img.size[0] == self.wl and new_img.size[1]==128, f"ERROR: new_img.size = {new_img.size}, self.wl = {self.wl}"
|
572 |
+
return new_img
|
573 |
+
|
574 |
+
|
575 |
+
|
576 |
+
class StackPianoRollsImage(torch.nn.Module):
|
577 |
+
"""
|
578 |
+
Given a PIL image of a piano roll, cut in in half horizontally,
|
579 |
+
stack the two halves, with the lower half mirrored horzontally.
|
580 |
+
"""
|
581 |
+
def __init__(self, final_size=(256, 256), max_shift=13):
|
582 |
+
super().__init__()
|
583 |
+
self.final_size = final_size
|
584 |
+
|
585 |
+
def __call__(self, img: Image, debug=False):
|
586 |
+
if img.size[0] <= 128 and img.size[1] <= 128:
|
587 |
+
return img # don't stack small images
|
588 |
+
# image dimensions are likely 512x128. I want 256x256 output
|
589 |
+
half_width = img.size[0] // 2
|
590 |
+
#make a new image with dimensions 256x256, with the same color mode as img
|
591 |
+
new_img = Image.new(img.mode, self.final_size)
|
592 |
+
# paste the first half of the image into the top half of the new image
|
593 |
+
first_half = img.crop((0, 0, half_width, img.size[1]))
|
594 |
+
new_img.paste(first_half, (0, 0))
|
595 |
+
# paste the second half of the image into the bottom half of the new image, but flipped horizontally
|
596 |
+
next_half = img.crop((half_width, 0, 2*half_width, img.size[1]))
|
597 |
+
next_half = ImageOps.mirror(next_half)
|
598 |
+
new_img.paste(next_half, (0, img.size[1]))
|
599 |
+
return new_img
|
600 |
+
|
601 |
+
|
602 |
+
|
603 |
+
class StackPianoRollsTensor(torch.nn.Module):
|
604 |
+
"""
|
605 |
+
Tensor version of StackPianoRollsImage. Unused, i think.
|
606 |
+
Given a torch tensor of a piano roll, cut in in half horizontally, stack the two halves
|
607 |
+
but have the bottom half mirrored horzontally.
|
608 |
+
"""
|
609 |
+
def __init__(self):
|
610 |
+
super().__init__()
|
611 |
+
|
612 |
+
def __call__(self, img: torch.Tensor):
|
613 |
+
if img.shape[0] <= 128 and img.shape[1] <= 128:
|
614 |
+
return img # don't stack small images
|
615 |
+
img = img.permute(1, 2, 0)
|
616 |
+
half_width = img.shape[0] // 2
|
617 |
+
img = torch.cat([img[:half_width], img[half_width:][::-1]], dim=0)
|
618 |
+
img = img.permute(2, 0, 1)
|
619 |
+
return img
|
620 |
+
|
621 |
+
|
622 |
+
|
623 |
+
|
624 |
+
if __name__ == '__main__':
|
625 |
+
import sys
|
626 |
+
|
627 |
+
# testing for the StackPianoRollsImage class
|
628 |
+
filename = sys.argv[-1]
|
629 |
+
print("filename = ", filename)
|
630 |
+
img = Image.open(filename)
|
631 |
+
img = transforms.RandomCrop((128, 512))(img) # randomly crop it to 128x512
|
632 |
+
img = StackPianoRollsImage()(img, debug=True)
|
633 |
+
img.show()
|
634 |
+
|
rect_to_square.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
|
3 |
+
# reads in a rectangular image, cuts it in half length-wise, and attaches the right half to the bottom, reversed
|
4 |
+
|
5 |
+
import sys
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
|
9 |
+
def rect_to_square(img):
|
10 |
+
# get width and height of img
|
11 |
+
w, h = img.size
|
12 |
+
new_img = Image.new(img.mode, (w//2, h*2))
|
13 |
+
new_img.paste(img.crop((0, 0, w, h)), (0, 0))
|
14 |
+
new_img.paste(img.crop((0, 0, w, h)).transpose(Image.FLIP_LEFT_RIGHT), (0, h))
|
15 |
+
return new_img
|
16 |
+
|
17 |
+
|
18 |
+
if __name__ == '__main__':
|
19 |
+
img_filename = sys.argv[1]
|
20 |
+
in_img = Image.open(img_filename)
|
21 |
+
print("Input image dimenions: ", in_img.size)
|
22 |
+
out_img = rect_to_square(in_img)
|
23 |
+
print("Output image dimenions: ", out_img.size)
|
24 |
+
out_filename = img_filename.replace('.png', '_square.png')
|
25 |
+
print("Saving to ", out_filename)
|
26 |
+
out_img.save(out_filename)
|
square_to_rect.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
|
3 |
+
# reads in a square image and outputs a rectangular image
|
4 |
+
|
5 |
+
import sys
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
def flip_bottom_half_and_attach(img):
|
9 |
+
"takes one 256x256 and returns on 512x128 image with the bottom half reversed and attached on the right"
|
10 |
+
#w, h = 256, 256
|
11 |
+
h, w = img.size
|
12 |
+
#assert sub_img.size[0] == h and sub_img.size[1] == w
|
13 |
+
new_img = Image.new(img.mode, (w*2, h//2))
|
14 |
+
new_img.paste(img.crop((0, 0, w, h//2)), (0, 0))
|
15 |
+
new_img.paste(img.crop((0, h//2, w, h)).transpose(Image.FLIP_LEFT_RIGHT), (w, 0))
|
16 |
+
return new_img
|
17 |
+
|
18 |
+
def square_to_rect(img):
|
19 |
+
# just an alias for flip_bottom_half_and_attach
|
20 |
+
return flip_bottom_half_and_attach(img)
|
21 |
+
|
22 |
+
|
23 |
+
if __name__ == '__main__':
|
24 |
+
img_filename = sys.argv[1]
|
25 |
+
square_img = Image.open(img_filename)
|
26 |
+
print("Input image dimenions: ", square_img.size)
|
27 |
+
rect_img = square_to_rect(square_img)
|
28 |
+
print("Output image dimenions: ", rect_img.size)
|
29 |
+
out_filename = img_filename.replace('.png', '_rect.png')
|
30 |
+
print("Saving to ", out_filename)
|
31 |
+
rect_img.save(out_filename)
|