select the most fitting road by sketching lines on the map - algorithm

I have a 2D road net data, which contains a lot of road points and the lines that link them.
I want to select a road(or several road) by drawing lines on the map, and the lines can be very inaccurate, I want to find the most fitting road. Is there any way to achieve this? Thanks.
========================================================================
UPDATE:
It's not a route searching problem, setting start point and end point and finding a best route.
What I want to do is, when user want to select a certain route on the map, he will draw a sketch line on the map like this:
and then the most fitting route can be found and highlighted like this:

1) Find the roads that link together
2) assign cost from one road to another road link (only the ones that are touching)
3) Pick up the ones with lowest cost - recursively

Related

OpenCV detect tennis court lines behind net

I'm trying to implement a tennis court detector using video recorded from the phone. I filmed it from the far corner of the tennis court.
The original image is like this.
Using OpenCV Canny Edge Detection and Hough Lines transformation, I'm able to detect the lines in my own half, but not the ones behind the net. How can I improve this process and get the undetected court lines?
The processed image is as below.
Updated on 2016-08-25
Thanks guys. I understand it makes sense to derive the court lines by fitting the detected lines to the model lines. I am not going to try combinatorial search to find the best lines to fit models. Therefore, I have been trying to separate the horizontal/vertical lines in order to reduce the computational complexity. I tried RANSAC in order to find vanishing points (VP) that associate two different groups of lines, but failed probably because of detection error(?).
The scatter plot of the line parameters in polar coordinates is as below. It is basically to classify the points into two groups: the top points that form a horizontal line; the down left points that also form a line with deep slope. Is there anyway to do that? Thanks
You don't need to detect the lines behind the net. You know the ground is a flat plane, you know the dimensions of each side of the court are the same - so you only need to detect the nearby lines and you can calculate where the missing lines are.
In fact you really only need to detect a single corner if you know the characteristics of the camera+lens.
In addition to Martin's comments, you might try using some kind of blur on the image before running your edge/line detection. With some tuning, you should be able to remove the signal of the net and maintain the court lines.
Another approach would be to reduce the thick lines to a single pixel by scanning the image left to right (for example) to detect transitions from red/green to white and back to red/green again. When this occurs, you can estimate that the midpoint of those two transitions is the midpoint of a court line. This would give you data you could feed directly into your Hough transform. This of course requires you to classify individual pixels as either court or line, which it seems like you aren't currently doing. This process can also be performed top-to-bottom to produce a second set of midpoint estimates.
For blurring, try a Bilateral filter
Example input image:
cv2.bilateralFilter(img_gray,30,25,75)
output image:

How to smooth area shape="poly" curves?

I am using image maps to provide the input for mouse over shading, nothing fancy here, but I've created polygons that have some sharp edges I'd prefer to see smoothed away.
At the same time I'd like to reduce the overall number of points by removing anything that would lie on a straight line, eg if points a, b and c fall on a straight line, remove point b.
Does anyone know of such an algorithm, preferably implemented in javascript?
We went down this path on a project once -- there is no other option than a whole mess of points. But from testing there doesn't seem to be any real issue with lots of points in the poly method and the size of the text (with all the numeric points) is nominal in the overall scope of HTML and supporting files.
So, as ugly as it looks in raw code, I recommend you just go ahead with the large number of points.

Indefinitely move objects around randomly without collision

