Define if a contour is closed or not - java

I need a way to define if a contour represents a line or a closed shape. In Java, I have an object Shape which contains all the points which defines it again as separate objects. The object Point represents the coordinates of the point. I tried parsing the shapes with a recursion but for larger shapes, more then 150 points, the performance is very poor. I am attaching a picture of the shapes I want to parse to help better understand the question.
I am putting a image for better visualisation of the problem.
This is just showing all the shapes I got. I want to display just the two closed ones.
Thanks in advance.
Vassil Kossev

First idea: Use a suitable contour tracing algorithm to get an ordered contour. If your contour is closed you will get back to the first point eventually.
Second idea: Use a flood filling algorithm: if you get out of the bounding box of your object it is open, otherwise it is closed.
Third idea: use morphology. Remove lone pixels. Find all endpoints and branchpoints. Remove all branchpoints. Connected components with no endpoints are closed contours ("circles"), connected components with two endpoints are open contours ("lines"). Re-project connected components with no endpoints to the original image and keep only connected components that have common part with them. I think this could be implemented real-time, and the easiest to implement.

If you have contour lines of 1 pixel width, then you can count the number of neighbors for each point *. If every point of a given contour has 2 neighbors, then the contour is closed. If there are 2 points with only 1 neighbor each, then the contour is open.
If your contours are thicker, then you can apply a skeletonization algorithm to make them exactly 1 pixel thin. An interesting case is when you have side branches on a contour, but in this case there must be branching points with 3 neighbors, so similar situations can be handled easily.
* Counting neighbors is easy: use the original image! Choose one point of the contour randomly, check the neighboring 8 pixels, and count those which are part of the contour. Then repeat the neighbor-checking for these, and so on, until all pixels of the contour have been checked.

If the points are stored in order, you might be able to compare the first and last points. If they're spatially equal, the contour is closed.

Related

Overlapping check between two polygon

I have a two polygon shape draw using HTML5 canvas(GWT). I have all the points for two polygon shape. Means I have the list of points for draw this type of polygon.
Below image showing two polygon intersect or overlapping each other. Now I am searching for a solution how to find two polygon "intersect or not" using java? I am using pure java programming without using any third library.
I have another issue. For explaining this issue I am attaching another image below.
This is the another case when one Polygon inside of another Polygon. In this scenario how to calculate minimum distance between two polygon in negative?
Using Postgis Api Using You get Information That Two Polygon intersect or not . Find Following Link As Reference
http://www.postgis.net/docs/ST_Intersection.html
You can use the sweepline paradigm.
Consider the horizontal lines passing through the vertexes of either polygons. Two consecutive lines cut out slabs (trapezoids).
As the slabs are simple, convex polygons, checking them for intersection is straightforward: it suffices to detect overlap of the bases (mind the case where they form an X cross).
Now the whole process can be decomposed as
sorting the vertices of both polygons by increasing ordinates; for every vertex, remember to what polygon it belongs and what are its neighbors with a higher ordinate (none, one or two);
scanning the vertices by increasing ordinate, while maintaining a list of the edges that are intersected (it is called the active list). Every time you move to another vertex, update the active list;
testing the slabs for intersection.

The shortest connection algorithm, mind game

This is a question from a mind games book. I tried solving it like this (http://pastebin.com/sdfcuxW1) but had no luck. It also has to be very optimized to process outputs for 2000 input coordinates under 4 seconds.
Any suggestions about my code, or any new algorithm ideas would be very helpful.
Question:
We have a coordinate plane, and we are only using the first quadrant. We are supplied with a number of coordinates each with +X and +Y values. For example 0,2 - 5,4 etc. We are required to connect each of these coordinates with rectangles (one corner of the rectangle touches one coordinate and another corner touches another coordinate) so that all coordinates are in contact with each other (no left-outs). We also have to make sure that the rectangles that we use to connect our 2 coordinates do not overlap with any other coordinate (on the edges is fine). What kind of algorithm can print out the best solution to this problem, given that the goal is to use the smallest total rectangle area possible.
http://cl.ly/image/1P012s3p1E1g
purple areas are rectangles and green dots are coordinates. we can have rectangles which have 0 height of width, which consume no area.
What I couldn't figure out: find the closest coordinates to our starting coordinate is easy. but it is hard to make sure that all coordinates are connected together. i always get pieces of coordinates floating in different areas of the plane. my code also lags with >1000 points.
Here is a solution:
Let's model this problem as a graph problem.
The vertices are the given points.
There is an edge between every pair vertices. The weight of this edge is the area of the rectangle formed by this pair of points.
The answer is the minimum spanning tree in this graph. We can use Prim's algorithm to find it.
The time complexity of this solution is O(n ^ 2).
The only question is: why can't a rectangle generated by this algorithm contain another point? I will not post a formal proof here, but drawing some pictures shows that if there is such a rectangle, the solution is not optimal(an idea of a proof: let's assume that there is a point inside. We can split this rectangle into two so that this points becomes one of their corner. The total area can only decrease after performing this operation).

represent 2d pile of ball in java

