Maximum-perimeter bounding rectangle for a set of points - c

I've been struggling for quite a while with this seemingly simple problem. I am given a set of points (which I have further simplified down to a convex hull) and my task is to find a rectangle (not necessarily axis-aligned) that encompasses all of them, has no extra space around (so that it is tight-fitting around the points) and has the maximum possible perimeter. It was no trouble for me to find the minimal one, but this has proven to be a tougher nut to crack. When searching for the minimal bounding rectangle, I was able to use the assumption that one of the rectangle's sides was always aligned with one of the hull's sides, but here I don't see any such case here. Am I missing something painfully obvious? The only way I could come up so far is to test antipodal pairs of points if they can project onto the sides of the rectangle and use some trig to maximize the function, but I just lost myself in the calculations.
Thanks in advance!

First, compute the convex hull of your point set.
Now, think about spinning the polygon around and computing the smallest enclosing axis-aligned rectangle. Notice that the top point, the left point, the right point, and the bottom point will proceed clockwise around the convex hull from one vertex to the next.
You can't try every possible angle explicitly. You can, however, do a sweep-line trick. Given an angle, though, you can compute the top, left, bottom, and right points after spinning the polygon by that angle as well as the first of the top, left, bottom, and right points to change identity as you continue rotating the polygon. So you get a range of angles for which your current choices of top, left, bottom, and right are correct; further, you know what the next correct choice of top, left, bottom, and right is.
For each legitimate choice of top, left, bottom, and right, You wind up having to compute the maximum value of a*sin(theta) + b*cos(theta) for fixed a and b over some range of theta. Recall from trig that a*sin(theta) + b*cos(theta) = sqrt(a^2+b^2) cos(theta - arctan(b/a)). You evaluate the function at the boundaries of your interval and where the derivative is zero (at arctan(b/a) plus any integer times pi) and you're golden.

Related

Most efficient way to determine circle coordinates?

