Intersection over union for rectangles with different orientation - swift

I need to implement an algorithm in swift to find the intersection over union (IoU) between two rectangles with different orientations in 2-dimensional space. I could not find any tutorials or sample codes to teach how to implement such an algorithm.
Could someone provide relevant resources?

You can use O'Rourke algorithm for calculation of intersection of two convex polygons.
C and Java code is availaible on the page for book "Computational Geometry in C"
Algorithm traverses edges of polygons until it finds intersection (using
orientation test). After intersection it chooses "the most inner" edge from two possible next ones to build intersection core polygon (always convex).
When you have ordered list of vertices, you can calculate polygon area with shoelace formula.
To get area of union, we can calculate (thanks to Yves Daoust for hint)
Area(Union) = Area(P) + Area(Q) - Area(Intersection)

Alternatively to the very good solution of MBo/O'Rourke, you can use a sweep line approach.
For convenience, assume that one of the polygons is axis aligned. Then there are two "events" when the line hits the top and bottom sides of the aligned rectangle and four events when the line hits the vertices of the other (depending on the orientation, there are 8 possible permutations of the vertices).
The intersection of the rectangles occurs inside the vertical ranges defined by these events (you perform a merge of the two event sets) and there are up two six intersections to be computed between the oblique sides and the horizontals. For every event line, it is an easy matter to determine the X intervals spanned by both rectangles, and find their intersection or union. And the areas between two event lines are trapezoids.
To cope with rectangles in general position, you can
rotate both polygons to align one of them,
work with a counter-rotated coordinate system,
perform the sweep with an horizontal line anyway without moving the polygons; but then there are 8 events instead of 6 and up to 8 intersection computations.

Related

how to perform hough transformfor finding hand curve

