Knowledge Dump

maximum_segments (Python)

Given a batch of white image segments on a black background, this script selects the segments that cover the largest possible area, without any of the segments overlapping. This is done by formulating the problem as an integer linear programming (ILP) problem and solving it, using the default CBC solver from the Python library PuLP. It can be seen that it corresponds to the Maximum-Weight Independent Set (MWIS) problem:
Let $n$ be the number of images, $\mu \in \mathbb N^n$ be the weight vector, consisting of the number of white pixels in each segment and $(x_1,\dots,x_n)^T=x^T\in\{0,1\}^n$ the vector of binary 0/1 decision variables. If $x_i=1$ holds for any $i\in\{1,\dots,n\}$ in our solution, this corresponds to the corresponding image $i$ being selected and the area of its white segment being added to the solution image. In order to enforce the chosen segments to be non-overlapping, we add constraints $x_i + x_j \le 1$ for any overlapping segments $i,j\in\{1,\dots,n\}$ - if $x_i$ is set to 1, this constraint prevents the segment $j$ to be selected and vice versa.
Since we want to find the segment combination covering the largest possible area, this results in the maximization problem: $$\max_{x\in\{0,1\}^n}\mu^T x,$$ $$\text{s.t. }x_i+x_j\le1,$$ $$\text{ for all overlapping segments }i,j\in\{1,\dots,n\}.$$ MWIS problems are NP-hard and can be quite difficult to solve. Thus, the number of image segments in the downloadable code example has to be adjusted for the respective machine running it. Methods of improving the solver speed/maximum solvable segment number are briefly mentioned in the Python code file.
Download (1000 .png segment images and Python 3.11 script as .zip).