Packing rectangular image data into a square texture
Asked Answered
T

4

20

I have N items of 2D image data that will be rectangular and I want to pack them into a single power of 2 texture as efficiently as possible.

A simple non-efficient and naive implementation of an algorithm to pack these rects would be easy to whip up, but I'm sure people have come up with algorithms to do this as space efficiently as possible. I've found various references to lightmap packing which is similar to what I'm looking for, but the algorithms for lightmapping tend to take non-rectangular images into account which actually complicates things more than I need them to be.

Does anyone have hints? Names of algorithms or paper authors I should google?

Thanks.

Thumping answered 4/11, 2008 at 23:57 Comment(0)
C
8

I've needed to do this very thing you describe.

This is the Python code I used, it's a recipe in the Python Cookbook:

Recipe 442299: pack multiple images of different sizes into one image

Croissant answered 5/11, 2008 at 4:9 Comment(1)
This code doesn't look like it is searching for an optimal solution. Also it seems to want to pack all the images into one single texture.Graner
G
6

Your problem in 1D is called Bin Packing. Perhaps that's a good start for your search.

Note that the problem you want to solve is really hard (it is NP-hard). So you should not search for the optimal solution, but some clever heuristical algorithm.

I think bottom-up dynamic programming is possible for 1D bin packing, but not for the 2D case.

You could think of simplifying your problem by only solving the 1D problem, making restrictions like cutting the textures into several (variable sized) slices in 1 dimension.

Another possiblity is running meta-heuristic optimization on it, like Evolutionary Algorithms or Particle Swarm Optimization.

Graner answered 5/11, 2008 at 0:30 Comment(0)
S
4

Very good and simple packing algorithm can be found here: http://www.blackpawn.com/texts/lightmaps/

Its implementation only takes 200 of C++ lines, not more (I suppose you have the Bitmap manipulation routines already).

For the theory behind there is an introduction by Jukka Jylänki (look for the "A Thousand Ways to Pack the Bin").

The author of the paper provides the C++ library which is really bloated from my point of view, but on the other hand it has a lot of options and is very well documented.

Said answered 26/4, 2012 at 18:40 Comment(0)
N
1

I had a similar problem but I was packing squares. Try this: http://www.mrashid.info/blog/stacking-squares-problem.php

The C++ code is not very elegant but at least you get the basic idea on how to approach this problem.

Necking answered 15/1, 2012 at 2:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.