Given these transparent png images, our goal is to plot these images at arbitrary locations (x, y, and rotation) in a MATLAB figure. For example, as follows:

This can be done in MATLAB by combining surf function with FaceColor option. 


Main code

rszwh  = [100 200];

carwh  = [4.5 1.8];

% POSITIONS

rcarpos = [10*rand(1, 2) 360*rand];

gcarpos = [10*rand(1, 2) 360*rand];

bcarpos = [10*rand(1, 2) 360*rand];

pcarpos = [10*rand(1, 2) 360*rand];

% LOAD IMAGES

[rcarrsz, rtrrsz] = get_rszcarimg('imgs/redcar.png', rszwh);

[gcarrsz, gtrrsz] = get_rszcarimg('imgs/greencar.png', rszwh);

[bcarrsz, btrrsz] = get_rszcarimg('imgs/bluecar.png', rszwh);

[pcarrsz, ptrrsz] = get_rszcarimg('imgs/purplecar.png', rszwh);


% THIS HAS TO RUN EVERY TIME. 

% PLOT

figure(); hold on; set(gcf,'Color', [0.6, 0.9, 0.8]/4 );

plot_carimage(rcarpos, carwh, rszwh, rcarrsz, rtrrsz); 

plot_carimage(gcarpos, carwh, rszwh, gcarrsz, gtrrsz); 

plot_carimage(bcarpos, carwh, rszwh, bcarrsz, btrrsz); 

plot_carimage(pcarpos, carwh, rszwh, pcarrsz, ptrrsz); 

axis equal off; grid on; 

xlabel('X'); ylabel('Y');

title('Plot Cars', 'FontSize', 15, 'Color', 'w');


Function codes

function [carrsz, trrsz] = get_rszcarimg(imgpath, rszwh)

% GET RESIZED CAR IMAGE


[carimg, ~, cartr] = imread(imgpath);

carrsz = imresize(carimg, rszwh);

trrsz  = imresize(cartr, rszwh);


function [xmesh_grid, ymesh_grid] = get_carmeshgred(carpos, carwh, rszwh)


[xtemp, ytemp] = meshgrid(linspace(-carwh(1)/2, carwh(1)/2, rszwh(2)) ...

    , linspace(-carwh(2)/2, carwh(2)/2, rszwh(1)));

xvec = xtemp(:);

yvec = ytemp(:);

xyvec = [xvec yvec];

c = cos(carpos(3)*pi/180);

s = sin(carpos(3)*pi/180);

rotmat = [c s ; -s c];

xyvec = xyvec * rotmat + repmat(carpos(1:2), rszwh(1)*rszwh(2), 1);

xvec = xyvec(:, 1);

yvec = xyvec(:, 2);

xmesh_grid = reshape(xvec, rszwh(1), rszwh(2));

ymesh_grid = reshape(yvec, rszwh(1), rszwh(2));


function plot_carimage(carpos, carwh, rszwh, carrsz, trrsz) 


[xmesh_grid, ymesh_grid] = get_carmeshgred(carpos, carwh, rszwh);

h = surf('xdata', xmesh_grid, 'ydata', ymesh_grid ...

    , 'zdata', zeros(rszwh(1), rszwh(2)) ...

    , 'cdata', carrsz, 'AlphaData', trrsz ...

    , 'FaceAlpha', 'texture' ...

    , 'FaceColor', 'texturemap' ...

    , 'EdgeColor','None', 'LineStyle', 'None');

Setting FaceAlpha option to texture and FaceColor option to texture map are important!

신고

'Enginius > Matlab' 카테고리의 다른 글

Closest Distance from Point to Line  (0) 2017.07.14
KNN-regression  (0) 2017.03.01
Plot transparent png images at arbitrary locations  (0) 2016.11.21
Highway Simulator  (0) 2016.02.23
Using MATLAB in script (OS X)  (0) 2016.01.15
Nonparametric Regression and Gaussian Random Paths  (0) 2015.12.23
« PREV : 1 : 2 : 3 : 4 : 5 : 6 : 7 : ··· : 65 : NEXT »