I have an application where I need to move a number of objects around on the screen in a random fashion and they can not bump into each other. I'm looking for an algorithm that will allow me to generate the paths that don't create collisions and can continue for an indefinite time (i.e.: the objects keep moving around until a user driven event removes them from the program).
I'm not a game programmer but I think this looks like an AI problem and you guys probably solve it with your eyes closed. From what I've read A* seems to be the recommended 'basic idea' but I don't really want to invest a lot of time into it without some confirmation.
Can anyone shed some light on an approach? Anti-gravity movement maybe?
This is to be implemented on iOS, if that is important
New paths need to be generated at the end of each path
There is no visible 'grid'. Movement is completely free in 2D space
The objects are insects that walk around the screen until they are killed
A* is an algorithm to find the shortest path between a start and a goal configuration (in terms of whatever you define as short: common are e.g. euclidean distance, cost or time, angular distance...). Your insects seem not to have a specific goal, they don't even need a shortest path. I would certainly not go for A*. (By the way, since you are having a dynamic environment, D* would have been an idea - still it's meant to find a path from A to B).
I would tackle the problem as follows:
Random Paths and following them
For the random paths I see two methods. The first would be a simple random walk (click here to see a nice 2D animation with explanations), which can suffer from jittering and doesn't look too nice. The second one needs a little bit more detailed explanations.
For each insect generate four random points around them, maybe starting on a sinusoid. With a spline interpolation generate a smooth curve between those points. Take care of having C1 (in 2D) or C2 (in 3D) continuity. (Suggestion: Hermite splines)
With Catmull-Rom splines you can find your configurations while moving along the curve.
An application of a similar approach can be found in this blog post about procedural racetracks, also a more technical (but still not too technical) explanation can be found in these old slides (pdf) from a computer animations course.
When an insect starts moving, it can constantly move between the second and third point, when you always remove the first and append a new point when the insect reaches the third, thus making that the second point.
If third point is reached
Remove first
Append new point
Recalculate spline
End if
For a smoother curve add more points in total and move somewhere in the middle, the principle stays the same. (Personally I only used this in fixed environments, it should work in dynamic ones as well though.)
This can, if your random point generation is good (maybe you can use an approach similar to the one provided in the above linked blog post, or have a look at algorithms on the PCG Wiki), lead to smooth paths all over the screen.
Avoid other insects
To avoid other insects, three different methods come to my mind.
Bug algorithms
Braitenberg vehicles
An application of potential fields
For the potential fields I recommend reading this paper about dynamic motion planning (pdf). It's from robotics, but fairly easy to apply to your problem as well. You can just use the robots next spline point as the goal and set its velocity to 0 to apply this approach. However, it might be a bit too much for your simple game.
A discussion of Braitenberg vehicles can be found here (pdf). The original idea was more of a technical method (drive towards or away from a light source depending on how your motor is coupled with the photo receptor) and is often used to show how we apply emotional concepts like fear and attraction to other objects. The "fear" behaviour is an approach used for obstacle avoidance in robotics as well.
The third and probably simplest method are bug algorithms (pdf). I always have problems with the boundary following, which is a bit tricky. But to avoid another insect, these algorithms - no matter which one you use (I suggest Bug 1 or Tangent Bug) - should do the trick. They are very simple: Move towards your goal (in this application with the catmull-rom splines) until you have an obstacle in front. If the obstacle is close, change the insect's state to "obstacle avoidance" and run your bug algorithm. If you give both "colliding" insects the same turn direction, they will automatically go around each other and follow their original path.
As a variation you could just let them turn and recalculate a new spline from that point on.
Conclusion
Path finding and random path generation are different things. You have to experiment around what looks best for your insects. A* is definitely meant for finding shortest paths, not for creating random paths and following them.
You cannot plan the trajectories ahead of time for an indefinite duration !
I suggest a simpler approach where you just predict the next collision (knowing the positions and speeds of the objects allows you to tell if they will collide and when), and resolve it by changing the speed or direction of either objects (bounce before objects touch).
Make sure to redo a check for collisions in case you created an even earlier collision !
The real challenge in your case is to efficiently predict collisions among numerous objects, a priori an O(N²) task. You will accelerate that by superimposing a coarse grid on the play field and look at objects in neighboring cells only.
It may also be possible to maintain a list of object pairs that "might interfere in some future" (i.e. considering their distance and relative speed) and keep it updated. Checking that a pair may leave the list is relatively easy; efficiently checking for new pairs needing to enter the list is not.
Look at this and this Which described an AI program to auto - play Mario game.
So in this link, what the author did was using a A* star algorithm to guide Mario Get to the right border of the screen as fast as possible. Avoid being hurt.
So the idea is for each time frame, he will have an Environment which described the current position of other objects in the scene and for each action (up, down left, right and do nothing) , he calculate its cost function and made a decision of the next movement based on this.
Source: http://www.quora.com/What-are-the-coolest-algorithms
For A* you would need a 2D-Grid even if it is not visible. If I get your idea right you could do the following.
Implement a pathfinding (e.g. A*) then just generate random destination points on the screen and calculate the path. Once your insect reaches the destination, generate another destination point/grid-cell and proceed until the insect dies.
As I see it A* would only make sence if you have obstacles on the screen the insect should navigate around, otherwise it would be enough to just calculate a straight vector path and maybe handle collision with other insects/objects.
Note: I implemented A* once, later I found out that Lee's Algorithm
pretty much does the same but was easier to implement.
Consider a Hamiltonian cycle - the idea is a route that visits all the positions on a grid once (and only once). If you construct the cycle in advance (i.e. precalculate it), and set your insects off with some offset between them, they will never collide, simply because the path never intersects itself.
Also, for bonus points, Hamiltonian paths tend to 'wiggle about', and because it's a loop you can predict (and precalculate) the path into the indefinite future.
You can always use the nodes of the grid as knot points for a spline to smooth the movement, or even randomly shift all the points away from their strict 2d grid positions, until you have the desired motion.
Example Hamiltonian cycle from Wikimedia:
On a side note, if you want to generate such a path, consider constructing a loop through many points and just moving the points around in such a manner that they never intersect an existing edge. With some encouragement to move into gaps and away from each other, they should settle into some long, never-intersecting path. Store the result and use for your loop.

