I created an algorithm for this, this is actually an NP-Hard version of the packaging problem , but with an infinite bin size.
You can try to find some articles about this and try to optimize your algorithm, but in the end it will remain a rude way to try every opportunity and try to minimize the resulting bin size.
If you do not need the best solution, but only one solution, you can avoid rough forcing all the combinations. I created a program that also did this.
Description:
Images: array of the input images ResultMap: 2d array of Booleans FinalImage: large image
- Sort the "Images" array so that the largest image is at the top.
- Calculate the total size of your images and initialize the ResultMap so that it is 1.5 times larger than the total size of your images (you could make this step smarter for better memory usage and performance). Make the ResultMap the same size and fill it with False.
- Then add the first image to the left of your FinalImage and set all the boolean values โโin ResultMap true from 0.0 to ImageHeight, ImageWidth.
ResultMap is used to quickly check if you can put an image in the current FinalImage. You can optimize it for using int32 and use each bit for one pixel. This will reduce memory and increase performance, because you can immediately check 32 bits (using a mask). But it will become more dense because you have to think about the mask that you will need to make for the edges of your image.
Now I will describe the real cycle of the "algorithm".
- For each image in the array, try to find a place that would be suitable. You can write a loop that will look through the ResultMap array and look for a false value, and then start to see if it remains in both directions by default for the image size.
- If you find a place, copy the image in FinalImage and update the correct boolean values โโin ResultMap
- If you find a place, just increase the size of FinalImage (so look at the edges where the minimum amount of extra space is required), and also synchronize it with ResultMap
- GOTO 1 :)
This is not optimal, but it can solve the problem in a reasonably optimal way (especially if there are several smaller images at the end to fill in the gabs).
Davy landman
source share