i found a example from %AHMADREZA ESHGHINEJAD () of a bouncing ball on a sinusoidal surface and tried to modify it to fit my model.
but matlab shows an error while calling the "graphicfunction" without any further information. i've been trying to figure out for hours trying to fix it, but it still does not work.
i would really appreciate your help.
main
%This set of files including (Rmain.m, RCalc.m, RGraficfunction.m and Rod.mdl) are written by:
%AHMADREZA ESHGHINEJAD (ahmadreza.eshghinejad#gmail.com), April 2011
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% to simulate and animation of a rod falling on a flat surface.
%
%clear
%clc
%global dblcart1 pa dt amp freq I m floormin floorwidth s R
spacing_width=0.001; %[m]
spacing_amplitude=0.008; %[m]
%disc diameter
d=0.01; %[m]
r=d/2; %Radius
x0=0; %% initial x
y0=spacing_amplitude; %% initial y
Bth0=0; %% initial angular position
pa=.001; %% pause in simulation step
T=30; %% simulation time
m=1; %% ball mass
dt=.01; % time steps
s=0; % Movement of frame counter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
animinit('disc on surface');
dblcart1 = findobj('Type','figure','Name','dblcart1 Animation');
hold on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Initializing
% Initial Ball points
th=0:.1:2*pi;
xx=r*cos(th)+x0;
yy=r*sin(th)+y0;
% Initial Ball line points
x1l1=1*r*cos(Bth0)+x0;
x1l2=1*r*cos(Bth0+pi)+x0;
y1l1=1*r*sin(Bth0)+y0;
y1l2=1*r*sin(Bth0+pi)+y0;
x2l1=1*r*cos(Bth0+pi/2)+x0;
x2l2=1*r*cos(Bth0+pi+pi/2)+x0;
y2l1=1*r*sin(Bth0+pi/2)+y0;
y2l2=1*r*sin(Bth0+pi+pi/2)+y0;
% Drawing the floor
floormin=0;
floorwidth=3*2*pi*spacing_width;
floorheight=floorwidth;
axis([floormin floormin+floorwidth 0 floorheight]);
plot(floormin:.1:floormin+floorwidth,spacing_amplitude*sin((1/spacing_width)* (floormin:.1:floormin+floorwidth))+spacing_amplitude,'yellow','LineWidth',2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initial drawing of ball
Ballhndl1=plot([x1l1 x1l2],[y1l1 y1l2],'red');
Ballhndl2=plot([x2l1 x2l2],[y2l1 y2l2],'red');
Ballhndl=plot(xx,yy,'blue','EraseMode','background');
set(gca,'UserData',[Ballhndl;Ballhndl1;Ballhndl2]);
%set(gca,'UserData',Ballhndl);
sim('simmod.mdl')
matlab function inside the simulink model
function [x,y,Bth] = fcn(ures,yres)
r=0.01; %% Ball radius
spacing_width=0.001; %[m]
spacing_amplitude=0.008; %[m]
for th=2*pi:-.01:0
x=ures+r*cos(th); %% bal points
y=yres+r*sin(th);
end;
Bth=atan(2*pi*(1/spacing_width)*spacing_amplitude*cos(2*pi*(1/spacing_width)*x));
graphic function
function GraficFunction(x,y,Bth)
global Ball
spacing_width=0.001; %[m]
pa=.01; %% pause in simulation step
s=0; % Movement of frame counter
floormin=0;
floorwidth=3*2*pi*spacing_width;
pause(pa)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% passing the window margins and moving the object based on the "s"
%%%%% parameter
if x<(floormin+s*floorwidth),s=s-1;
elseif x>((s+1)*floorwidth),s=s+1;end
x=x-s*floorwidth;
set(0,'currentfigure',Ball)
Ballhndl=get(gca,'UserData');
%Ball Circle points
th=0:.1:2*pi;
x1=ures+r*cos(th);
y1=yres+r*sin(th);
%%%%%%%%%%%%%% Ball line points
x1l1=1*r*cos(Bth)+x;
x1l2=1*r*cos(Bth+pi)+x;
y1l1=1*r*sin(Bth)+y;
y1l2=1*r*sin(Bth+pi)+y;
x2l1=1*r*cos(Bth+pi/2)+x;
x2l2=1*r*cos(Bth+pi+pi/2)+x;
y211=1*r*sin(Bth+pi/2)+y;
y2l2=1*r*sin(Bth+pi+pi/2)+y;
% Draw Lines
set(Ballhndl(1),'XData',x1);
set(Ballhndl(1),'YData',y1);
set(Ballhndl,'XData',x1);
set(Ballhndl,'YData',y1);
set(Ballhndl(2),'XData',[x1l1 x1l2]);
set(Ballhndl(2),'YData',[y1l1 y1l2]);
set(Ballhndl(3),'XData',[x2l1 x2l2]);
set(Ballhndl(3),'YData',[y2l1 y2l2]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
drawnow;
end
Related
I am running a MATLAB code which produces a discrete element simulation at the end of the code. The code produces a simulation of particle locations as shown in the figure below. Currently, the code to produce this simulation is running incredibly slow. The simulation is slow to the point that's it's not practical to watch it. I put the movie part of the code below, does anyone have ideas to speed this part of the code up? Also, does anyone know how to control the pace at which MATLAB plots the circles and lines in the code?
Thanks
%% Movie Output
if SkipMovie == 1
Start = 1;
INTMOVIE = 1;
End = NT;
for TimeStep = Start:INTMOVIE:End % For 1 to the number of time steps at interval INTMOVIE
dim = [0.15,.95,.25,.06]; % Location of Time Step Text Box
str = {sprintf(sprintf('TimeStep = %3.2f',TimeStep))}; % Text in Time Step Text Box
annotation('textbox', dim, 'String', str,'BackgroundColor','w'); % Draw text box
for j = 1:NP % for 1 to the number of particles
th = 0:pi/50:2*pi;
x_circle = R(j) * cos(th) + LPart(j,1,TimeStep); %LPart gives the x/y postition of particle j at the corresponding time step
y_circle = R(j) * sin(th) + LPart(j,2,TimeStep);
plot(x_circle, y_circle); % Draw a circle for particle j
fill(x_circle, y_circle, colorP) % Fill circle for particle j
hold on;
GW1 = plot(LWall(1,1:2),LWall(1,3:4),['-',colorW]); % Draw Wall 1
GW2 = plot(LWall(2,1:2),LWall(2,3:4),['-',colorW]); % Draw Wall 2
GW3 = plot(LWall(3,1:2),LWall(3,3:4),['-',colorW]); % Draw Wall 3
GW4 = plot(LWall(4,1:2),LWall(4,3:4),['-',colorW]); % Draw Wall 4
GW5 = plot(LWall(5,1:2),LWall(5,3:4),['-',colorW]); % Draw Wall 5
GW6 = plot(LWall(6,1:2),LWall(6,3:4),['-',colorW]); % Draw Wall 6
set(GW1(1),'LineWidth',2); % Set Line Width of Wall 1
set(GW2(1),'LineWidth',2); % Set Line Width of Wall 2
set(GW3(1),'LineWidth',2); % Set Line Width of Wall 3
set(GW4(1),'LineWidth',2); % Set Line Width of Wall 4
set(GW5(1),'LineWidth',2); % Set Line Width of Wall 5
set(GW6(1),'LineWidth',2); % Set Line Width of Wall 6
axis([xdim1,xdim2,ydim1,ydim2]); % Set viewing window of plot
end
FF = getframe; % Save the plotted frame to FF
hold off; % Hold current frame until items for next frame are drawn (not sure if this is needed)
clf; % clear frame before loops repeat
end
movie(FF,repeat,1) % Create movie based on frame FF
end
I have a image of fuel spray and i want to find the angle of the fuel spray. One of the research papers I was reading tells me that I can find the angle using the area at half length of the spray and I've been trying to find the area at half length for a couple of weeks right now.
The code below shows what I tried. I've also tried other methods such as trimming out all the non zero elements and just calculating the angle from the end of the spray. Since that is giving me an inaccurate answer, I'm here looking for help.
img_subt_binary= imbinarize(img_subt);
BW2= BiggestImageOnly(img_subt_binary);% Clear out all white areas that have less than 175 pixels.
% figure(2),imshow(BW2),
% title('Filtered Binary Image')
% [pixelCount, grayLevels] = imhist(BW2);
% figure(3)
% bar(grayLevels, pixelCount);
[the_length,the_width]=size(BW2)
%% Spray Angle
half_length=the_length/2;
for j=1:half_length
j=j+1;
[LL(j),WW(j)]= size(BW2);
final_width=max(WW);
end
angle= atan(final_width/half_length)
I'm expecting the spray angle to be around 20 degrees.
To get a better estimation of the change in width (spray angle) you might want to fit a line across the entire image
[h w] = size(BW2);
margin = ceil(h/10); % ignore top/bottom parts
row_width = sum(BW2(margin:end-margin,:), 2); % number of white pixel in each row
x = 1:numel(row_width);
pp = polyfit(x, row_width.', 1); % fit a line
% see the line
figure;
plot(row_width);
hold all;
plot(x, x*pp(1) + pp(2));
% get the angle (in degrees)
angle = atan(pp(1)) * 180 / pi
The estimated angle is
7.1081
The plot:
I am a student just learning about matlab, im using the version R2014a student.
I need to use a webcam to detect 3 squares (2cm x 2 cm each one) that will be randomly colocated. I must have the position and it's centroid for each of the 3 squares, I must have the position and orientation (the relative angle to the x axis of the image) and I should ve able to constantly detect them.
The webcam is set to a fixed position, and I need to know which is the distance I've got from each square to it's relative position at the board.
The code I have so far is the following: (currently I am not able to detect them properly and I cannot know the distance)
vid=videoinput('winvideo', 1)
preview(vid)
constantlydoing =1
while constantlydoing>=1
%Sacar fotografía del tablero (obtain a photo of the board)
image=getsnapshot(vid);
imshow(image)
%Conversión BW
level = graythresh(image);
imageBW = im2bw(image,level);
imageBW= not (imageBW);
imshow(imageBW);
L = bwlabel(imageBW,8);
imshow(L);
pause(1);
s=regionprops(L, 'centroid');
centroids = cat(1, s.Centroid);
j=regionprops(L, 'Perimeter');
k=regionprops(L, 'orientation');
orientations = cat(1, k.Orientation);
%determinamos perímetro (perimeter detect)
perimetro = cat(1, j.Perimeter);
[m,n]= size(perimetro);
pos=find(perimetro(:,1)>=100);
centroids=[centroids(pos(1),1) centroids(pos(1),2);...
centroids(pos(2),1) centroids(pos(2),2);...
centroids(pos(3),1) centroids(pos(3),2)];
%orientacion (orientation)
orientations=[orientations(pos(1),1);...
orientations(pos(2),1) ;...
orientations(pos(3),1)]
%Localización de los cubos (localization of squares)
cubo1=centroids(1,1:2);
cubo2=centroids(2,1:2);
cubo3=centroids(3,1:2);
hold on;
plot(centroids(:,1),centroids(:,2),'b*');
hold off;
propied=regionprops(L,'BoundingBox');
hold on
% Plot Bounding Box
for n=1:size(propied,1)
rectangle('Position',propied(n).BoundingBox ...
,'EdgeColor','g','LineWidth',2); ...
end
hold off
pause(1);
end
I have a list of 2D points (x1,y1),(x2,y2)......(Xn,Yn) representing a curved segment, is there any formula to determine whether the direction of drawing that segment is clockwise or anti clockwise ?
any help is appreciated
Alternately, you can use a bit of linear algebra. If you have three points a, b, and c, in that order, then do the following:
1) create the vectors u = (b-a) = (b.x-a.x,b.y-a.y) and v = (c-b) ...
2) calculate the cross product uxv = u.x*v.y-u.y*v.x
3) if uxv is -ve then a-b-c is curving in clockwise direction (and vice-versa).
by following a longer curve along in the same manner, you can even detect when as 's'-shaped curve changes from clockwise to anticlockwise, if that is useful.
One possible approach. It should work reasonably well if the sampling of the line represented by your list of points is uniform and smooth enough, and if the line is sufficiently simple.
Subtract the mean to "center" the line.
Convert to polar coordinates to get the angle.
Unwrap the angle, to make sure its increments are meaningful.
Check if total increment is possitive or negative.
I'm assuming you have the data in x and y vectors.
theta = cart2pol(x-mean(x), y-mean(y)); %// steps 1 and 2
theta = unwrap(theta); %// step 3
clockwise = theta(end)<theta(1); %// step 4. Gives 1 if CW, 0 if ACW
This only considers the integrated effect of all points. It doesn't tell you if there are "kinks" or sections with different directions of turn along the way.
A possible improvement would be to replace the average of x and y by some kind of integral. The reason is: if sampling is denser in a region the average will be biased towards that, whereas the integral wouldn't.
Now this is my approach, as mentioned in a comment to the question -
Another approach: draw a line from starting point to ending point. This line is indeed a vector. A CW curve has most of its part on RHS of this line. For CCW, left.
I wrote a sample code to elaborate this idea. Most of the explanation can be found in comments in the code.
clear;clc;close all
%% draw a spiral curve
N = 30;
theta = linspace(0,pi/2,N); % a CCW curve
rho = linspace(1,.5,N);
[x,y] = pol2cart(theta,rho);
clearvars theta rho N
plot(x,y);
hold on
%% find "the vector"
vec(:,:,1) = [x(1), y(1); x(end), y(end)]; % "the vector"
scatter(x(1),y(1), 200,'s','r','fill') % square is the starting point
scatter(x(end),y(end), 200,'^','r','fill') % triangle is the ending point
line(vec(:,1,1), vec(:,2,1), 'LineStyle', '-', 'Color', 'r')
%% find center of mass
com = [mean(x), mean(y)]; % center of mass
vec(:,:,2) = [x(1), y(1); com]; % secondary vector (start -> com)
scatter(com(1), com(2), 200,'d','k','fill') % diamond is the com
line(vec(:,1,2), vec(:,2,2), 'LineStyle', '-', 'Color', 'k')
%% find rotation angle
dif = diff(vec,1,1);
[ang, ~] = cart2pol(reshape(dif(1,1,:),1,[]), reshape(dif(1,2,:),1,[]));
clearvars dif
% now you can tell the answer by the rotation angle
if ( diff(ang)>0 )
disp('CW!')
else
disp('CCW!')
end
One can always tell on which side of the directed line (the vector) a point is, by comparing two vectors, namely, rotating vector [starting point -> center of mass] to the vector [starting point -> ending point], and then comparing the rotation angle to 0. A few seconds of mind-animating can help understand.
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)