Find street intersections within an area in using Google Maps API

Given a square area, what is the best way to find the approximate coordinates of every street intersection within the given area ?
Since there is no description of your application, I can't tell if you need to use Google Maps or if another data source would answer your needs.
If http://openstreetmap.org fulfills the requirements of your application, then it's easy:
the OSM API has a request to pull data from a rectangular region. You get XML data.
filter this data to keep only the street you are interested in, probably the "key=highway" tags
filter this to keep only the points belonging to two or more lines.
Please disregard this if Google Maps is a requirement.
But still: since the roads exist independently of the database, the above method will yield roads intersections (in lat/long coordinates) with a pretty high correlation with what you would get from Google maps ;-) You can then use those points to display them over a Google map, knowing that both datasets aren't identical so it won't be perfect.
Might not be the easiest method but I used a seperate database of our countries roads with their linestrings.
I took the first and last points of each line string, then counted the number of roads within 50 m of each start/end point. I then took the nodes from navigation route and used these to compare the number of roads intersecting with each node. I then looked at the direction each start point and the next point along that road, which gives you direction. from that with a bit of maths you can work out the number and angle of the roads at the next intersection. I then made a road rules application that tells you which vehicles to give way to

What's the name of algorithm/field about positioning many small objects to form shapes?

sorry that English is not my native language. I would like to know what's the name of the algorithm/field about positioning small objects to form shapes?
I don't know what's the term for it, so let me give some examples.
e.g.1.
In cartoons, sometimes there will be a swarm of insects forming a skeleton head in the air
e.g.2.
In the wars in the 1700s, infantry units are a bunch of men standing together, forming columns or ranks, changing shapes as the battle rage on.
e.g.3
In opening ceremonies of Olympics, often there will be a bunch of dancers forming variou symbols on the field.
So bascally, numerous small objects beginning in arbitrary positions, moving to a new position such that they together form a shape in 2D or 3D.
What is such technique called?
In graphics, this would normally be called a "particle system" (and Googling for that should yield quite a few results that are at least reasonably relevant).
If you assume that the dancers/soldiers don't interfere when moving, then you can view the problem as a maximum matching problem.
For each person, you know their starting location, and you know the shape of the final pattern. You probably want to minimize the total time it takes to form the final shape from the start shape.
You can determine if it's possible to go from an initial state from a start state in time T by forming a bipartite graph. For each person and final position, if the person can reach the position in <= T, add an edge from the person to that position. Then run a maximum matching algorithm to see if everyone can find some position in the final locations within the time constraint.
Do a binary search on the time T and you'll have the minimum amount of time to go from one state to another.
http://en.wikipedia.org/wiki/Matching_(graph_theory)#Maximum_matchings_in_bipartite_graphs

Resources