I'm trying to find an algorithm to find a space in a Bitmap large enough to contain a new bitmap. Currently I'm iterating each x and y pixel and seeing if my smaller bitmap will collide with the background at all. It works but it's extremely slow. I've recently become aware of something called Integral Image to parse the background image and then check if a space in it is available in constant time.
The algorithm I'm using is:
public class IntegralImage
{
private int[][] integralImage = null;
public IntegralImage(Bitmap image)
{
int originalImageHeight = image.getHeight();
int originalImageWidth = image.getWidth();
integralImage = new int[originalImageHeight][originalImageWidth];
int[][] originalPixels = new int[image.getHeight()][image.getWidth()];
for(int i = 0; i < image.getHeight(); i++)
{
for(int j = 0; j < image.getWidth(); j++)
{
originalPixels[i][j] = image.getPixel(j, i);
}
}
int originalPixelValue = 0;
for (int row = 0; row < originalImageHeight; row++)
{
for (int column = 0; column < originalImageWidth; column++)
{
originalPixelValue = originalPixels[column][row];
if (row == 0 && column == 0)
{
integralImage[row][column] = originalPixelValue;
}
else if (row == 0)
{
integralImage[row][column] = originalPixelValue + integralImage[row][column - 1];
}
else if (column == 0)
{
integralImage[row][column] = originalPixelValue + integralImage[row - 1][column];
}
else
{
integralImage[row][column] = originalPixelValue + integralImage[row][column - 1] + integralImage[row - 1][column] - integralImage[row - 1][column - 1];
}
}
}
}
public int total(int x1, int y1, int x2, int y2)
{
int a = x1 > 0 && y1 > 0 ? integralImage[x1-1][y1-1] : 0;
int b = x1 > 0 ? integralImage[x1-1][y2] : 0;
int c = y1 > 0 ? integralImage[x2][y1-1] : 0;
int d = integralImage[x2][y2];
return a + d - b - c;
}
}
However when I call it using this:
if(imageIntegral.total(i, j, i + _imageBitmap.getWidth(), j + _imageBitmap.getHeight()) == 0)
It always returns true and just stacks all the text bitmaps on top of each other.
Does anyone have any experience in trying to fit bitmaps within a bitmap without overlapping efficiently?
It's my understanding that it should return zero if the sub-array contains nothing but white pixels.
Thank you.