I am making a function for drawing a circle in 2d space.
For this, I have identified 2 approaches:
go through all the possible pixels and run them through a formula that will return a value that shows whether the pixel coordinates are inside the circle, outside (bonus: or intersecting it)
get all the circle pixels (basically draw the circle)
I tried to look at some math sources, but I have met with some problems:
in the second approach, the resolution at which I am incrementing the angle matters, so if it is too little, or radius is too small, there will be unnecessary duplication. On the other hand, if the angle gets incremented by more, or radius is too large, there will be gaps.
The formula I was using is:
struct vec2{int x; int y;};
void get_circle(int x, int y, int r, int angle, struct vec2 *coordinates) {
coordiantes->x = x + r * cos(angle);
coordinates->y = y + r * sin(angle);
}
This is obviously a bit much to run a lot of times.
I also want to make some kind of primitive anti-aliasing, so if I can get a value where a pixel only intersects the circle line by a half, it would be drawn as a half-pixel.
My final goal is to draw a nice circle with a line that can be thick. The thickness can be achieved with the area approach where I fill all pixels in a circle area, and then I remove pixels in the inner circle. Or it can be several iterations of the circle. I didn't write the array part of the computation, but yes, I would like each pixel identified. If we take a pixel as a rectangle, then I would like no pixel to be drawn if the theoretical circle goes through <33% of the surface, half-pixel 33-66, and full if >66%.
Please advise. I need some approach that will be computationally efficient.
First, "most efficient" depends on quite a few things. For most modern OpenGL systems you can usually get away with just computing points around the circumference using sine and cosine (and an appropriate aspect scale) with the native floating-point type, then plotting the points using any decent polyline algorithm.
Once you have things working, profile.
If profiling shows your algorithm to be holding things up (and compared to other normal and common computations, it shouldn't be), only then should you spend time and effort on trickier (read: more complicated) stuff, like the Midpoint Circle Algorithm to generate points to send to your polyline.
Also, don't forget to memoize into a sprite or texture or pixmap or whatever is appropriate for your hardware/software IFF profiling shows a worthwhile improvement.

How to order 3d points in clockwise order?

I have bunch of 3d points (an array) not ordered in some particular order and not restricted to some axis/plane. Based on the coordinates of these points I want to order the array in clockwise order, like in the image. At moment I am clueless where to start. One idea is to find for each the closest point and somehow figure out the direction.
3Dave has already said this, but it completely depends on where the camera is.
There is no answer unless you specify the frustrum.
Note that circles are 2D, not 3D objects. "Clockwise" relates to circles.
Assuming that you mean on a plane:
This is a problem with two parts.
The first part is incredibly difficult.
The second part is relatively easy.
First part: indeed, you are doing object recognition: you have to find a circle.
For this, investigate the existing technology for shape recognition, or read up on stuff like https://link.springer.com/article/10.1007/s11042-018-6167-2
For the second part: (which is almost irrelevant after the first part). Just get the coords of each point relative to the center of the circle you found, simply calculate the angle of each from the top, and sort them.
Cheap game-type solution
If you want the cheap solution, which you can use if the points are "reasonable" ..
find the centroid of all the points (it's just the average of all)
write each point as a vector from the centroid to the point
pick any one point as being the "top"
use something like this https://docs.unity3d.com/ScriptReference/Vector3.Angle.html to get the angle of each from the "top" one
voila! just put them in order
In practice you'll likely need these things also:
find the "plane" the points are on (find the "average plane" they are on, it's relatively easy to do this, look it up!)
make an axis through the centroid which is perpendicular to the plane

Measuring the area of an arbitrary shape from an edge map

I'm trying to write an algorithm that will give me the (approximate) area of a shape.
My algorithm is provided with an image, which in then performs a Sobel edge-detection on. Using the edge-detected image, I'd like to find the area of an enclosed space, given a co-ordinate within the area. The co-ordinate is likely to be close to the centre of the shape, but not exactly centred..
If I wanted to be thorough, I'd do it recursively. However, I'm running this code on an embedded platform, so I'm memory-limited. I'd also prefer speedier algorithms.
The algorithm doesn't need to produce the exact area of the shape - something close (an order of magnitude at most) would be OK.
So far, I've considered approximating the shape as both a rectangle and an ellipse, by measuring up, down, left and right from the co-ordinate until an edge is found.
Here's an example of said methods:
- example image:
- ellipse and rectangle-marked:
The green fill is a partial-run of recursively filling the area.
If anyone has some better methods, I'd appreciate it!

I have a dot bouncing around an image. Need to calculate angles of reflection off of groups of pixels (surface of objects)

Suppose we have an image (pixel buffer) that is in black and white, so each pixel is either black or white (not gray scale).
Now somewhere in the middle of that images, place a green dot. It may have a radius of n for rendering purposed, but it is really a just point. Give the dot a randomly selected direction and speed, and start it moving. If the image is all white pixels, the dot will bounce off the edges of the image, infinitely wandering around the picture. This is quite easy... just reverse either the rise or run of the dot's vector.
Next, suppose the image has some globs of black pixels. As the dot encounters these globs of black pixels, the angle of reflection needs to be calculated. This is also quite easy of the the black pixels have a fixed slope, as in my sketch (blue X represents black pixels). You can find the slope of the blue Xs and easily calculate the new vector.
But how about the case where the black pixels form really unfriendly surfaces? What are some approaches to figuring out this angle?
This is the subject that I am interested in.
There must be some algorithms that exist for this kind of purpose, but I never ran across any in school. I am not asking how to code this, rather approaches to writing the algorithm to do this. I have a few ideas that I'll try, but if there are some standard ways to do this that exist, I'd like to learn about them.
Obviously I'd like to start with Black and White then move into RGBA.
I am looking for any reference material on just this sort of subject. Websites, books, or other references are very very welcome.
Also, if there are different StackOverflow tags that could be good, let me know.
Thanks much!
Edit********** More pics and information
Maybe I wasn't clear what I meant by "unfriendly surfaces". In the previous picture, our blue X's happened to just be a line. Picture a case where it is not a line, rather a wierd shape.
We start with our green pixel traveling at a slope of 2. Suppose it's vector is that of 12 pixels per frame. It would have a projected path like this:
But suppose instead of a nice friendly line, we have this:
In my mind I can kinda of see what is likely to happen if this were a ball and some walls.
Look for edge detection algorithms used in image processing. Some edge detectors also approximate the direction of edges.
You can think of the pixel neighborhood of the green dot, maybe somewhere between 3x3 and 7x7, as a small edge direction detection problem. One approach would take two passes at the pixels:
In the first pass, smooth the sharp black/white pixels using a Gaussian filter.
In the second pass, apply an edge detection operator, such as Sobel, Prewitt or Roberts to produce the X and Y derivatives of the pixels' intensity. You can then approximate the direction as:
angle = arctan(dx/dy)
The motivation for the smoothing pass is to give the edge detection operator information from farther-away pixels.
The Wikipedia page on the Canny edge detector has a good discussion on obtaining the direction (the "gradient") of an edge, including an example of a particular Gaussian filter you can use for smoothing.
Am doing something similar with a ball and randomly generated backgrounds.
The filter and edge detection is highly technical but all other processes using a 5*5 or 3*3 grid seem similarly difficult.
However, I think I may have a cheap way around this. Assuming a ball travelling in any direction, scan all leading edges of the ball - a semicircle. The further to the edge of the ball the collision occurs the closer to vertical is the collision. Again, I think, this should allow you to easily infer the background normal and from there the answer is fairly simple

Eliminating rectangles enclosed within other rectangles in OpenCV

I'm in the process of writing a C program using OpenCV to detect some rectangles made with tape, which are hollow on the inside. Problem is, each physical rectangle gives two digital rectangles: one for the inner perimeter, one for the outer perimeter. The outer rectangle in all cases completely encloses the inner rectangle.
I need some way to remove the inner rectangles, and in a reasonably efficient manner, as this is being run on a video feed and must not drop framerate considerably (approx. 15fps, on a BeagleBoard xM, which is not terribly powerful).
There are always four physical rectangles, and somewhere between four to eight digital rectangles depending on the cleanliness of the processing operations. The outer rectangle is detected reliably; the inner rectangle is not. The image is thresholded, eroded, and dilated such that the image is clean and detection is reliable in general.
I feel that this problem is separate from OpenCV and is really just working with rectangles and could probably be solved by me with some time, but the project is on a crunch deadline, so I'm also throwing this question in. Thanks in advance, guys.
there is a function called grouprectangle in opencv.
The function can remove multiple rectangles...
Have a happy coding.
Since you only have at most 8 digital rectangles, I think it would be fine to use the natural, brute force, algorithm to figure out which rectangles are inside other rectanges. It's OK to do O(N^2) algorithms when N is small, and 8 is small.
Here is the pseudo code:
for each rectangle i {
for each rectangle j {
if i != j and rectangle i is inside rectangle j {
disregard rectangle i
}
}
}
Solved - the speedy solution is to take the distance to one of the corners from the center point of the rectangle, and compare that distance between rectangles whose centers are very close together. The one with the shorter distance must be the inner rectangle.
Code-wise you'd want to calculate the center, then find, say, the bottom right point, which is just the point with both min x and min y. Calculate the distance between them and store it somehow. For each rectangle, iterate over the other ones and check if their centers are very close (a constant of ~30px works fine for this in my case). Compare the distances calculated earlier; the rectangle with the shorter distance should be deleted from the list of rectangles.

Resources