I'm creating an application where I need to model (and display) a large number of 2-dimensional 'balls' (circles) using java. I've started by creating an ArrayList of Circle objects (a class that I defined, which has x/y pixel coordinates of the center of the circle, radius, color, and velocity in the x & y directions). I use a java.util.Timer object with a repeated TimerTask to control the motion of the circles. The circles vary in size from around 10-50 pixel radii.
What I want to happen is have balls fall from the top of the screen (randomly distributed across the x-axis) until they reach the bottom of the screen, which acts like a floor -- ball that reach it stop moving, and balls that reach stopped balls roll downhill on the other balls until they rest at a low/flat point. In the future I might want to make their behaviour a bit more complicated, so I want to create flexible code so I can easily expand. How it works right now is that every time period each circle check to see how close they are to every other circle. If there are no other circles nearby they continue falling normally. If two (or more) circles are close to each other there is code to determine how they will interact.
I have it working perfectly for small numbers of circles (< 200), but when I get larger numbers of circles (> 400) it starts slowing down significantly. I'm sure I can optimize some of the logic to make the comparisons a bit faster, but I was wondering if there are any ways of storing the circle in some structure besides an unorganized ArrayList that would let me easily find circles that are close to each other, so I don't have to do the N^2 operation of comparing each circle to every other one and, instead, just compare a circle to the 5-10 circles closest to it. For instance, I've considered using a 2D array to represent every pixel (or maybe square of 5x5 pixels) and store a circle where its center lies (so I could check if there are circles in any of the nearby cells, and ignore the rest). However, this still seems pretty inefficient as if I'm using a 800x1000 pixel canvas with 500 circles there would be a TON of empty spaces in the 2d array that I'd waste time checking. I've also considered some sort of hashmap, but I haven't thought of a great way to use that either.
So, can anyone think of an efficient way to store these circles that corresponds to it's location in 2d space and makes it easy to find nearby circles? Thanks in advance!
You can use a QuadTree to find close neighbours. Or you can simply sort by one direction, which would be far easier to implement and should still allow you to reduce the number of candidate neighbours to a small window.
Perhaps your idea of a 2D array is not so crazy. What I think you want is one List of all your circles, and a 2D array that would reference the circles also. So at each time, you can iterate over your List<Circle> to check each one. Each Circle has x,y coords and you only have to loop on your array for (x,y +/- 5). There is no need to check the whole possible space for Circles, because you already are keeping track of each Circle's center. Just grab the center, and check around it for other circles.

Getting boundary information from a 3d array

