Download Matlab code: photoToDots.m
01 function photoToDots( src_file, dst_file, diameter ) 02 03 % Load image and convert to gray scale 04 src_img = rgb2gray(im2double(imread(src_file))); 05 06 % Calculate the dimensions of the output image 07 rows = round(size(src_img, 1) / diameter); 08 cols = round(size(src_img, 2) / diameter); 09 10 % Resize, normalize and invert the source image 11 src_img = imresize(src_img, [rows cols], 'bicubic'); 12 src_img = (src_img - min(src_img(:))) / (max(src_img(:) - min(src_img(:)))); 13 src_img = 1 - src_img; 14 15 % Create an empty destination image 16 dst_img = zeros((rows+1)*diameter, (cols+1)*diameter); 17 18 % Draw the dots 19 for i = 1:cols 20 for j = 1:rows 21 x = i * diameter; 22 y = j * diameter; 23 24 % The size of the dot is determined by the darkness of the original pixel 25 r = sqrt(src_img(j, i) * diameter^2 / pi); 26 dst_img = addDot(dst_img, x, y, r); 27 end 28 end 29 30 % If the output image is a png, store a transparent image. 31 if strcmpi(dst_file(end-3:end), '.png') 32 imwrite(zeros(size(dst_img)), dst_file, 'Alpha', dst_img); 33 34 % Otherwise, just store a grayscale image. 35 else 36 dst_img = 1 - dst_img; 37 imwrite(dst_img, dst_file); 38 end 39 end 40 41 function I = addDot(I, x, y, r) 42 43 % Determine the dimensions of the dot 44 w = ceil(r) + (x - floor(x)) - 1; 45 h = ceil(r) + (y - floor(y)) - 1; 46 47 % Create a meshgrid 48 [X,Y] = meshgrid(-h:h,-w:w); 49 50 % Create the dot (the division by 2 is to smooth the edge) 51 D = r-sqrt(X.^2+Y.^2); 52 C = min(max(D/2, 0), 1); 53 54 % Calculate the position of the patch in the destination image image 55 X = x+X; 56 Y = y+Y; 57 58 % Calculate the indexes in the destination image 59 idx = (X-1) * size(I,1) + Y; 60 61 % Add the dot to the original image 62 I(idx) = max(I(idx), C); 63 64 end