music_file='nabucodonosor.jpg'; % sheet music
mask_file='nabucodonosor_mask.jpg'; % note template

M=imread(music_file);
M = rgb2gray(M);
figure;
imshow(M); title('Original image');

M=255-M;

M2 = imtophat(M, strel('disk', 5));
figure;
imshow(M2); title('tophat of the negative');

M3 = im2bw(M2,.1);
figure;
imshow(M3); title('thresholding');

M4 = imopen(M3, strel('disk', 4));
figure;
imshow(M4); title('matching by opening with a disk');

SE = imread(mask_file);
SE = im2bw(SE, .5);
% A better result is obtained with a smaller template
%SE = imerode(SE, [1;1]);

M5 = imopen(M3, SE);
figure;
imshow(M5); title('matching by opening with a template');

% the morphological reconstruction can help in selecting the region
% where the notes can be found.
marker = imerode(M3,strel('line', 80, 0));
M6 = imreconstruct(marker, M3);
figure;
imshow(M6); title('reconstruction with a long horizontal line');

M7r = M;
M7g = M;
M7b = M;

% red channel: notes identified in M5
% blue channel: staff identified in M6

M7r(find(M5)) = 255;
M7g(find(M5)) = 0;
M7b(find(M5)) = 0;
M7b(find(M6)) = 255;

M7(:,:,1) = M7r;
M7(:,:,2) = M7g;
M7(:,:,3) = M7b;
figure;
imshow(M7); title('red: notes; blue: staff');


