Test iOS summed-area tables on a cloud Mac

Test iOS summed-area tables on a cloud Mac

Test iOS summed-area tables on a cloud Mac

You are developing a scanning tool on Windows and sending the project to a cloud Mac to build. You notice that local brightness readings near the image’s right edge sometimes come out too low. The pixel-by-pixel version works correctly; the problem appeared only after switching to a summed-area table. Before adjusting recognition thresholds, set aside image decoding and UI coordinates and test rectangle sums using a dozen or so grayscale values. That usually makes an off-by-one error or an incorrect subtraction order much easier to find.

Define the pixel and selection contract first

A summed-area table stores cumulative pixel sums from the origin to each position. Building it requires a pass over the entire image, but each subsequent rectangle query reads just four table entries. This makes it useful for repeated local brightness analysis on the same image, not for building an extra table to answer a single query.

Here, the input is a tightly packed, row-major array of eight-bit grayscale values, with the origin at the top left. Selections use half-open intervals: [x0,x1) × [y0,y1). The right boundary may equal the image width, an empty selection returns zero, and reversed or out-of-bounds coordinates throw an error.

A summed-area table is not an image coordinate converter. Handle view scaling, image orientation, and grayscale conversion upstream. Do not use screen points directly as pixel indices.

The prefix table has an extra row and column of zeros beyond the original image dimensions. This lets selections touching the top or left edge use the same formula, without four separate boundary-handling branches.

Build a minimal implementation on a cloud Mac

Run xcrun swift --version in Terminal to confirm that the toolchain is available, then save the following code as IntegralCheck.swift. The width and height are each capped at 2048 here. That is a resource policy for this example, not a limitation of the summed-area table algorithm.

enum IntegralError: Error {
    case invalidInput
    case invalidRectangle
}

struct IntegralImage {
    let width: Int
    let height: Int
    private let pitch: Int
    private let prefix: [UInt64]

    init(pixels: [UInt8], width: Int, height: Int) throws {
        guard width > 0, height > 0,
              width <= 2048, height <= 2048 else {
            throw IntegralError.invalidInput
        }
        guard pixels.count == width * height else {
            throw IntegralError.invalidInput
        }

        let pitch = width + 1
        var table = [UInt64](
            repeating: 0,
            count: pitch * (height + 1)
        )

        for y in 0..<height {
            var rowSum: UInt64 = 0
            for x in 0..<width {
                rowSum += UInt64(pixels[y * width + x])
                table[(y + 1) * pitch + x + 1] =
                    table[y * pitch + x + 1] + rowSum
            }
        }

        self.width = width
        self.height = height
        self.pitch = pitch
        self.prefix = table
    }

    func sum(
        x0: Int, y0: Int, x1: Int, y1: Int
    ) throws -> UInt64 {
        guard x0 >= 0, y0 >= 0,
              x0 <= x1, y0 <= y1,
              x1 <= width, y1 <= height else {
            throw IntegralError.invalidRectangle
        }

        let right = prefix[y1 * pitch + x1]
            - prefix[y0 * pitch + x1]
        let left = prefix[y1 * pitch + x0]
            - prefix[y0 * pitch + x0]
        return right - left
    }
}

Notice that the input limits are checked before multiplication. If you extend this to arbitrary dimensions, use overflow-reporting multiplication and addition, and check the memory budget before allocating. Do not calculate the array capacity first and only then check whether the result is too large.

Check every rectangle with an independent algorithm

Append the following code to the same file. The fixture deliberately uses different pixel values: on a uniform image, shifted coordinates might still produce the same result. The reference algorithm iterates directly over the pixels without reusing the summed-area formula, so the same mistake is not copied into both implementations.

let pixels: [UInt8] = [
    1, 2, 4, 8,
    3, 5, 7, 9,
    6, 0, 2, 1
]
let width = 4
let height = 3
let integral = try IntegralImage(
    pixels: pixels, width: width, height: height
)

for y0 in 0...height {
    for y1 in y0...height {
        for x0 in 0...width {
            for x1 in x0...width {
                var expected: UInt64 = 0
                for y in y0..<y1 {
                    for x in x0..<x1 {
                        expected += UInt64(pixels[y * width + x])
                    }
                }
                let actual = try integral.sum(
                    x0: x0, y0: y0, x1: x1, y1: y1
                )
                precondition(actual == expected)
            }
        }
    }
}

do {
    _ = try integral.sum(x0: 0, y0: 0, x1: 5, y1: 1)
    preconditionFailure("Expected invalid rectangle")
} catch IntegralError.invalidRectangle {
}

Run xcrun swift IntegralCheck.swift. The check passes only if the program finishes normally with exit code zero. It covers single pixels, the full image, edge-touching rectangles, and empty rectangles. Add rejection tests for reversed coordinates, negative coordinates, mismatched pixel counts, and dimensions above the limit. Confirm that invalid inputs are not silently clipped into valid ones.

Check integer and memory limits separately

A nonnegative result does not make every subtraction order safe. The code first calculates the sums of two vertical strips, then subtracts the left strip from the right, ensuring that no intermediate result is negative. Translating the mathematical formula directly into a chain of unsigned subtractions can cause an intermediate underflow.

Create three more kinds of fixtures: all zeros, all 255, and a single nonzero pixel. For an all-255 image, the full-image sum should be 255 × width × height. For the single-pixel fixture, check that the pixel contributes only when the rectangle contains it. These two kinds of property checks help fill the coverage gaps left by fixed examples.

With eight-byte entries, the prefix table uses approximately (width+1) × (height+1) × 8 bytes. The largest table in this example is about 32 MiB, in addition to the input, decoding buffers, and temporary copies. Before increasing the dimension limits, estimate peak memory use from all buffers that are alive at the same time, not just the source image’s file size.

Validate each layer when integrating with iOS

First move the pure algorithm into the project’s test target, keeping the fixtures above. Then check the image adapter. Real bitmap data may include padding at the end of each row, so do not assume that every row contains exactly one byte per pixel of width. The adapter should read the actual row stride, produce the agreed grayscale array row by row, and use a fixed color-conversion policy.

When converting a UI selection to pixel coordinates, make the sequence explicit: handle orientation first, calculate scaling next, and then apply your rounding policy. You might round the start down and the end up, or follow another application-specific rule. Every rule needs concrete examples; do not rely on integer conversion happening to truncate.

Final acceptance checks should confirm that the sums of adjacent, nonoverlapping rectangles add up to the sum of their combined region; averaging an empty selection does not divide by zero; changing the image rebuilds the prefix table; and canceling a background task prevents results for the old image from being published. A summed-area table is valid only for the pixels used to build it. Unchanged coordinates do not mean that an old table is still reusable. Keep the tiny fixtures and image-adapter examples so that, the next time you optimize storage or parallelize table construction, you can tell whether the speedup has changed the results.

Frequently asked questions

Is a summed-area table worthwhile for one rectangle?

Usually not. Building it scans the entire image and allocates a prefix table. It pays off when many region queries reuse the same pixels.

Can UInt64 arithmetic still fail?

Yes. An intermediate subtraction can underflow even when the final sum is nonnegative. Compute two nonnegative vertical strip sums first, then subtract them.

Get your own cloud Mac

A dedicated physical machine, not a virtual machine. Rent by the day, with same-day activation. Sign in to open the remote desktop in your browser. If you need help, submit a support ticket in the console.

Get a cloud Mac

Move your next build to a cloud Mac

A dedicated physical machine, rented by the day and activated the day you order. Sign in to open the desktop in your browser. If you need help, submit a support ticket in the console.