BitMatrix.java
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.common;
import java.util.Arrays;
/**
* <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common
* module, x is the column position, and y is the row position. The ordering is always x, y.
* The origin is at the top-left.</p>
*
* <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins
* with a new int. This is done intentionally so that we can copy out a row into a BitArray very
* efficiently.</p>
*
* <p>The ordering of bits is row-major. Within each int, the least significant bits are used first,
* meaning they represent lower x values. This is compatible with BitArray's implementation.</p>
*
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class BitMatrix implements Cloneable {
private int width;
private int height;
private int rowSize;
private int[] bits;
/**
* Creates an empty square {@code BitMatrix}.
*
* @param dimension height and width
*/
public BitMatrix(int dimension) {
this(dimension, dimension);
}
/**
* Creates an empty {@code BitMatrix}.
*
* @param width bit matrix width
* @param height bit matrix height
*/
public BitMatrix(int width, int height) {
if (width < 1 || height < 1) {
throw new IllegalArgumentException("Both dimensions must be greater than 0");
}
this.width = width;
this.height = height;
this.rowSize = (width + 31) / 32;
bits = new int[rowSize * height];
}
private BitMatrix(int width, int height, int rowSize, int[] bits) {
this.width = width;
this.height = height;
this.rowSize = rowSize;
this.bits = bits;
}
/**
* Interprets a 2D array of booleans as a {@code BitMatrix}, where "true" means an "on" bit.
*
* @param image bits of the image, as a row-major 2D array. Elements are arrays representing rows
* @return {@code BitMatrix} representation of image
*/
public static BitMatrix parse(boolean[][] image) {
int height = image.length;
int width = image[0].length;
BitMatrix bits = new BitMatrix(width, height);
for (int i = 0; i < height; i++) {
boolean[] imageI = image[i];
for (int j = 0; j < width; j++) {
if (imageI[j]) {
bits.set(j, i);
}
}
}
return bits;
}
public static BitMatrix parse(String stringRepresentation, String setString, String unsetString) {
if (stringRepresentation == null) {
throw new IllegalArgumentException();
}
boolean[] bits = new boolean[stringRepresentation.length()];
int bitsPos = 0;
int rowStartPos = 0;
int rowLength = -1;
int nRows = 0;
int pos = 0;
while (pos < stringRepresentation.length()) {
if (stringRepresentation.charAt(pos) == '\n' ||
stringRepresentation.charAt(pos) == '\r') {
if (bitsPos > rowStartPos) {
if (rowLength == -1) {
rowLength = bitsPos - rowStartPos;
} else if (bitsPos - rowStartPos != rowLength) {
throw new IllegalArgumentException("row lengths do not match");
}
rowStartPos = bitsPos;
nRows++;
}
pos++;
} else if (stringRepresentation.startsWith(setString, pos)) {
pos += setString.length();
bits[bitsPos] = true;
bitsPos++;
} else if (stringRepresentation.startsWith(unsetString, pos)) {
pos += unsetString.length();
bits[bitsPos] = false;
bitsPos++;
} else {
throw new IllegalArgumentException(
"illegal character encountered: " + stringRepresentation.substring(pos));
}
}
// no EOL at end?
if (bitsPos > rowStartPos) {
if (rowLength == -1) {
rowLength = bitsPos - rowStartPos;
} else if (bitsPos - rowStartPos != rowLength) {
throw new IllegalArgumentException("row lengths do not match");
}
nRows++;
}
BitMatrix matrix = new BitMatrix(rowLength, nRows);
for (int i = 0; i < bitsPos; i++) {
if (bits[i]) {
matrix.set(i % rowLength, i / rowLength);
}
}
return matrix;
}
/**
* <p>Gets the requested bit, where true means black.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
* @return value of given bit in matrix
*/
public boolean get(int x, int y) {
int offset = y * rowSize + (x >>> 5);
return ((bits[offset] >>> (x & 0x1f)) & 1) != 0;
}
/**
* Finds the next set bit in the given row at or after {@code fromX}.
*
* @param fromX first column to check (inclusive)
* @param y row to search
* @return column of first bit that is set at or beyond {@code fromX} in row {@code y},
* or {@code width} if none are set
* @see #getNextUnset(int, int)
*/
public int getNextSet(int fromX, int y) {
return getNext(fromX, y, 0);
}
/**
* Finds the next unset bit in the given row at or after {@code fromX}.
*
* @param fromX first column to check (inclusive)
* @param y row to search
* @return column of first bit that is unset at or beyond {@code fromX} in row {@code y},
* or {@code width} if none are unset
* @see #getNextSet(int, int)
*/
public int getNextUnset(int fromX, int y) {
return getNext(fromX, y, -1);
}
private int getNext(int fromX, int y, int xorMask) {
if (fromX >= width) {
return width;
}
int rowOffset = y * rowSize;
int wordIndex = fromX >>> 5;
int currentBits = bits[rowOffset + wordIndex] ^ xorMask;
// mask off lesser bits first
currentBits &= -(1 << (fromX & 0x1F));
while (currentBits == 0) {
if (++wordIndex == rowSize) {
return width;
}
currentBits = bits[rowOffset + wordIndex] ^ xorMask;
}
int result = (wordIndex << 5) + Integer.numberOfTrailingZeros(currentBits);
return Math.min(result, width);
}
/**
* <p>Sets the given bit to true.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/
public void set(int x, int y) {
int offset = y * rowSize + (x >>> 5);
bits[offset] |= 1 << (x & 0x1f);
}
public void unset(int x, int y) {
int offset = y * rowSize + (x >>> 5);
bits[offset] &= ~(1 << (x & 0x1f));
}
/**
* <p>Flips the given bit.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/
public void flip(int x, int y) {
int offset = y * rowSize + (x >>> 5);
bits[offset] ^= 1 << (x & 0x1f);
}
/**
* <p>Flips every bit in the matrix.</p>
*/
public void flip() {
int max = bits.length;
for (int i = 0; i < max; i++) {
bits[i] = ~bits[i];
}
// Clear padding bits beyond the logical width in the last int of each row
int remainder = width % 32;
if (remainder != 0) {
int mask = (1 << remainder) - 1;
for (int y = 0; y < height; y++) {
int offset = y * rowSize + rowSize - 1;
bits[offset] &= mask;
}
}
}
/**
* Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
* mask bit is set.
*
* @param mask XOR mask
*/
public void xor(BitMatrix mask) {
if (width != mask.width || height != mask.height || rowSize != mask.rowSize) {
throw new IllegalArgumentException("input matrix dimensions do not match");
}
int[] maskBits = mask.bits;
for (int i = 0; i < bits.length; i++) {
bits[i] ^= maskBits[i];
}
}
/**
* Clears all bits (sets to false).
*/
public void clear() {
Arrays.fill(bits, 0);
}
/**
* <p>Sets a square region of the bit matrix to true.</p>
*
* @param left The horizontal position to begin at (inclusive)
* @param top The vertical position to begin at (inclusive)
* @param width The width of the region
* @param height The height of the region
*/
public void setRegion(int left, int top, int width, int height) {
if (top < 0 || left < 0) {
throw new IllegalArgumentException("Left and top must be nonnegative");
}
if (height < 1 || width < 1) {
throw new IllegalArgumentException("Height and width must be at least 1");
}
int right = left + width;
int bottom = top + height;
if (bottom > this.height || right > this.width) {
throw new IllegalArgumentException("The region must fit inside the matrix");
}
for (int y = top; y < bottom; y++) {
int offset = y * rowSize;
for (int x = left; x < right; x++) {
bits[offset + (x >>> 5)] |= 1 << (x & 0x1f);
}
}
}
/**
* A fast method to retrieve one row of data from the matrix as a BitArray.
*
* @param y The row to retrieve
* @param row An optional caller-allocated BitArray, will be allocated if null or too small
* @return The resulting BitArray - this reference should always be used even when passing
* your own row
*/
public BitArray getRow(int y, BitArray row) {
if (row == null || row.getSize() < width) {
row = new BitArray(width);
}
int[] rowBits = row.getBitArray();
System.arraycopy(bits, y * rowSize, rowBits, 0, rowSize);
if (rowBits.length > rowSize) {
Arrays.fill(rowBits, rowSize, rowBits.length, 0);
}
return row;
}
/**
* @param y row to set
* @param row {@link BitArray} to copy from
*/
public void setRow(int y, BitArray row) {
System.arraycopy(row.getBitArray(), 0, bits, y * rowSize, rowSize);
}
/**
* Modifies this {@code BitMatrix} to represent the same but rotated the given degrees (0, 90, 180, 270)
*
* @param degrees number of degrees to rotate through counter-clockwise (0, 90, 180, 270)
*/
public void rotate(int degrees) {
switch (degrees % 360) {
case 0:
return;
case 90:
rotate90();
return;
case 180:
rotate180();
return;
case 270:
rotateQuarterTurn(false);
return;
}
throw new IllegalArgumentException("degrees must be a multiple of 0, 90, 180, or 270");
}
/**
* Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
*/
public void rotate180() {
int[] bits = this.bits;
int totalWords = height * rowSize;
for (int i = 0, j = totalWords - 1; i <= j; i++, j--) {
int left = Integer.reverse(bits[i]);
int right = Integer.reverse(bits[j]);
bits[i] = right;
bits[j] = left;
}
int leftOffset = rowSize * 32 - width;
if (leftOffset != 0) {
int rightShift = 32 - leftOffset;
for (int rowStart = 0; rowStart < totalWords; rowStart += rowSize) {
int current = bits[rowStart] >>> leftOffset;
for (int i = 1; i < rowSize; i++) {
int next = bits[rowStart + i];
bits[rowStart + i - 1] = current | (next << rightShift);
current = next >>> leftOffset;
}
bits[rowStart + rowSize - 1] = current;
}
}
}
/**
* Modifies this {@code BitMatrix} to represent the same but rotated 90 degrees counterclockwise
*/
public void rotate90() {
rotateQuarterTurn(true);
}
private void rotateQuarterTurn(boolean counterClockwise) {
int newWidth = height;
int newHeight = width;
int newRowSize = (newWidth + 31) / 32;
int[] newBits = new int[newRowSize * newHeight];
int[] tile = new int[32];
int srcStep = counterClockwise ? rowSize : -rowSize;
int dstStep = counterClockwise ? -newRowSize : newRowSize;
for (int wy = 0; wy < newRowSize; wy++) {
int by = wy << 5;
int blockH = Math.min(32, height - by);
int srcRowBase = (counterClockwise ? by : height - 1 - by) * rowSize;
for (int wx = 0; wx < rowSize; wx++) {
int any = 0;
int srcIndex = srcRowBase + wx;
for (int dy = 0; dy < blockH; dy++, srcIndex += srcStep) {
int w = bits[srcIndex];
tile[dy] = w;
any |= w;
}
if (any == 0) {
continue;
}
if (blockH < 32) {
Arrays.fill(tile, blockH, 32, 0);
}
transpose32(tile);
int bx = wx << 5;
int blockW = Math.min(32, width - bx);
int dstIndex = (counterClockwise ? newHeight - 1 - bx : bx) * newRowSize + wy;
for (int dx = 0; dx < blockW; dx++, dstIndex += dstStep) {
newBits[dstIndex] = tile[dx];
}
}
}
width = newWidth;
height = newHeight;
rowSize = newRowSize;
bits = newBits;
}
private static void transpose32(int[] t) {
// 5-stage 32x32 bit-matrix transpose (Hacker's Delight, Fig. 7-2)
for (int stage = 16, mask = 0x0000FFFF; stage > 0; stage >>>= 1, mask ^= mask << stage) {
for (int i = 0; i < 32; i += stage << 1) {
for (int j = i, end = i + stage; j < end; j++) {
int a = t[j];
int b = t[j + stage];
int diff = ((a >>> stage) ^ b) & mask;
t[j] = a ^ (diff << stage);
t[j + stage] = b ^ diff;
}
}
}
}
/**
* This is useful in detecting the enclosing rectangle of a 'pure' barcode.
*
* @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white
*/
public int[] getEnclosingRectangle() {
int left = width;
int top = height;
int right = -1;
int bottom = -1;
for (int y = 0; y < height; y++) {
int rowOffset = y * rowSize;
for (int x32 = 0; x32 < rowSize; x32++) {
int theBits = bits[rowOffset + x32];
if (theBits != 0) {
if (y < top) {
top = y;
}
if (y > bottom) {
bottom = y;
}
int xBase = x32 << 5;
if (xBase < left) {
left = Math.min(left, xBase + Integer.numberOfTrailingZeros(theBits));
}
if (xBase + 31 > right) {
right = Math.max(right, xBase + 31 - Integer.numberOfLeadingZeros(theBits));
}
}
}
}
if (right < left || bottom < top) {
return null;
}
return new int[] {left, top, right - left + 1, bottom - top + 1};
}
/**
* This is useful in detecting a corner of a 'pure' barcode.
*
* @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white
*/
public int[] getTopLeftOnBit() {
int bitsOffset = 0;
while (bitsOffset < bits.length && bits[bitsOffset] == 0) {
bitsOffset++;
}
if (bitsOffset == bits.length) {
return null;
}
int y = bitsOffset / rowSize;
int x = (bitsOffset % rowSize) << 5;
x += Integer.numberOfTrailingZeros(bits[bitsOffset]);
return new int[] {x, y};
}
public int[] getBottomRightOnBit() {
int bitsOffset = bits.length - 1;
while (bitsOffset >= 0 && bits[bitsOffset] == 0) {
bitsOffset--;
}
if (bitsOffset < 0) {
return null;
}
int y = bitsOffset / rowSize;
int x = (bitsOffset % rowSize) << 5;
x += 31 - Integer.numberOfLeadingZeros(bits[bitsOffset]);
return new int[] {x, y};
}
/**
* @return The width of the matrix
*/
public int getWidth() {
return width;
}
/**
* @return The height of the matrix
*/
public int getHeight() {
return height;
}
/**
* @return The row size of the matrix
*/
public int getRowSize() {
return rowSize;
}
int[] getBits() {
return bits;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BitMatrix)) {
return false;
}
BitMatrix other = (BitMatrix) o;
return width == other.width && height == other.height && rowSize == other.rowSize &&
Arrays.equals(bits, other.bits);
}
@Override
public int hashCode() {
int hash = width;
hash = 31 * hash + width;
hash = 31 * hash + height;
hash = 31 * hash + rowSize;
hash = 31 * hash + Arrays.hashCode(bits);
return hash;
}
/**
* @return string representation using "X" for set and " " for unset bits
*/
@Override
public String toString() {
return toString("X ", " ");
}
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @return string representation of entire matrix utilizing given strings
*/
public String toString(String setString, String unsetString) {
return buildToString(setString, unsetString, "\n");
}
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @param lineSeparator newline character in string representation
* @return string representation of entire matrix utilizing given strings and line separator
* @deprecated call {@link #toString(String,String)} only, which uses \n line separator always
*/
@Deprecated
public String toString(String setString, String unsetString, String lineSeparator) {
return buildToString(setString, unsetString, lineSeparator);
}
private String buildToString(String setString, String unsetString, String lineSeparator) {
StringBuilder result = new StringBuilder(height * (width + 1));
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
result.append(get(x, y) ? setString : unsetString);
}
result.append(lineSeparator);
}
return result.toString();
}
@Override
public BitMatrix clone() {
return new BitMatrix(width, height, rowSize, bits.clone());
}
}