Given a CGPath, how to make it curve? - iphone

In the following screen shot:
when you drag the tail of the word balloon (the thing that connects from the balloon to the persons mouth), the shape curves (as illustrated by the difference between the two balloon tails in the picture). I'm wondering, how is this done? I'm assuming you need to start with a CGPath and do something to it, does anyone happen to know what this is?
Update: So if I wanted to curve the following shape:
Would I use the following code:
CGPathAddCurveToPoint(mutablePath, NULL, x1, y1, x2, y2 + constant, x5, y5);
CGPathAddCurveToPoint(mutablePath, NULL, x3, y3, x4, y4 + constant, x5, y5);
Where the constant readjusts the y position of point 2 and point 4 to make the curve?

You need to exploit the fact that, mathematically, a straight-line segment is just a kind of curve segment.
(It's easier than it sounds, trust me.)
Bézier path segments have something called “order” that essentially determines how many points there are in the segment, not counting the point you're coming from.
A straight-line segment is a first-order curve, meaning that it only has the destination point. These “curves” are always straight lines because there are no control points to curve toward.
Quadratic curves are second-order curves (one control point plus the destination).
Cubic curves are third-order curves (two control points).
(The math doesn't put any limit on this, but Quartz stops here. No fourth-order curves for you without rolling your own rasterizer.)
This matters because any lower-order curve—including a straight line—can be expressed as a higher-order curve.
So, the secret?
For even a straight tail, use a curve.
(Namely, a cubic curve, since you want the curve going in two different directions: One, more or less into the tail, and the other, more or less along the edge of the balloon.)
From each of the two points at the base of the tail, you want one of the control points to be about halfway to the destination. This much is unconditional.
The direction of each of the control points gives you three options:
The straight-out tail
Notice the two control points along the blue line at the vertical center of the image.
Notice the direction of these two control points, relative to the base point it's connected to. They are angled inward, toward the tip—indeed, exactly on the straight line to the tip.
The oblique tail
Here, the tip point is no longer horizontally between the two base points. The control points have moved, but only to follow: each one is still halfway along the straight line between the corresponding base point and the tip.
The curved tail
For a curved tail, you move the tip, but you keep the control points at the same position as for a straight tail. Thus, the tail starts out straight out (following the control points), but as it gets farther from the base points, their influence wanes, and the tail begins curving toward the tip.
This is a lot easier to describe visually than to put into code, so you may want to consider using something like PaintCode or Opacity to draw each kind of tail using a pen tool and then see what the code they generate for it looks like.

You can use the CGContextAddCurveToPoint() functions:
CGContextMoveToPoint(ctx, x, y);
CGContextAddCurveToPoint(ctx, outTangentX, outTangentY, inTangentX, inTangentY, newX, newY);
... // more points or whatever you need here
CGContextFillPath(ctx); // Fill with white
CGContextStrokePath(ctx); // stroke the edges with black
The in/out tangents can be hardcoded to be something that looks good based on the point on the mouth of the picture and the point where it meets the balloon bubble. You might try something like making their angles half-way between perpendicular and the slope of the straight line between the 2 points or something like that as a starting place.

Related

Is it possible to find the depth of an internal point of an object using stereo images (or any other method)?

I have image of robot with yellow markers as shown
The yellow points shown are the markers. There are two cameras used to view placed at an offset of 90 degrees. The robot bends in between the cameras. The crude schematic of the setup can be referred.
https://i.stack.imgur.com/aVyDq.png
Using the two cameras I am able to get its 3d co-ordinates of the yellow markers. But, I need to find the 3d-co-oridnates of the central point of the robot as shown.
I need to find the 3d position of the red marker points which is inside the cylindrical robot. Firstly, is it even feasible? If yes, what is the method I can use to achieve this?
As a bonus, is there any literature where they find the 3d location of such internal points which I can refer to (I searched, but could not find anything similar to my ask).
I am welcome to a theoretical solution as well(as long as it assures to find the central point within a reasonable error), which I can later translate to code.
If you know the actual dimensions, or at least, shape (e.g. perfect circle) of the white bands, then yes, it is feasible and possible.
You need to do the following steps, which are quite non trivial to do, and I won't do them here:
Optional but extremely suggested: calibrate your camera, and
undistort it.
find the equation of the projection of a 3D circle into a 2D camera, for any given rotation. You can simplify this by assuming the white line will be completely horizontal. You want some function that takes the parameters that make a circle and a rotation.
Find all white bands in the image, segment them, and make them horizontal (rotate them)
Fit points in the corrected white circle to the equation in (1). That should give you the parameters of the circle in 3d (radious, angle), if you wrote the equation right.
Now that you have an analytic equation of the actual circle (equation from 1 with parameters from 3), you can map any point from this circle (e.g. its center) to the image location. Remember to uncorrect for the rotations in step 2.
This requires understanding of curve fitting, some geometric analytical maths, and decent code skills. Not trivial, but this will provide a solution that is highly accurate.
For an inaccurate solution:
Find end points of white circles
Make line connecting endpoints
Chose center as mid point of this line.
This will be inaccurate because: choosing end points will have more error than fitting an equation with all points, ignores cone shape of view of the camera, ignores geometry.
But it may be good enough for what you want.
I have been able to extract the midpoint by fitting an ellipse to the arc visible to the camera. The centroid of the ellipse is the required midpoint.
There will be wrong ellipses as well, which can be ignored. The steps to extract the ellipse were:
Extract the markers
Binarise and skeletonise
Fit ellipse to the arc (found a matlab function for this)
Get the centroid of the ellipse
hsv_img=rgb2hsv(im);
bin=new_hsv_img(:,:,3)>marker_th; %was chosen 0.35
%skeletonise
skel=bwskel(bin);
%use regionprops to get the pixelID list
stats=regionprops(skel,'all');
for i=1:numel(stats)
el = fit_ellipse(stats(i).PixelList(:,1),stats(i).PixelList(:,2));
ellipse_draw(el.a, el.b, -el.phi, el.X0_in, el.Y0_in, 'g');
The link for fit_ellipse function
Link for ellipse_draw function

Can I compute contour orientation without using polygon area sign?

Most of the times, I determine contour orientation generating 2D points and computing the closed polygon area. Depending on the area value sign I can understand if the contour is oriented clockwise or not (see How to determine if a list of polygon points are in clockwise order?).
Would it be possible to do the same computations without generating 2D points? I mean, relying only on geometric curve properties?
We are interested in determining the orientation of contours like these ones without sampling them with 2D points.
EDIT: Some interesting solutions can be found here:
https://math.stackexchange.com/questions/423718/general-way-to-find-out-whether-a-curve-is-positively-oriented
Scientific paper: Determining the orientation of closed planar curves, DJ Filip (1990)
How are those geometric curves defined?
Do you have an angle for them? The radius doesn't matter, only the difference between entry-angle and exit-angle of each curve.
In that case, a trivial idea crossing my mind is to just sum up all the angles. If the result is positive, you know you had more curves towards the right meaning it's a clockwise contour. If it was negative, then more curves were leftwards -> anti-clockwise contour. (assuming that positive angels determine a right-curve and vica versa)
After thinking about this for awhile, for polygons that contain arcs I think there are three ways to do this.
One, is to break the arcs into line segments and then use the area formula as described above. The success of this approach seems to be tied to how close the interpolation of the arcs is as this could cause the polygon to intersect itself.
A quicker way than the above would be to do the interpolation of the arcs and then find a vertex in the corner (minimal Y, if tie minimal X) and use the sign of the cross product for that vertex. Positive CCW, negative CW. Again, this is still tied to the accuracy of the interpolation.
I think a better approach would be to find the midpoint of the arc and create two line segments, one from the beginning of the arc to the midpoint and another from the midpoint to the end of the arc and replace the arc with these line segments. Now you have a polygon with only line segments. Then you can add up all the normalized cross products of all the vertices. The sign will tell you the direction. Positive is counter-clockwise, negative is clockwise. In this case it doesn't matter if the polygon self-intersects.

Oriented Bounding Box algorithm, Need some understanding/clarification of a few lines of existing (working) code

I am reviewing some MATLAB code that is publicly available at the following location:
https://github.com/mattools/matGeom/blob/master/matGeom/geom2d/orientedBox.m
This is an implementation of the rotating calipers algorithm on the convex hull of a set of points in order to compute an oriented bounding box. My review was to understand intuitively how the algorithm works however I seek clarification on certain lines within the file which I am confused on.
On line 44: hull = bsxfun(#minus, hull, center);. This appears to translate all the points within the convex hull set so the calculated centroid is at (0,0). Is there any particular reason why this is performed? My only guess would be that it allows straightforward rotational transforms later on in the code, as rotating about the real origin would cause significant problems.
On line 71 and 74: indA2 = mod(indA, nV) + 1; , indB2 = mod(indB, nV) + 1;. Is this a trick in order to prevent the access index going out of bounds? My guess is to prevent out of bounds access, it will roll the index over upon reaching the end.
On line 125: y2 = - x * sit + y * cot;. This is the correct transformation as the code behaves properly, but I am not sure why this is actually used and different from the other rotational transforms done later and also prior (with the calls to rotateVector). My best guess is that I am simply not visualizing what rotation needs to be done in my head correctly.
Side note: The external function calls vectorAngle, rotateVector, createLine, and distancePointLine can all be found under the same repository, in files named after the function name (as per MATLAB standard). They are relatively uninteresting and do what you would expect aside from the fact that there is normalization of vector angles going on.
I'm the author of the above piece of code, so I can give some explanations about it:
First of all, the algorithm is indeed a rotating caliper algorithm. In the current implementation, only the width of the algorithm is tested (I did not check the west and est vertice). Actually, it seems the two results correspond most of the time.
Line 44 -> the goal of translating to origin was to improve numerical accuracy. When a polygon is located far away from the origin, coordinates may be large, and close together. Many computation involve products of coordinates. By translating the polygon around the origin, the coordinates are smaller, and the precision of the resulting products are expected to be improved. Well, to be honest, I did not evidenced this effect directly, this is more a careful way of coding than a fix…
Line 71-74! Yes. The idea is to find the index of the next vertex along the polygon. If the current vertex is the last vertex of the polygon, then the next vertex index should be 1. The use of modulo rescale between 0 and N-1. The two lines ensure correct iteration.
Line 125: There are several transformations involved. Using the rotateVector() function, one simply computes the minimal with for a given edge. On line 125, one rotate the points (of the convex hull) to align with the “best” direction (the one that minimizes the width). The last change of coordinates (lines 132->140) is due to the fact that the center of the oriented box is different from the centroid of the polygon. Then we add a shift, which is corrected by the rotation.
I did not really look at the code, this is an explanation of how the rotating calipers work.
A fundamental property is that the tightest bounding box is such that one of its sides overlaps an edge of the hull. So what you do is essentially
try every edge in turn;
for a given edge, seen as being horizontal, south, find the farthest vertices north, west and east;
evaluate the area or the perimeter of the rectangle that they define;
remember the best area.
It is important to note that when you switch from an edge to the next, the N/W/E vertices can only move forward, and are readily found by finding the next decrease of the relevant coordinate. This is how the total processing time is linear in the number of edges (the search for the initial N/E/W vertices takes 3(N-3) comparisons, then the updates take 3(N-1)+Nn+Nw+Ne comparisons, where Nn, Nw, Ne are the number of moves from a vertex to the next; obviously Nn+Nw+Ne = 3N in total).
The modulos are there to implement the cyclic indexing of the edges and vertices.

coordinates and heading direction relative to one point, rotating a map (MatLab)

I painted a scheme/diagram that makes it easier to understand my question. (The angles are for technical reasons 0° 90° 180° ... MSpaint won't rotate degreewise, but my data does). I need the B arrows relative to A, concerning the coordinate and relative angle. I subtract A's coordinates from A and B, now A always sits at (0,0) and B keeps its relative distance. How can I do that with the angles of the arrows?
The data I have is situation 1,2 and 3.
I have A and B's coordinates and directions. I need to translate/rotate/normalize/egocentric - whatever the right word might be, to get to situation 4,5 and 6 respectively. In the end, all data (4,5,6) pooled will look like 7, with the new coordinates and directions of B, because then A would always be in the center and heading up. I would believe that something like that might be used often in a different context and am hoping for a inline function or hint/topic to search in.

Drawing a bezier from multiple points

I have a set with 50 points in x,y. I need to draw the smoothest bezier that passes in all points, or in other words, the bezier that will best fit the points.
How do I do that? thanks
I am undergoing a similar problem in 3D. It is slightly easier in 2D because lines will always intersect if not parallel.
Firstly, read up on quadratic bezier curves. Each curve is represented by three points. The line will not pass through the middle point. Thus, your middle point cannot be one of the points you are trying to fit, or it won't go through it.
Instead, the beginning and end point of your quadratic bezier curve must be two consecutive points you want it to pass through. So what is your middle point going to be?
One way of solving this (never tried it myself HENCE it might not look perfect, but Im thinking off the top of my head) is to calculate the tangents from your -1st data point to your 0th data point, and find the intersection between that and the 1st data point to the 2nd data point. Then draw the line between the 0th data point and the 1st data point using this intersection as the middle bezier curve value.
Obviously you may have trouble at the ends of the curves, that may require some inventive thinking to make them look good. (the first point has no -1st point).
Sorry about the lack of diagrams. I would draw one but I'm on an iPad.
Imagine 3-point bezier curve (start-A, middle-B, end-C)
Imagine a straight line from A to C.
Imagine a straight line that is perpendicular to AC and goes through point B.
Those two lines cross in point D.
Bezier curve will go through EXACTLY half way from D to B. In other words if you want bezier curve that goes through 3 points, you must make the second point 2 times further from start and end than the actual second point.