I want to programm a tool that can place objects on a rectangle with the minumum of waste, this problem is also known as the cutting problem.
So i looked around to find some algorithms and i found out there are a few for rectangles but not that much for n-edged polygones.
my first approach was to get a bounding box for the polygone, then run the normal rectangle algorithm. After that you cound slowly try to increase the number of edges but still have only isometric lines (only vertical and horizontal), to approximate the polygone.
I wonder if there is any good algorithm that implement such thing, but is more common than create my own stuff.
the other way ive come up with could be something with two dimensional knapsack and some sorting heuristics that sort the best fitting polygones and try to put them on the rectangle.
But all i come up with has some good detection of special polygones (such as a square or normal rectangle) but does not work on common polygones.
Related
consider an image like this:
by grouping pixels by color into distinct rectangles, different configurations might be achieved, for example:
the goal is to find one of the best configurations, i.e. a configuration which has the least possible number of rectangles (rectangles sizes are not important).
any idea on how to design an efficient algorithm which is able to solve this problem?
EDIT:
i think the best answer is the one by #dshin, as they proved that this problem is a NP-HARD one so there probably isn't any efficient solution that is able to guarantee an optimal result.
other answers provide reasonable compromises to get an acceptable solution, but that won't always be the optimal one.
Each connected colored region is a rectilinear polygon that can be considered independently, and so your problem amounts to solving the minimum rectangle covering for rectilinear polygons. This is a well-studied problem that finds applications in some fields, like VLSI.
For convex rectilinear polygons, there is an algorithm that finds the optimal solution in polynomial time, described in this 1984 thesis.
The non-convex case is NP-hard (reference), so an efficient optimal solution likely does not exist. But there are several algorithms which produce good empirical results. This 1990 publication describes three separate algorithms, each of which are guaranteed to use at most twice as many rectangles as the optimal solution. This 2016 publication describes an algorithm that uses the common IP + LP relaxation technique, which apparently produces better results in real-life problem instances, although lacking in theoretical guarantees. Unfortunately, both publications are behind paywalls, and I haven't been able to find free resources that describe the algorithms.
If you are just looking for something reasonable, and your problem instances are not pathological in nature, then the algorithms described in other answers are probably good enough.
I don't have a proof but my feeling is a greedy approach should solve this problem:
Start on the upper left (or in whichever corner)
Expand rectangle 1px to the right as long as colors match
Expand rectangle 1px to the bottom as long as all colors in that row match
Line by line and column by column, find the next pixel that is not already part of a square (maybe keep track of visited pixels in a second array) and repeat 2 and 3.
You can switch lines and columns and go up and left or whatever instead and end up with different configurations, but from playing this through in my mind I think the number of rectangles should always be the same.
The idea here is based on the following links: Link 1 and Link 2.
In both the cases, the largest possible rectangle is computed within a given polygon/shape. Check both the above links for details.
We can extend the idea above to the problem at hand.
Steps:
Filter the image by color (say red)
Find the largest possible rectangle in the red region. After doing so mask it.
Repeat to find the next biggest rectangle until all the portions in red have been covered.
Repeat the above for every unique color.
Overview:
BACKGROUND
So I'm creating a program that recognizes chess moves. So far, I have implemented a fair number of algorithms to come up with the best results possible. What I've found so far is that the combination of undistorting an image (using undistort ), then applying a histogram equalization algorithm, and finally the goodFeaturesToTrack algorithm (I've found this to be better than the harris corner detection) yields pretty decent results. The goal here is to have every corner of every square accounted for with a point. That way, when I apply canny edge detection, I can process individual squares.
EXAMPLE
WHAT I'VE CONSIDERED
http://www.nandanbanerjee.com/index.php?option=com_content&view=article&id=71:buttercup-chess-robot&catid=78&Itemid=470
To summarize the link above, the idea is to find the upper-leftmost, upper-rightmost, lower-leftmost, and lower-rightmost points and divide the distance between them by eight. From there you would come up with probable points and compare them to the points that are actually on the board. If one of the points doesn't match, simply replace the point.
I've also considered some sort of mode, like finding the distance between neighboring points and storing them in a list. Then I would perform a mode operation to figure out the most probable distance and use that to draw points.
QUESTION
As you can see, the points are fairly accurate over most of the squares (though there are random points that do not do what I want). My question is what do you think the best way to find all corners on the chessboard (I'm open to all ideas) and could you give me a somewhat detailed description (just enough to steer me in the right direction or more if you choose :)? Also, (and this is a secondary question) do you have any recommendations on how to proceed in order to best recognize a move? I'm attempting to implement multiple ways of doing so and am going to compare methods to obtain best results! Thank you.
Please read these two links:
http://www.aishack.in/tutorials/sudoku-grabber-opencv-plot/
How to remove convexity defects in a Sudoku square?
I have a connected shape that consists of squares put together, e.g. take a squared paper and draw a line along the existing lines that ends at its beginning and does not cross itself.
The goal is now to find an algorithm (not brute-force) that fills this shape with as few, non-overlapping rectangles as possible.
I'm looking for the optimal solution. As can be seen in the images, the naive greedy approach (take the largest rectangle) does not work.
(Optimal)
(Greedy)
My scenario is vertices reduction, but I'm sure there are other use-cases as well.
Note: This problem seems basic, but I was not able to find a solution elsewhere. Also, is this problem NP-hard?
Edit: I just realized that, in my scenario, filling the shape with as few non-overlapping triangles as possible, would give an even better result.
I've spend a lot of time researching this, since I asked the initial question. For the first problem (optimally filling the shape with rectangles), I've written the solution here under the header "Optimal Greedy Meshing":
http://blackflux.wordpress.com/2014/03/01/meshing-in-voxel-engines-part-2/
The complexity is actually better (faster) than for optimally triangulating a polygon without holes. The slowest part is the Hopcroft-Karp algorithm.
Treating the shape as a polygon is also discussed in the linked blog post. Note that I'm also considering holes.
The first problem is harder than the one with triangles; for triangles, see the algorithms in
http://en.wikipedia.org/wiki/Polygon_triangulation
which can do it without any extra vertices.
Given a collection of say, 50, images with various widths and heights, how would one go about programmatically arranging them in an interesting* abstract way? (see image below)
By interesting I mean, no large gaps, and no easily distinguishable rows or columns (negative space forms a lot of T-like intersections).
For my specific case, all images have a set max dimension of 150px, which could mean the height OR width is a max of 150px (could be 150px by 450px, or 378px by 150px).
This seems like it could be a classic programming challenge but I'm finding the topic hard to Google...
EDIT: Changed image to show that there is no restriction on how the overall arrangement must be (doesn't have to fit inside a set area)
If you are not opposed to jquery plugin, you can check this out - http://masonry.desandro.com/
Your problem is NP-Hard.
This thread shows that even with one type of nXm rectangles, it is NP-Hard to find if there is a solution , so your more generalized problem is of course NP-Hard as well [The only one type of rectangle is a private case of this problem]
You could try a backtracking solution if you are after optimized solution, or a heuristic approach such as genetic algorithms or hill climbing, which will be faster - but will usually find a non optimal result.
I have built something similar to this (although it is probably not the most sophisticated solution). My approach was to use a quadtree to organize the rectangles that I had placed on the canvas. I then just basically went around the center point in a spiral, trying to place new rectangles, and using the quadtree to detect collisions. If I detected a collision then I would move the rectangle I was trying to place to the edge of the rectangle that it collided with that was furthest from the center and repeat the collision checking process.
Again, probably not the most sophisticated method, and it does tend to leave some larger gaps between rectangles (the borders between them are not uniform), but to my taste it gave good results.
I've been searching far and wide on the seven internets, and have come to no avail. The closest to what I need seems to be The cutting stock problem, only in 2D (which is disappointing since Wikipedia doesn't provide any directions on how to solve that one). Another look-alike problem would be UV unwrapping. There are solutions there, but only those that you get from add-ons on various 3D software.
Cutting the long talk short - what I want is this: given a rectangle of known width and height, I have to find out how many shapes (polygons) of known sizes (which may be rotated at will) may I fit inside that rectangle.
For example, I could choose a T-shaped piece and in the same rectangle I could pack it both in an efficient way, resulting in 4 shapes per rectangle
as well as tiling them based on their bounding boxes, case in which I could only fit 3
But of course, this is only an example... and I don't think it would be much use to solving on this particular case. The only approaches I can think of right now are either like backtracking in their complexity or solve only particular cases of this problem. So... any ideas?
Anybody up for a game of Tetris (a subset of your problem)?
This is known as the packing problem. Without knowing what kind of shapes you are likely to face ahead of time, it can be very difficult if not impossible to come up with an algorithm that will give you the best answer. More than likely unless your polygons are "nice" polygons (circles, squares, equilateral triangles, etc.) you will probably have to settle for a heuristic that gives you the approximate best solution most of the time.
One general heuristic (though far from optimal depending on the shape of the input polygon) would be to simplify the problem by drawing a rectangle around the polygon so that the rectangle would be just big enough to cover the polygon. (As an example in the diagram below we draw a red rectangle around a blue polygon.)
Once we have done this, we can then take that rectangle and try to fit as many of that rectangle into the large rectangle as possible. This simplfies the problem into a rectangle packing problem which is easier to solve and wrap your head around. An example of an algorithm for this is at the following link:
An Effective Recursive Partitioning Approach for the Packing of Identical Rectangles in a Rectangle.
Now obviously this heuristic is not optimal when the polygon in question is not close to being the same shape as a rectangle, but it does give you a minimum baseline to work with especially if you don't have much knowledge of what your polygon will look like (or there is high variance in what the polygon will look like). Using this algorithm, it would fill up a large rectangle like so:
Here is the same image without the intermediate rectangles:
For the case of these T-shaped polygons, the heuristic is not the best it could be (in fact it may be almost a worst case scenario for this proposed approximation), but it would work very well for other types of polygons.
consider what the other answer said by placing the t's into a square, but instead of just leaving it as a square set the shapes up in a list. Then use True and False to fill the nested list as the shape i.e. [[True,True,True],[False,True,False]] for your T shape. Then use a function to place the shapes on the grid. To optimize the results, create a tracker which will pay attention to how many false in a new shape overlap with trues that are already on the grid from previous shapes. The function will place the shape in the place with the most overlaps. There will have to be modifications to create higher and higher optimizations, but that is the general premise which you are looking for.