I need to do the following:
I have a fixed environment with a point in it
At each time step the point moves and I need to take a screenshot of the current status (environment + point)
What I do is
function getPixels(state)
fig = figure('visible','off')
hold all
plot_environment() % calls patch and other stuff
plot(state(1),state(2),'r+')
f = getframe();
data = f.cdata;
close(fig)
The problem is that it is very slow (0.6s which for me is really too much).
I tried using persistent fig and I can go down to 0.4s, still too much.
I read about using print or hardcopy, but it did not help. Even reducing the number of pixels by -r20 (1/5 of my default size) did not speed it up.
Any suggestion? Is there a faster way to get the pixels?
EDIT: ADDITIONAL DETAILS
The state is just a 2d point.
The environment is defined by some fixed known variables used to draw shapes. More specifically I have some points
points = [c11 c12
c21 c22
.....]
used to patch rectangles, circles and triangles. For this I use patch and circles.
So in the end I want to plot everything together and get the resulting pixels. Is there a way to do it without getframe or a way to speed it up?
COMPLETE EXAMPLE
It requires circles.
Launch tic, getPixels([0.1, 0.2]'); toc
It takes 0.43s on average. The getframe command alone takes 0.29s.
function data = getPixels(state)
fig = figure('visible','off');
hold all
c1 = [0.1 0.75;
0.45 0.75];
c2 = [0.45 0.4;
0.45 0.8];
radius = 0.1;
grey = [0.4,0.4,0.4];
% Circles
p = [c1; c2];
circles(p(:,1), p(:,2), radius, 'color', grey, 'edgecolor', grey)
% Rectangles
patch([0.1 0.45 0.45 0.1], [0.65 0.65 0.85 0.85], grey, 'EdgeAlpha', 0)
patch([0.35 0.55 0.55 0.35], [0.4 0.4 0.8 0.8], grey, 'EdgeAlpha', 0)
% Triangle
x = [0.95, 1.0, 1.0];
y = [1.0, 0.95, 1.0];
fill(x, y, 'r')
axis([0 1 0 1])
box on
axis square
% Point
plot(state(1),state(2),'ro','MarkerSize',8,'MarkerFaceColor','r');
f = getframe();
data = f.cdata;
close(fig)
You can reduce the execution time of Matlab's getframe() function by a factor of ten. The trick consists of not creating a figure each time you call the getPixels() function but using an existing one. You may pass the figure handle via the function parameters. And use the Matlab's function clf that clears the current figure window between two calls.
EDIT
Here is an example of the way I play with figure et getframe.
The following performance chart
is given by
%%
clear al
close all
clc
nbSim = 10 %number of getframe calls
tElapsed = zeros(nbSim, 2); %two types of getting frames
%% METHOD 1: figure within loop
for ind_sim = 1:nbSim
fig = figure;
%some graphical elements
hold all
patch(rand(1,4), rand(1,4), rand(1,3), 'EdgeAlpha', 0)
patch(rand(1,4), rand(1,4), rand(1,3), 'EdgeAlpha', 0)
fill(rand(1,3), rand(1,3), 'r')
plot(rand,rand,'ro','MarkerSize',8,'MarkerFaceColor','k');
%some axes properties
axis([0 1 0 1])
box on
axis square
tStart = tic;
f = getframe();
tElapsed(ind_sim,1) = toc(tStart);
data = f.cdata;
close(fig)
end
%% METHOD 2: figure outside loop
fig = figure;
for ind_sim = 1:nbSim
%some graphical elements
hold all
patch(rand(1,4), rand(1,4), rand(1,3), 'EdgeAlpha', 0)
patch(rand(1,4), rand(1,4), rand(1,3), 'EdgeAlpha', 0)
fill(rand(1,3), rand(1,3), 'r')
plot(rand,rand,'ro','MarkerSize',8,'MarkerFaceColor','k');
%some axes properties
axis([0 1 0 1])
box on
axis square
tStart = tic;
f = getframe();
tElapsed(ind_sim,2) = toc(tStart);
data = f.cdata;
clf
end
close(fig)
%% plot results
plot(tElapsed);
set(gca, 'YLim', [0 max(tElapsed(:))+0.1])
xlabel('Number of calls');
ylabel('Execution time');
legend({'within (method 1)';'outside (method 2)'});
title('GetFrame exectution time');
You have to drop the creation of a figure, even if it is declared not visible. This impairs the execution times.
Related
Currently I have been working on obtaining the length of a curve, with the following code I have managed to get the length of a curve present in an image.
test image one curve
Then I paste the code that I used to get the length of the curve of a simple image. What I did is the following:
I got the columns and rows of the image
I got the columns in x and the rows in y
I obtained the coefficients of the curve, based on the formula of the
parable
Build the equation
Implement the arc length formula to obtain the length of the curve
grayImage = imread(fullFileName);
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
grayImage = grayImage(:, :, 2); % Take green channel.
end
subplot(2, 2, 1);
imshow(grayImage, []);
% Get the rows (y) and columns (x).
[rows, columns] = find(binaryImage);
coefficients = polyfit(columns, rows, 2); % Gets coefficients of the formula.
% Fit a curve to 500 points in the range that x has.
fittedX = linspace(min(columns), max(columns), 500);
% Now get the y values.
fittedY = polyval(coefficients, fittedX);
% Plot the fitting:
subplot(2,2,3:4);
plot(fittedX, fittedY, 'b-', 'linewidth', 4);
grid on;
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
% Overlay the original points in red.
hold on;
plot(columns, rows, 'r+', 'LineWidth', 2, 'MarkerSize', 10)
formula = poly2sym([coefficients(1),coefficients(2),coefficients(3)]);
% formulaD = vpa(formula)
df=diff(formula);
df = df^2;
f= (sqrt(1+df));
i = int(f,min(columns),max(columns));
j = double(i);
disp(j);
Now I have the image 2 which has n curves, I do not know how I can do to get the length of each curve
test image n curves
I suggest you to look at Hough Transformation:
https://uk.mathworks.com/help/images/hough-transform.html
You will need Image Processing Toolbox. Otherwise, you have to develop your own logic.
https://en.wikipedia.org/wiki/Hough_transform
Update 1
I had a two-hour thinking about your problem and I'm only able to extract the first curve. The problem is to locate the starting points of the curves. Anyway, here is the code I come up with and hopefully will give you some ideas for further development.
clc;clear;close all;
grayImage = imread('2.png');
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
grayImage = grayImage(:, :, 2); % Take green channel.
end
% find edge.
bw = edge(grayImage,'canny');
imshow(bw);
[x, y] = find(bw == 1);
P = [x,y];
% For each point, find a point that is of distance 1 or sqrt(2) to it, i.e.
% find its connectivity.
cP = cell(1,length(x));
for i = 1:length(x)
px = x(i);
py = y(i);
dx = x - px*ones(size(x));
dy = y - py*ones(size(y));
distances = (dx.^2 + dy.^2).^0.5;
cP{i} = [x(distances == 1), y(distances == 1);
x(distances == sqrt(2)), y(distances == sqrt(2))];
end
% pick the first point and a second point that is connected to it.
fP = P(1,:);
Q(1,:) = fP;
Q(2,:) = cP{1}(1,:);
m = 2;
while true
% take the previous point from point set Q, when current point is
% Q(m,1)
pP = Q(m-1,:);
% find the index of the current point in point set P.
i = find(P(:,1) == Q(m,1) & P(:,2) == Q(m,2));
% Find the distances from the previous points to all points connected
% to the current point.
dx = cP{i}(:,1) - pP(1)*ones(length(cP{i}),1);
dy = cP{i}(:,2) - pP(2)*ones(length(cP{i}),1);
distances = (dx.^2 + dy.^2).^0.5;
% Take the farthest point as the next point.
m = m+1;
p_cache = cP{i}(find(distances==max(distances),1),:);
% Calculate the distance of this point to the first point.
distance = ((p_cache(1) - fP(1))^2 + (p_cache(2) - fP(2))^2).^0.5;
if distance == 0 || distance == 1
break;
else
Q(m,:) = p_cache;
end
end
% By now we should have built the ordered point set Q for the first curve.
% However, there is a significant weakness and this weakness prevents us to
% build the second curve.
Update 2
Some more work since the last update. I'm able to separate each curve now. The only problem I can see here is to have a good curve fitting. I would suggest B-spline or Bezier curves than polynomial fit. I think I will stop here and leave you to figure out the rest. Hope this helps.
Note that the following script uses Image Processing Toolbox to find the edges of the curves.
clc;clear;close all;
grayImage = imread('2.png');
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
grayImage = grayImage(:, :, 2); % Take green channel.
end
% find edge.
bw = edge(grayImage,'canny');
imshow(bw);
[x, y] = find(bw == 1);
P = [x,y];
% For each point, find a point that is of distance 1 or sqrt(2) to it, i.e.
% find its connectivity.
cP =[0,0]; % add a place holder
for i = 1:length(x)
px = x(i);
py = y(i);
dx = x - px*ones(size(x));
dy = y - py*ones(size(y));
distances = (dx.^2 + dy.^2).^0.5;
c = [find(distances == 1); find(distances == sqrt(2))];
cP(end+1:end+length(c),:) = [ones(length(c),1)*i, c];
end
cP (1,:) = [];% remove the place holder
% remove duplicates
cP = unique(sort(cP,2),'rows');
% seperating curves
Q{1} = cP(1,:);
for i = 2:length(cP)
cp = cP(i,:);
% search for points in cp in Q.
for j = 1:length(Q)
check = ismember(cp,Q{j});
if ~any(check) && j == length(Q) % if neither has been saved in Q
Q{end+1} = cp;
break;
elseif sum(check) == 2 % if both points cp has been saved in Q
break;
elseif sum(check) == 1 % if only one of the points exists in Q, add the one missing.
Q{j} = [Q{j}, cp(~check)];
break;
end
end
% review sets in Q, merge the ones having common points
for j = 1:length(Q)-1
q = Q{j};
for m = j+1:length(Q)
check = ismember(q,Q{m});
if sum(check)>=1 % if there are common points
Q{m} = [Q{m}, q(~check)]; % merge
Q{j} = []; % delete the merged set
break;
end
end
end
Q = Q(~cellfun('isempty',Q)); % remove empty cells;
end
% each cell in Q represents a curve. Note that points are not ordered.
figure;hold on;axis equal;grid on;
for i = 1:length(Q)
x_ = x(Q{i});
y_ = y(Q{i});
coefficients = polyfit(y_, x_, 3); % Gets coefficients of the formula.
% Fit a curve to 500 points in the range that x has.
fittedX = linspace(min(y_), max(y_), 500);
% Now get the y values.
fittedY = polyval(coefficients, fittedX);
plot(fittedX, fittedY, 'b-', 'linewidth', 4);
% Overlay the original points in red.
plot(y_, x_, 'r.', 'LineWidth', 2, 'MarkerSize', 1)
formula = poly2sym([coefficients(1),coefficients(2),coefficients(3)]);
% formulaD = vpa(formula)
df=diff(formula);
lengthOfCurve(i) = double(int((sqrt(1+df^2)),min(y_),max(y_)));
end
Result:
You can get a good approximation of the arc lengths using regionprops to estimate the perimeter of each region (i.e. arc) and then dividing that by 2. Here's how you would do this (requires the Image Processing Toolbox):
img = imread('6khWw.png'); % Load sample RGB image
bw = ~imbinarize(rgb2gray(img)); % Convert to grayscale, then binary, then invert it
data = regionprops(bw, 'PixelList', 'Perimeter'); % Get perimeter (and pixel coordinate
% list, for plotting later)
lens = [data.Perimeter]./2; % Compute lengths
imshow(bw) % Plot image
hold on;
for iLine = 1:numel(data),
xy = mean(data(iLine).PixelList); % Get mean of coordinates
text(xy(1), xy(2), num2str(lens(iLine), '%.2f'), 'Color', 'r'); % Plot text
end
And here's the plot this makes:
As a sanity check, we can use a simple test image to see how good an approximation this gives us:
testImage = zeros(100); % 100-by-100 image
testImage(5:95, 5) = 1; % Add a vertical line, 91 pixels long
testImage(5, 10:90) = 1; % Add a horizontal line, 81 pixels long
testImage(2020:101:6060) = 1; % Add a diagonal line 41-by-41 pixels
testImage = logical(imdilate(testImage, strel('disk', 1))); % Thicken lines slightly
Running the above code on this image, we get the following:
As you can see the horizontal and vertical line lengths come out close to what we expect, and the diagonal line is a little bit more than sqrt(2)*41 due to the dilation step extending its length slightly.
I try with this post but i don´t understand so much, but the idea Colours123 sounds great, this post talk about GUI https://www.mathworks.com/matlabcentral/fileexchange/24195-gui-utility-to-extract-x--y-data-series-from-matlab-figures
I think that you should go through the image and ask if there is a '1' if yes, ask the following and thus identify the beginning of a curve, get the length and save it in a BD, I am not very good with the code , But that's my idea
I have to use an inverse filter to remove the blurring from this image
.
Unfortunately, I have to figure out the transfer function H of the imaging
system used to get these sharper images, It should be Gaussian. So, I should determine the approximate width of the Gaussian by trying different Gaussian widths in an inverse filter and judging which resulting images look the “best”.
The best result will be optimally sharp – i.e., edges will look sharp but will not have visible ringing.
I tried by using 3 approaches:
I created a transfer function with N dimensions (odd number, for simplicity), by creating a grid of N dimensions, and then applying the Gaussian function to this grid. After that, we add zeroes to this transfer function in order to get the same size as the original image. However, after applying the filter to the original image, I just see noise (too many artifacts).
I created the transfer function with size as high as the original image, by creating a grid of the same size as the original image. If sigma is too small, then the PSF FFT magnitude is wide. Otherwise it gets thinner. If sigma is small, then the image is even more blurred, but if we set a very high sigma value then we get the same image (not better at all).
I used the fspecial function, playing with sizes of sigma and h. But still I do not get anything sharper than the original blurred image.
Any ideas?
Here is the code used for creating the transfer function in Approach 1:
%Create Gaussian Filter
function h = transfer_function(N, sigma, I) %N is the dimension of the kernel
%create a 2D-grid that is the same size as the Gaussian filter matrix
grid = -floor(N/2) : floor(N/2);
[x, y] = meshgrid(grid, grid);
arg = -(x.*x + y.*y)/(2*sigma*sigma);
h = exp(arg); %gaussian 2D-function
kernel = h/sum(h(:)); %Normalize so that total weight equals 1
[rows,cols] = size(I);
add_zeros_w = (rows - N)/2;
add_zeros_h = (cols - N)/2;
h = padarray(kernel,[add_zeros_w add_zeros_h],0,'both'); % h = kernel_final_matrix
end
And this is the code for every approach:
I = imread('lena_blur.jpg');
I1 = rgb2gray(I);
figure(1),
I1 = double(I1);
%---------------Approach 1
% N = 5; %Dimension Assume is an odd number
% sigma = 20; %The bigger number, the thinner the PSF in FREQ
% H = transfer_function(N, sigma, I1);
%I1=I1(2:end,2:end); %To simplify operations
imagesc(I1); colormap('gray'); title('Original Blurred Image')
I_fft = fftshift(fft2(I1)); %Shift the image in Fourier domain to let its DC part in the center of the image
% %FILTER-----------Approach 2---------------
% N = 5; %Dimension Assume is an odd number
% sigma = 20; %The bigger number, the thinner the PSF in FREQ
%
%
% [x,y] = meshgrid(-size(I,2)/2:size(I,2)/2-1, -size(I,1)/2:size(I,1)/2-1);
% H = exp(-(x.^2+y.^2)*sigma/2);
% %// Normalize so that total area (sum of all weights) is 1
% H = H /sum(H(:));
%
% %Avoid zero freqs
% for i = 1:size(I,2) %Cols
% for j = 1:size(I,1) %Rows
% if (H(i,j) == 0)
% H(i,j) = 1e-8;
% end
% end
% end
%
% [rows columns z] = size(I);
% G_filter_fft = fft2(H,rows,columns);
%FILTER---------------------------------
%Filter--------- Aproach 3------------
N = 21; %Dimension Assume is an odd number
sigma = 1.25; %The bigger number, the thinner the PSF in FREQ
H = fspecial('gaussian',N,sigma)
[rows columns z] = size(I);
G_filter_fft = fft2(H,rows,columns);
%Filter--------- Aproach 3------------
%DISPLAY FFT PSF MAGNITUDE
figure(2),
imshow(fftshift(abs(G_filter_fft)),[]); title('FFT PSF magnitude 2D');
% Yest = Y_blurred/Gaussian_Filter
I_restoration_fft = I_fft./G_filter_fft;
I_restoration = (ifft2(I_restoration_fft));
I_restoration = abs(I_restoration);
I_fft = abs(I_fft);
% Display of Frequency domain (To compare with the slides)
figure(3),
subplot(1,3,1);
imagesc(I_fft);colormap('gray');title('|DFT Blurred Image|')
subplot(1,3,2)
imshow(log(fftshift(abs(G_filter_fft))+1),[]) ;title('| Log DFT Point Spread Function + 1|');
subplot(1,3,3)
imagesc(abs(I_restoration_fft));colormap('gray'); title('|DFT Deblurred|')
% imshow(log(I_restoration+1),[])
%Display PSF FFT in 3D
figure(4)
hf_abs = abs(G_filter_fft);
%270x270
surf([-134:135]/135,[-134:135]/135,fftshift(hf_abs));
% surf([-134:134]/134,[-134:134]/134,fftshift(hf_abs));
shading interp, camlight, colormap jet
xlabel('PSF FFT magnitude')
%Display Result (it should be the de-blurred image)
figure(5),
%imshow(fftshift(I_restoration));
imagesc(I_restoration);colormap('gray'); title('Deblurred Image')
%Pseudo Inverse restoration
% cam_pinv = real(ifft2((abs(G_filter_fft) > 0.1).*I_fft./G_filter_fft));
% imshow(fftshift(cam_pinv));
% xlabel('pseudo-inverse restoration')
A possible solution is deconvwr. I will first show its performance starting from an undistorted lena image. So, I know exactly the gaussian blurring function. Note that setting estimated_nsr to zero will destroy the performance completely due to quantisation noise.
I_ori = imread('lenaTest3.jpg'); % Download an original undistorted lena file
N = 19;
sigma = 5;
H = fspecial('gaussian',N,sigma)
estimated_nsr = 0.05;
I = imfilter(I_ori, H)
wnr3 = deconvwnr(I, H, estimated_nsr);
figure
subplot(1, 4, 1);
imshow(I_ori)
subplot(1, 4, 2);
imshow(I)
subplot(1, 4, 3);
imshow(wnr3)
title('Restoration of Blurred, Noisy Image Using Estimated NSR');
subplot(1, 4, 4);
imshow(H, []);
The best parameters I found for your problem by trial and error.
N = 19;
sigma = 2;
H = fspecial('gaussian',N,sigma)
estimated_nsr = 0.05;
EDIT: calculating exactly the used blurring filter
If you download an undistorted lena (I_original_fft), you can calculate the used blurring filter as follows:
G_filter_fft = I_fft./I_original_fft
My simplified problem is to animate some text on a 3D plot.
I have a cube,
vert = [1 1 0;0 1 0;0 1 1;1 1 1;0 0 1;1 0 1;1 0 0;0 0 0];
fac = [1 2 3 4; 4 3 5 6; 6 7 8 5; 1 2 8 7; 6 7 1 4; 2 3 5 8];
patch('Faces',fac,'Vertices',vert,'FaceColor',[.8 .5 .2]);
axis([0, 1, 0, 1, 0, 1]);
axis equal
axis off
Is it possible to get something like this?
Using text doesn't help (it looks fake!),
Thanks,
The idea is to use texture mapping as #Hoki showed. I tried to implement this on my end, here is what I came up with.
First we'll need 6 images to apply on the cube faces. These can be any random images of any size. For example:
% just a bunch of demo images from IPT toolbox
function imgs = get_images()
imgs = {
imread('autumn.tif');
imread('coloredChips.png');
imread('toysflash.png');
imread('football.jpg');
imread('pears.png');
imread('peppers.png');
};
end
Better yet, let's use an online service that returns placeholder images containing digits 1 to 6:
% online API for placeholder images
function imgs = get_images()
imgs = cell(6,1);
clr = round(255*brighten(lines(6),0.75));
for i=1:6
%bg = randsample(['0':'9' 'a':'f'], 6, true);
%fg = randsample(['0':'9' 'a':'f'], 6, true);
bg = strjoin(cellstr(dec2hex(clr(i,:))).', '');
fg = strjoin(cellstr(dec2hex(clr(7-i,:))).', '');
[img,map] = imread(sprintf(...
'http://placehold.it/100x100/%s/%s&text=%d', bg, fg, i));
imgs{i} = im2uint8(ind2rgb(img,map));
end
end
Here are the resulting images:
>> imgs = get_images();
>> montage(cat(4,imgs{:}))
Next let's create a function that renders a unit cube with images texture-mapped as faces:
function h = get_unit_cube(imgs)
% we need a cell array of 6 images, one for each face (they can be any size)
assert(iscell(imgs) && numel(imgs)==6);
% coordinates for unit cube
[D1,D2,D3] = meshgrid([-0.5 0.5], [-0.5 0.5], 0.5);
% texture mapped surfaces
opts = {'FaceColor','texturemap', 'EdgeColor','none'};
h = zeros(6,1);
h(6) = surface(D1, flipud(D2), D3, imgs{6}, opts{:}); % Z = +0.5 (top)
h(5) = surface(D1, D2, -D3, imgs{5}, opts{:}); % Z = -0.5 (bottom)
h(4) = surface(fliplr(D1), D3, flipud(D2), imgs{4}, opts{:}); % Y = +0.5 (right)
h(3) = surface(D1, -D3, flipud(D2), imgs{3}, opts{:}); % Y = -0.5 (left)
h(2) = surface(D3, D1, flipud(D2), imgs{2}, opts{:}); % X = +0.5 (front)
h(1) = surface(-D3, fliplr(D1), flipud(D2), imgs{1}, opts{:}); % X = -0.5 (back)
end
Here is what it looks like:
imgs = get_images();
h = get_unit_cube(imgs);
view(3), axis vis3d, rotate3d on
Now we can have some fun with this creating interesting animations. Consider the following:
% create two separate unit cubes
figure('Renderer','OpenGL')
h1 = get_unit_cube(get_images());
h2 = get_unit_cube(get_images());
set([h1;h2], 'FaceAlpha',0.8) % semi-transparent
view(3), axis vis3d off, rotate3d on
% create transformation objects, used as parents of cubes
t1 = hgtransform('Parent',gca);
t2 = hgtransform('Parent',gca);
set(h1, 'Parent',t1)
set(h2, 'Parent',t2)
% transform the second cube (scaled, rotated, then shifted)
M = makehgtform('translate', [-0.7 1.2 0.5]) * ...
makehgtform('yrotate', 15*(pi/180)) * ...
makehgtform('scale', 0.5);
set(t2, 'Matrix',M)
drawnow
axis on, axis([-2 2 -2 2 -0.7 1]), box on
xlabel x, ylabel y, zlabel z
% create animation by rotating cubes 5 times
% (1st rotated around z-axis, 2nd around its own z-axis in opposite
% direction as well as orbiting the 1st)
for r = linspace(0,10*pi,90)
R = makehgtform('zrotate', r);
set(t1, 'Matrix',R)
set(t2, 'Matrix',R\(M/R))
pause(0.1)
end
I'm using the hgtransform function to manage transformations, this is much more efficient than continuously changing the x/y/z data points of the graphics objects.
BTW I've used slightly different images in the animation above.
EDIT:
Let's replace the rotating cubes with images of planet earth mapped onto spheres. First here are two functions to render the spheres (I'm borrowing code from these examples in the MATLAB documentation):
get_earth_sphere1.m
function h = get_earth_sphere1()
% read images of planet earth
earth = imread('landOcean.jpg');
clouds = imread('cloudCombined.jpg');
% unit sphere with 35x35 faces
[X,Y,Z] = sphere(35);
Z = flipud(Z);
a = 1.02;
% render first sphere with earth mapped onto the surface,
% then a second transparent surface with clouds layer
if verLessThan('matlab','8.4.0')
h = zeros(2,1);
else
h = gobjects(2,1);
end
h(1) = surface(X, Y, Z, earth, ...
'FaceColor','texturemap', 'EdgeColor','none');
h(2) = surface(X*a, Y*a, Z*a, clouds, ...
'FaceColor','texturemap', 'EdgeColor','none', ...
'FaceAlpha','texturemap', 'AlphaData',max(clouds,[],3));
end
get_earth_sphere2.m
function h = get_earth_sphere2()
% load topographic data
S = load('topo.mat');
C = S.topo;
cmap = S.topomap1;
n = size(cmap,1);
% convert altitude data and colormap to RGB image
C = (C - min(C(:))) ./ range(C(:)); % scale to [0,1]
C = ind2rgb(round(C*(n-1)+1), cmap); % convert indexed to RGB
% unit sphere with 50x50 faces
[X,Y,Z] = sphere(50);
% render sphere with earth mapped onto the surface
h = surface(X, Y, Z, C, ...
'FaceColor','texturemap', 'EdgeColor','none');
end
The animation script is similar to before (with minor changes), so I'm not gonna repeat it. Here is the result:
(This time I'm using the new graphics system in R2014b)
I have a solution which renders ok by using texture mapping.
The idea is to apply an image to the face and let Matlab take care of everything else. The great advantage is that matlab will take care of all the perspective aspects, and the rendering is pretty good. The small disadvantage is that you can only apply texture to surface objects, and since you want 6 different images, you'll have to manage 6 different surfaces.
The code below shows an example of how to do it:
%% // read faces images
idxFaces = [1 2 3 4 5 6] ;
for iface = idxFaces
imgface{iface} = imread( ['E:\ICONS\number_blue_' num2str(iface) '-150x150.png'] ) ;
end
%% // Define cube properties
cubeLenght = 1 ;
x = linspace(-cubeLenght/2,cubeLenght/2,21) ;
[X,Y] = meshgrid(x,x) ;
Zp = ones(size(X))*cubeLenght/2 ; Zm = Zp-cubeLenght ;
%// draw face surfaces (organised 2 by 2)
hcubeface(1) = surf(X,Y,Zp ,'CData',imgface{1},'FaceColor','texturemap','LineStyle','none') ; hold on
hcubeface(6) = surf(X,Y,Zm ,'CData',imgface{6},'FaceColor','texturemap','LineStyle','none') ;
hcubeface(2) = surf(X,Zp,Y ,'CData',imgface{2},'FaceColor','texturemap','LineStyle','none') ;
hcubeface(5) = surf(X,Zm,Y ,'CData',imgface{5},'FaceColor','texturemap','LineStyle','none') ;
hcubeface(3) = surf(Zp,X,Y ,'CData',imgface{3},'FaceColor','texturemap','LineStyle','none') ;
hcubeface(4) = surf(Zm,X,Y ,'CData',imgface{4},'FaceColor','texturemap','LineStyle','none') ;
axis square
axis off
This will render the following figure:
Sorry for the actual images I took the first one I had available. You will have to generate a nice image of your cube faces, then apply them as shown above.
If you rotate your cube with the figure interactive tool, you will have no problem.
If you want to rotate it programatically, you have 2 options:
if the object is the only one displayed, then the easiest is to only move the point of view (using view or other camera manipulation functions).
if you have multiple objects and you only want to rotate your cube, then you will have to rotate each surface individually. In this case I would suggest writing a helper function which will rotate the 6 faces for you given an angle and a direction.
An even neater way would be to have your cube managed in a class, then add a method to rotate it (internally it will rotate the 6 faces).
Edit: just for fun, the snippet below will animate your dice (not the pretiest way but it shows you an example of the first option above).
%% // animate by changing point of view
azi = linspace(-180,180,100) ;
for iv =1:100
view(azi(iv),azi(iv)+randi(5))
pause(0.01)
end
view(45,45)
Run this block to see your dice dancing ;)
Edit (again)
And this is an example on how to animate the cube object by rotating the object itself
%% // animate by rotating the object
%// this is necessary because the first rotation reset the axes to shading interp
rotate(hcubeface , [0 1 1] , 0.5)
for iface = 1:6 ; set( hcubeface(iface) , 'CData',imgface{iface}, 'FaceColor','texturemap' ) ; end
%// after that, no need to reset the texture map, enjoy as many rotations as you like
for iv =1:360
axerot = rand(1,3) ; % // pick a random axis to rotate around
rotate(hcubeface , axerot , 0.5) %// rotate the 6 faces by 0.5 degrees
pause(0.01)
end
Note that I modified the definition of the cube in order to have all the face surfaces handles in one array. This allow to apply the rotate command to all the surfaces in one go just by sending the handle array as parameter.
Suppose i would like to draw an image like the following:
Where the pixel values are refined to 0 for black and white for 1.
These line are drawn with specific radius and angles
Now I create a 80 x 160 matrix
texturematrix = zeros(80,160);
then i want to change particular elements to be 1 according to the lines conditions
but how do i make them repeatedly with specific distance apart from each others effectively?
Thanks a lot everyone!
This might not be what you are looking for, but generating such an image could be done by plotting a set of lines, as follows:
% grid sizes
m = 6;
n = 5;
% line length and angle
len = 1;
theta = .1*pi;
[a,b] = meshgrid(1:m,1:n);
x = reshape([a(:),a(:)+len*cos(theta),nan(numel(a),1)]',[],1);
y = reshape([b(:),b(:)+len*sin(theta),nan(numel(b),1)]',[],1);
h = figure();
plot(x,y,'k', 'LineWidth', 2);
But this has nothing to do with a texture matrix. So, we construct a matrix of desired size:
set(gca, 'position',[0 0 1 1], 'units','normalized', 'YTick',[], 'XTick',[]);
frame = frame2im(getframe(h),[0 0 1 1]);
im = imresize(frame,[80 160]);
M = ~(im(2:end,2:end,1)==255);
I have an image in MATLAB:
im = rgb2gray(imread('some_image.jpg');
% normalize the image to be between 0 and 1
im = im/max(max(im));
And I've done some processing that resulted in a number of points that I want to highlight:
points = some_processing(im);
Where points is a matrix the same size as im with ones in the interesting points.
Now I want to draw a circle on the image in all the places where points is 1.
Is there any function in MATLAB that does this? The best I can come up with is:
[x_p, y_p] = find (points);
[x, y] = meshgrid(1:size(im,1), 1:size(im,2))
r = 5;
circles = zeros(size(im));
for k = 1:length(x_p)
circles = circles + (floor((x - x_p(k)).^2 + (y - y_p(k)).^2) == r);
end
% normalize circles
circles = circles/max(max(circles));
output = im + circles;
imshow(output)
This seems more than somewhat inelegant. Is there a way to draw circles similar to the line function?
You could use the normal PLOT command with a circular marker point:
[x_p,y_p] = find(points);
imshow(im); %# Display your image
hold on; %# Add subsequent plots to the image
plot(y_p,x_p,'o'); %# NOTE: x_p and y_p are switched (see note below)!
hold off; %# Any subsequent plotting will overwrite the image!
You can also adjust these other properties of the plot marker: MarkerEdgeColor, MarkerFaceColor, MarkerSize.
If you then want to save the new image with the markers plotted on it, you can look at this answer I gave to a question about maintaining image dimensions when saving images from figures.
NOTE: When plotting image data with IMSHOW (or IMAGE, etc.), the normal interpretation of rows and columns essentially becomes flipped. Normally the first dimension of data (i.e. rows) is thought of as the data that would lie on the x-axis, and is probably why you use x_p as the first set of values returned by the FIND function. However, IMSHOW displays the first dimension of the image data along the y-axis, so the first value returned by FIND ends up being the y-coordinate value in this case.
This file by Zhenhai Wang from Matlab Central's File Exchange does the trick.
%----------------------------------------------------------------
% H=CIRCLE(CENTER,RADIUS,NOP,STYLE)
% This routine draws a circle with center defined as
% a vector CENTER, radius as a scaler RADIS. NOP is
% the number of points on the circle. As to STYLE,
% use it the same way as you use the rountine PLOT.
% Since the handle of the object is returned, you
% use routine SET to get the best result.
%
% Usage Examples,
%
% circle([1,3],3,1000,':');
% circle([2,4],2,1000,'--');
%
% Zhenhai Wang <zhenhai#ieee.org>
% Version 1.00
% December, 2002
%----------------------------------------------------------------
Funny! There are 6 answers here, none give the obvious solution: the rectangle function.
From the documentation:
Draw a circle by setting the Curvature property to [1 1]. Draw the circle so that it fills the rectangular area between the points (2,4) and (4,6). The Position property defines the smallest rectangle that contains the circle.
pos = [2 4 2 2];
rectangle('Position',pos,'Curvature',[1 1])
axis equal
So in your case:
imshow(im)
hold on
[y, x] = find(points);
for ii=1:length(x)
pos = [x(ii),y(ii)];
pos = [pos-0.5,1,1];
rectangle('position',pos,'curvature',[1 1])
end
As opposed to the accepted answer, these circles will scale with the image, you can zoom in an they will always mark the whole pixel.
Hmm I had to re-switch them in this call:
k = convhull(x,y);
figure;
imshow(image); %# Display your image
hold on; %# Add subsequent plots to the image
plot(x,y,'o'); %# NOTE: x_p and y_p are switched (see note below)!
hold off; %# Any subsequent plotting will overwrite the image!
In reply to the comments:
x and y are created using the following code:
temp_hull = stats_single_object(k).ConvexHull;
for k2 = 1:length(temp_hull)
i = i+1;
[x(i,1)] = temp_hull(k2,1);
[y(i,1)] = temp_hull(k2,2);
end;
it might be that the ConvexHull is the other way around and therefore the plot is different. Or that I made a mistake and it should be
[x(i,1)] = temp_hull(k2,2);
[y(i,1)] = temp_hull(k2,1);
However the documentation is not clear about which colum = x OR y:
Quote: "Each row of the matrix contains the x- and y-coordinates of one vertex of the polygon. "
I read this as x is the first column and y is the second colum.
In newer versions of MATLAB (I have 2013b) the Computer Vision System Toolbox contains the vision.ShapeInserter System object which can be used to draw shapes on images. Here is an example of drawing yellow circles from the documentation:
yellow = uint8([255 255 0]); %// [R G B]; class of yellow must match class of I
shapeInserter = vision.ShapeInserter('Shape','Circles','BorderColor','Custom','CustomBorderColor',yellow);
I = imread('cameraman.tif');
circles = int32([30 30 20; 80 80 25]); %// [x1 y1 radius1;x2 y2 radius2]
RGB = repmat(I,[1,1,3]); %// convert I to an RGB image
J = step(shapeInserter, RGB, circles);
imshow(J);
With MATLAB and Image Processing Toolbox R2012a or newer, you can use the viscircles function to easily overlay circles over an image. Here is an example:
% Plot 5 circles at random locations
X = rand(5,1);
Y = rand(5,1);
% Keep the radius 0.1 for all of them
R = 0.1*ones(5,1);
% Make them blue
viscircles([X,Y],R,'EdgeColor','b');
Also, check out the imfindcircles function which implements the Hough circular transform. The online documentation for both functions (links above) have examples that show how to find circles in an image and how to display the detected circles over the image.
For example:
% Read the image into the workspace and display it.
A = imread('coins.png');
imshow(A)
% Find all the circles with radius r such that 15 ≤ r ≤ 30.
[centers, radii, metric] = imfindcircles(A,[15 30]);
% Retain the five strongest circles according to the metric values.
centersStrong5 = centers(1:5,:);
radiiStrong5 = radii(1:5);
metricStrong5 = metric(1:5);
% Draw the five strongest circle perimeters.
viscircles(centersStrong5, radiiStrong5,'EdgeColor','b');
Here's the method I think you need:
[x_p, y_p] = find (points);
% convert the subscripts to indicies, but transposed into a row vector
a = sub2ind(size(im), x_p, y_p)';
% assign all the values in the image that correspond to the points to a value of zero
im([a]) = 0;
% show the new image
imshow(im)