hi i want to detect fingertips point and valleypoint of hand by using hough transform.Simply the Question is what is the [H,theta,rho]=hough(BW) is good for extract these point.
the image is here:
https://www.dropbox.com/sh/n1lz7b5eedzbui7/AADwy5O1l7sWf5aOx7KWAmhOa?dl=0
tnx
The standard hough transformation is just for detecting straight lines. Not more and not less. The Matlab function hough (please see here) returns the so-called hough space H, a parametric space which is used to find these lines and the parametric representation of each line: rho = x*cos(theta) + y*sin(theta).
You will have to do more than this to detect your desired points. Since your fingers usually won't consist of straight lines, I think you should think of something else anyway, e.g. if you can assume such a perfect curve as the one in your image maybe this is interesting for you.
Another simple technique you might consider is to compare the straight line distance between two points on your hand line to the distance between those two points along the perimeter (geodesic distance). For this you would need an ordered list of points along the perimeter.
Along regions of high curvature, the straight line distance between two points will be smaller than the number of pixels between those two points along the perimeter.
For example, you could check perimeter pixels separate by 10 pixels. That is, you would search through the list and compare the point at index N and the point index N+10. (You'll need to loop back around to the beginning of the list as you approach the end.) If the straight line distance between these two points is nearly 10 pixels as well, then you know those points lie on a straight section of the perimeter. If the straight line distance is much smaller than 10, then you know the perimeter curves in some fashion between those points. Whether you check pixels that are 5, 10, 20, or 30 items apart in the list will depend on the resolution of your image and the curves you're looking for.
This technique is useful because it's simple and quick to implement. Maybe it would work well enough for your needs.
Yet another way: simplify the outline to small line segments, and then you can calculate the line-line angle between adjacent segments. To simplify the curves, implement the Ramer-Douglas-Puecker algorithm. A little experimentation will reveal what parameter settings will work for your application.
https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Finally, you could look into piecewise curve fitting: a curve would be fitted to small segments of the outline. This can get very complicated, and researchers continue to find ways to decompose complex figures into a limited number of more basic shapes or curves. I recommend trying the simplest technique and then only adding complexity if you need it.

An gridded area is divided into several sub-areas. How to track each grid's membership?

I have a square that is grid into many small cells. Each cell has a size of 0.1*0.1. Several zigzag lines are drawn to divided that square into sub-area. The zigzag lines only follow the cell edges.
The vertices that these zigzag lines cross are calculated and stored in a different matrix. In this case, there are 6 zigzag lines that meet at the center, thus there are 6 matrix that store the coordinated of the lines.
The center of each cell, as well as the four vertices, are calculated and store in a big matrix. Now, if I want to track to which sub-area each of the cell belongs, what looping algorithm should I use?
Say, we mark the top left area as 1, and count it clockwise. Then the cells in the top left area should be marked 1. Cells in the top right area should be marked 2, and so on.
From the given example, we can infer that the areas are "sectors" with a common center and the radial lines meeting the outline.
You can get the starting edges (on the outline) of the zigzag lines from their respective array. They each separate two cells belonging to different areas. By computing the angles and sorting them, you can number the areas increasingly and associate them a starting cell.
Now "draw" the zigzag lines in the big matrix (every cell having two flags that indicate the presence of an edge to the right or below it). Then, starting from the cell of every area, use a seed filling algorithm. You will need to modify the basic algorithm to account for the presence of the edges.

Intersection of segment with polygon

I have to create a function in MATLAB that performs the following task:
Input:
p polygon in the form
p = [x1,y1; x2,y2; x3,y3; x4,y4...]
s struct with the segment from A to B
s = struct('A',[x,y],'B'[u,w])
Return:
1) An integer indicating how many intersections there are between the segment and the polygon (e.g., 0,1,2)
2) A new segment from A to B, where A is the first intersection or the initial point of the input segment and B the second point of the intersection or the last point of the segment input.
I have an idea on how to do it by using the function inpolygon. I have been reading how to use this function, and know that to use that, I should provide a query point and the coordinates of the polygon vertices. It will return 1 or 0 depending on whether it is inside or not.
My question is, how can I get the query point of the segment that is placed exactly in the boundary (in the case that the segment intersects with it)?
If you have the Mapping Toolbox installed, you could use polyxpoly. As this is a rather basic problem, there are quite a few free MATLAB-codes out there on the File Exchange. Here is what I found for the search term 'polygon intersect':
2D Polygon edges intersection by Bruno Luong
Find the intersection points of the edges of two 2D polygons, a simple function made to follow up a Newsgroup discussion
Curve Intersect 2 by Sebastian Hölz
This file is based on the Curve Intersect function by Duane Hanselman. It extends the scope of the function to handle arbitrary lines / polygons, which may also have vertical segments or segments with non-increasing x-values.
Curve intersections by NS
While a few other functions already exist in FEX that compute the
intersection points of curves, this short piece of code was written
with speed being the highest priority. No loops are used throughout,
taking full advantage of MATLAB's vectorization capabilities
Fast and Robust Curve Intersections by Douglas Schwarz
This function computes the (x,y) locations where two curves intersect. The curves can be broken with NaNs or have vertical segments. It is also very fast (at least on data that represents what I think is a typical application).
geom2d by David Legland
[...] derive new shapes: intersection between 2 lines, between a line and a circle, parallel and perpendicular lines

Fast way to convert array of points into triangle strip?

I have an array of CGPoints (basic struct with two floats: x and y). I want to use OpenGL ES to draw a textured curve using these points. I can do this fine with just two points, but it gets harder when I need to make a line from several points.
Currently I draw a line horizontally, calculate its angle from the points given, and then rotate it. I don't think doing this for all lines in a curve is a good idea. There's probably a faster way.
I'm thinking that I can "enlarge" or "constrict" all the points at once to make a curve with some sort of width.
I'm not positive what you want to accomplish, but consider this:
Based on a ordered list of points, you can draw a polyline using those points. If you want to have a polyline with a 2D texture on it, you can draw a series of quadrilaterals (using two triangles each, of course). You can generate these quadrilaterals using an idea similar to catmul-rom spline generation.
Consider a series of points p[i-1], p[i], p[i+1]. Now, for each i, you can find two points each an epsilon distance away from p[i] along the line perpendicular to the line connecting p[i-1] and p[i+1]. You can determine the two points generated for the endpoints in various ways, like using the perpendicular to the line from p[0] to p[1].
I'm not sure if this will be faster than your method, but you should be caching the results. If you are planning on doing this every frame, another type of solution to your problem may be needed.