Hey, I'm currently trying to extract information from a 3d array, where each entry represents a coordinate in order to draw something out of it. The problem is that the array is ridiculously large (and there are several of them) meaning I can't actually draw all of it.
What I'm trying to accomplish then, is just to draw a representation of the outside coordinates, a shell of the array if you'd like. This array is not full, can have large empty spaces with only a few pixels set, or have large clusters of pixel data grouped together. I do not know what kind of shape to expect (could be a simple cube, or a complex concave mesh), and am struggling to come up with an algorithm to effectively extract the border. This array effectively stores a set of points in a 3d space.
I thought of creating 6 2d meshes (one for each side of the 3d array), and getting the shallowest point they can find for each position, and then drawing them separetly. As I said however, this 3d shape could be concave, which creates problems with this approach. Imagine a cone with a circle on top (said circle bigger than the cone's base). While the top and side meshes would get the correct depth info out of the shape, the bottom mesh would connect the base to the circle through vertical lines, making me effectivelly loose the conical shape.
Then I thought of annalysing the array slice by slice, and creating 2 meshes from the slice data. I believe this should work for any type of shape, however I'm struggling to find an algorithm which accuratly gives me the border info for each slice. Once again, if you just try to create height maps from the slices, you will run into problems if they have any concavities. I also throught of some sort of edge tracking algorithm, but the array does not provide continuous data, and there is almost certainly not a continuous edge along each slice.
I tried looking into volume rendering, as used in medical imaging and such, as it deals with similar problems to the one I have, but couldn't really find anything that I could use.
If anyone has any experience with this sort of problem, or any valuable input, could you please point me in the right direction.
P.S. I would prefer to get a closed representation of the shell, thus my earlier 2d mesh approach. However, an approach that simply gives me the shell points, without any connection between them, that would still be extremely helpful.
Thank you,
Ze
I would start by reviewing your data structure. As you observed, the array does not maintain any obvious spatial relationships between points. An octree is a pretty good representation for data like you described. Depending upon the complexity of you point set, you may be able to find the crust using just the octree - assuming you have some connectivity between near points.
Alternatively, you may then turn to more rigorous algorithms like raycasting or marching cubes.
Guess, it's a bit late by now to be truly useful to you, but for reference I'd say this is a perfect scenario for volumetric modeling (as you guessed yourself). As long as you know the bounding box of your point cloud, you can map these coordinates to a voxel space and increase the density (value) of each voxel for each data point. Once you have your volume fully defined, you can then use the Marching cubes algorithm to produce a 3D surface mesh for a given threshold value (iso value). That resulting surface doesn't need to be continuous, but will wrap all voxels with values > isovalue inside. The 2D equivalent are heatmaps... You can refine the surface quality by adjusting the iso threshold (higher means tighter) and voxel resolution.
Since you're using Java, you might like to take a look at my toxiclibs volumeutils library, which also comes with sevaral examples (for Processing) showing the general approach...
Imagine a cone with a circle on top
(said circle bigger than the cone's
base). While the top and side meshes
would get the correct depth info out
of the shape, the bottom mesh would
connect the base to the circle through
vertical lines, making me effectivelly
loose the conical shape.
Even an example as simple as this would be impossible to reconstruct manually, let alone algorithmically. The possibility of your data representing a cylinder with a cone shaped hole is as likely as the vertices representing a cone with a disk attached to the top.
I do not know what kind of shape to
expect (could be a simple cube...
Again, without further information on how the data was generated, 8 vertices arranged in the form of a cube might as well represent 2 crossed squares. If you knew that the data was generated by, for example, a rotating 3d scanner of some sort then that would at least be a start.

Connect the dots - connect the line between contour points

I have a gray scale image of 64x64. I found the dots of the contour by a simple algorithm:
find brightest spot (Example: 100)
divide by 2 (100/2 = 50)
define a band around the result (50-5=45 to 50+5=55)
mark all dots that have value in the band (between 45 to 55)
The question now is, how do I decide of the order of connecting the dots?
(All references will be accepted, links, thoughts, etc')
Your algorithm allows the entire image, save for one pixel, to be "the contour". I'm not sure that's exactly what you want; usually a contour is a border between two different regions. The problem with your method is that you can get huge blobs of pixels that have no particularly obvious traversal order. If you have a contour that is a single pixel thick, then the traversal order is much more obvious: clockwise or counterclockwise.
Consider the following image.
........
..%%%%..
.%%%%...
...%%%%.
....%...
........
Here, I've marked everything "dark" (<50, perhaps) as % and everything bright as .. Now you can pick any pixel that is on the border between the two regions (I'll pick the dark side; you can draw the contour on the light side also, or with a little more work, directly between the light and dark sides.)
........
..%%%%..
.*%%%...
...%%%%.
....%...
........
Now you try to travel along the outer edge of the dark region, one pixel at a time. First, you look in the direction of something bright (directly left, for example). Then you rotate around--counterclockwise, let's say--until you hit a dark pixel.
........
..%%%%..
1*5%%...
234%%%%.
....%...
........
Once you hit position 5, you see that it's dark. So, you mark it as part of the contour and then try find the next piece on the contour by sweeping around starting from the pixel you just came from
........
..%%%%..
.0*%%...
.123%%%.
....%...
........
Here 0 is where you came from--and you're not going back there--and then you try pixels 1 and 2 (both light, which is not okay), until you hit pixel 3, which is dark.
In this way, you can walk around the contour pixel by pixel--both identifying the contour and getting the order of pixels--until you collide with the same pixel you started with and will leave from it so that you hit the same pixel that you did the first time you left it. Then the contour is closed. In our example, where we're making an 8-connected contour (i.e. we look at 8 neighbors, not 4), we'd get the following (where # denotes a contour point).
........
..####..
.##%#...
...#%##.
....#...
........
(You have to have this two-in-a-row criterion or if you have a dark region a single pixel wide, you'll walk up it but then not be able to walk back down along it.)
At this point, you've covered one entire boundary. But there might be others. Keep looking for dark pixels next to light ones until you have drawn a contour on top of all of them. Now you've converted your two-level picture (dark & bright pixels) into a set of contours.
If the contours end up too noisy, consider blurring the image first. That will smooth the contours out. (Alternatively, you can find the contours first and then average the coordinates with a moving window.)
In general, a given set of points can be connected in multiple ways to make different shapes.
For example, consider a set of 5 points consisting of the corners of a square and its center. These points can be connected to form a square with one side "dented in" to the center. But which side? There is no unique answer.
Other shapes can be much more complicated, with no obvious way to connect the dots.
If you are allowed to reduce your set of points to a convex hull, then it would be much easier.
I have also tried to create an algorithm that will connect contour dots into the smooth curve. See my open-source project http://outliner.codeplex.com.
The idea is the same as proposed by FUZxxl but I do not understand his worries about complexity: the time of processing is proportional to the total length of all contour strokes.
I don't know if collecting those points will get you far. (I can come up with situations in which it's almost impossible to tell which order they should come in.)
How about going to the brightest point.
Go to the brightness point of, say, 360 points surrounding this point at a distance of, say, 5 pixels.
Continue from there, but make sure you don't go back where you came from :)
Maybe try:
Start at a
Find the nearest point b
Connect a with b
and so on.
Probably not good, as complexity is something like O(n²). You may simplify this by looking only for points near the start, as aioobe suggest. This algorithm is good, if the points are just like 2-3px away from each other, but may create very strange grids.
See also Flood fill
and the lovely applet under SO
mapping-a-branching-tile-path .

Categories