Home » Blog » Sketch with least-squares

Sketch with least-squares

The idea is from David Barber's page and here.

The original figure is here, as and we wish to have a sketch of it, not by hand, but from a computer program. The program is given a bunch of lines with random lengths and orientations and it seeks a weight for each of the lines through a minimisation of the least-squares error between the original and the generated figure.

The resulting figure is as follows.

The MATLAB program is

% load the image
yo = imread('a380.jpg');
Z = rgb2gray(yo);
 
N = 2000;                                  % number of lines
[Ymax, Xmax] = size(Z);                    % width and height
S = ceil(diag([Xmax Ymax])*rand(2,N));     % starting points for lines
E = ceil(diag([Xmax Ymax])*rand(2,N));     % ending points for lines
% for first run, initialise B=[];
% generating the lines (not optimised, very time consuming)
for i = 1:N
    b = zeros(Ymax,Xmax);
    dx = E(1,i) - S(1,i);
    if dx>0
        dy = E(2,i) - S(2,i);
        x = linspace(S(1,i),E(1,i),abs(dx)+1);
        y = round((x - S(1,i)) * dy / dx + S(2,i));
        b(sub2ind(size(b), y, x)) = 1;
        B = [B b(:)];
    end
end
disp('Lines generated...')
%least squres
B = sparse(B);                            
%w = B\double(Z(:));
w = lsqr(B,double(Z(:)));
imshow(reshape(B*w,Ymax,Xmax),[0 255])

— Last modified: xiaoke 2014/06/20 13:46