How to represent a polygon with hole(s)?

It's usually popular to work with polygons with their vertices sorted CW or CCW in vectors(2*1 or 1*2 matrices). However, how to state polygons with holes in vectors?
I'm going to apply various process on these polygons, so I want a way of representing with which I could work easily or efficiently.(i.e how to state that kind of polygons in my program in order to ease my algorithms?)
polygons are 2D and I'm programming in MATLAB.
EDIT 1 : I'm going to calculate visibility graph of these polygons(with or without holes).
As others have mentioned, a polygon with holes can be represented as an exterior boundary, plus zero or more interior boundaries, all of which are mutually nonoverlapping*. If you use nonzero winding number to determine inside/outside, be sure to specify your interior boundaries in the opposite direction as the exterior boundaries (counterclockwise for exterior and clockwise for interior, or vice-versa) so that the contour integrals are zero inside the holes.
FYI, tis kind of definition/representation has been formalized in the OpenGIS Simple Features Specification (PDF).
As far as representation:
I'd probably have a cell array of K Nx2 matrices, where the first element in the cell array is the exterior boundary, and the remaining elements (if any) in the cell array are the interior boundaries. I would use a cell array because there may not be the same number of points on each boundary.
*nonoverlapping = except at individual points, e.g. a diamond inside a square:
You can break a polygon with a hole in it into two shapes without a hole. When you're doing contour integration in a complex plane, you can create a "cut" from one edge of the polygon that brings you to the edge of the hole; integrate around one side of the hole and back; then traverse around the other side for the second polygon. You end up with two path integrals along each cut that cancel each other out.
"visibility graph" - is this for a radiation view factor calculation with shading? Or a ray-tracing graphics algorithm?
A polygon, plus a list of polygonal holes. Just be sure the various polygons don't intersect.
What do you plan to do with this thing?
It sounds like each hole is just a polygon inside the polygon itself. Perhaps you could store a vector like you describe for the outer polygon, then a vector of more polygon vectors for the holes.
Presumably you'll want to have a tree structure if you want this to be as generic as possible (i.e. polygons with polygonal holes that have polygons inside them with holes inside that, ...). Matlab isn't really great at representing tree structures efficiently, but here's one idea...
Have a struct-array of polygons.
Each polygon is a struct with two fields, 'corners', and 'children'.
The 'corners' field contains a matrix of (x,y) coordinates of the corners, accessed as "data{polyIdx}.corners(:,cornerIdx)".
The 'children' field is a struct-array of polygons.
Here's an example of some code to make a triangle with bogus children that are holes (they aren't really valid though because they will likely overlap:
polygon = struct;
npoints = 3;
polygon.corners = rand(2,npoints);
polygon.children = struct;
nchildren = 5;
for c=1:nchildren
polygon.children(c).corners = rand(2,npoints);
polygon.children(c).children = struct;
end
You could continue to recursively define children that alternate between creating holes and filling them.
What exactly do you mean under "a visibility graph" ?
Two "full" poligons, two states possible, either +1 or -1.
If you're representing a hole, you've got one with state +1 and one with state -1, which represents a hole, resulting in state 0.
If you've got overlapping polygons, you'll end up with resultant state >1. Then you can calculate the borders of a new polygon.
If you've got two polygons with holes that intersect, then first calculate the state of a new polygon which consists of outer borders of the two old ones, then deal with holes.
Anyways, ... I think you get the general principle.
Have no idea how to do it in matlab, I used it only marginally so far, and even that for very simple things.