Algorithm Search⌘K

Algorithmcore

Local binary patterns

Also called LBP, LBP texture descriptor.

Code each pixel by the signs of the differences to P neighbors on a circle, then describe a region by the histogram of the codes, often in the uniform or rotation invariant form.

Time
O(W H P + 2^P P) worst · average · best
Space
O(2^P) extra
Where
H = the image height in pixels; P = the number of neighbors on the circle; W = the image width in pixels
Properties
deterministicexactgray scale invariantnot heuristicnot rotation invariant
Origin
Timo Ojala, Matti Pietikainen, David Harwood, 1996

Local binary patterns (LBP) describe the texture of a region of an image. For each pixel, the method compares PP neighbors on a circle of radius RR with the center. Each comparison gives one bit, so each pixel gets a PP-bit code. The descriptor of the region is the histogram of the codes. Only the signs of the differences go into the code, so the code does not change when the brightness of the image changes by any increasing function. A mapping of the codes, such as the uniform code u2 or the rotation invariant uniform code riu2, makes the histogram shorter and more stable. LBP is a feature descriptor for regions and is a close relative of the census transform in stereo.

In plain words

Look at a pixel and at a ring of pixels around it. Write a 1 for each ring pixel that is at least as bright as the center, and a 0 for each that is darker. Read the bits around the ring as one binary number. A flat area, a spot, an edge and a corner give different numbers. Do this for every pixel of a region and count how often each number occurs. The counts describe the texture of the region. If you make the whole image brighter, or increase the contrast, each comparison gives the same answer, so the counts stay the same. Most counts come from simple patterns with at most two changes between 0 and 1 around the ring. Many methods keep these simple patterns and put all other patterns into one shared bin.

The problem

The input is a gray digital image II with WW columns and HH rows, a number of neighbors P≥1P \ge 1, a radius R>0R > 0 and a mapping of codes to labels. A pixel is (u,v)(u, v), with uu the column (to the right) and vv the row (down). Neighbor pp, for p=0,…,P−1p = 0, \dots, P - 1, of the center c=(u,v)c = (u, v) is at

(u+Rcos⁡2πpP,  v−Rsin⁡2πpP).\Big(u + R\cos\tfrac{2\pi p}{P},\; v - R\sin\tfrac{2\pi p}{P}\Big).

So neighbor 0 is to the right, and the neighbors go counterclockwise on the screen. If the point is not a pixel center, its value gpg_p comes from bilinear interpolation of the four pixels around it. The paper of 2002 places neighbor pp at (−Rsin⁡(2πp/P),Rcos⁡(2πp/P))(-R\sin(2\pi p/P), R\cos(2\pi p/P)); another start or direction only turns the bit order by a fixed amount. With gcg_c the value of the center and s(x)=1s(x) = 1 for x≥0x \ge 0 and s(x)=0s(x) = 0 for x<0x < 0, the code is

LBPP,R(c)=∑p=0P−1s(gp−gc) 2p.\mathrm{LBP}_{P,R}(c) = \sum_{p=0}^{P-1} s(g_p - g_c)\, 2^p .

The number of circular 0/1 changes of a code is

U=∣s(gP−1−gc)−s(g0−gc)∣+∑p=1P−1∣s(gp−gc)−s(gp−1−gc)∣.U = \big|s(g_{P-1} - g_c) - s(g_0 - g_c)\big| + \sum_{p=1}^{P-1} \big|s(g_p - g_c) - s(g_{p-1} - g_c)\big| .

A code is uniform when U≤2U \le 2. The four common mappings are:

  • none: the code itself, with 2P2^P labels.
  • u2: one label for each uniform code and one shared label for all other codes. This gives P(P−1)+3P(P - 1) + 3 labels, 59 for P=8P = 8.
  • riu2: for a uniform code, the number of ones, which is 0,…,P0, \dots, P; for any other code, P+1P + 1. This gives P+2P + 2 labels, 10 for P=8P = 8.
  • ri: the smallest of the PP circular rotations of the code. This gives one label for each binary necklace of length PP, 36 for P=8P = 8.

The output is the histogram of the labels over all pixels whose circle is inside the image. A region descriptor is the same histogram over one region.

The algorithm

  1. LBP(I, P, R, map) ▷ map gives the label of each P-bit code
  2. 1for p = 0 to P - 1 do (du_p, dv_p) ← (R cos(2πp/P), -R sin(2πp/P))
  3. 2h ← a histogram of zeros, one bin for each label of map
  4. 3for each pixel c = (u, v) whose circle is inside I do
  5. 4code ← 0
  6. 5for p = 0 to P - 1 do
  7. 6g_p ← the bilinear value of I at (u + du_p, v + dv_p)
  8. 7if g_p - g_c ≥ 0 then code ← code + 2^p
  9. 8h[map(code)] ← h[map(code)] + 1
  10. 9return h

The mapping is a table of 2P2^P entries that the code builds once. For u2 and riu2 it counts the changes UU of each code, and for ri it takes the smallest rotation. The comparison of two regions uses a distance of histograms. Ojala and his coauthors used the log-likelihood statistic and other distances; the chi-square distance ∑b(hb−kb)2/(hb+kb)\sum_b (h_b - k_b)^2 / (h_b + k_b) is common, and Ahonen, Hadid and Pietikainen used a weighted form of it for faces.

Example

Take the 3×33 \times 3 image below with P=8P = 8, R=1R = 1 and the center value gc=6g_c = 6.

652761987\begin{matrix} 6 & 5 & 2 \\ 7 & 6 & 1 \\ 9 & 8 & 7 \end{matrix}

The neighbors 0, 2, 4 and 6 are pixel centers: right 1, top 5, left 7 and bottom 8. The neighbors 1, 3, 5 and 7 are at a distance of about 0.707 along both axes and need interpolation. The weight of the nearest corner is (1−0.2929)2≈0.5(1 - 0.2929)^2 \approx 0.5, the two side weights are 0.2929×0.7071≈0.20710.2929 \times 0.7071 \approx 0.2071 and the far weight is 0.29292≈0.08580.2929^2 \approx 0.0858. The values and bits are:

pp position gpg_p bit
0 right 1 0
1 top right 2.7574 0
2 top 5 0
3 top left 6.0000 1
4 left 7 1
5 bottom left 8.1213 1
6 bottom 8 1
7 bottom right 5.8787 0

Neighbor 3 is a tie. Its cell has the corners 6, 5, 7 and 6, and since 5+7=2×65 + 7 = 2 \times 6 the interpolated value is exactly 6, so the bit is 1. The code is 23+24+25+26=1202^3 + 2^4 + 2^5 + 2^6 = 120, which is 01111000 in binary. It has two changes, so it is uniform. Its riu2 label is 4, the number of ones. Its u2 label in our table is 25, and its ri label is the smallest rotation 00001111, which is 15.

Correctness

The method is a definition, so correctness means that the histogram counts the labels of the codes as defined, and that the mappings have the stated sizes and invariances. The proof in proofs/correctness.md shows these facts:

  • Without interpolation, the code does not change under any strictly increasing change of the gray values. With interpolation, it does not change under g↦ag+bg \mapsto a g + b with a>0a > 0.
  • There are exactly P(P−1)+2P(P - 1) + 2 uniform codes, so u2 has P(P−1)+3P(P - 1) + 3 labels. Each uniform code with kk ones is a run of kk ones on the circle, so riu2 has P+2P + 2 labels and is constant on each rotation class.
  • If 44 divides PP, a rotation of the image by 90 degrees moves neighbor pp to neighbor p+P/4p + P/4, and bilinear interpolation commutes with the rotation. So each code becomes a circular rotation of itself, and the riu2 and ri histograms do not change.
Proof: Correctness of local binary patternsfull

Fix P≥1P \ge 1 and R>0R > 0. For a center cc let gcg_c be its value and g0,…,gP−1g_0, \dots, g_{P-1} the values of its neighbors, taken from pixels or by bilinear interpolation. Write bp=s(gp−gc)b_p = s(g_p - g_c), with s(x)=1s(x) = 1 for x≥0x \ge 0 and 00 otherwise, so the code is ∑pbp2p\sum_p b_p 2^p. Indices of bits are taken modulo PP. A rotation of a code by kk is the code with bits bp′=bp−kb'_p = b_{p - k}.

Lemma 1 (the algorithm computes the defined histogram). LBP returns, for each label ℓ\ell, the number of pixels cc with the circle inside the image and map(LBPP,R(c))=ℓ\mathrm{map}(\mathrm{LBP}_{P,R}(c)) = \ell.

Proof. Line L1 computes the offsets of the definition. For a fixed cc, line L4 sets the code to 0, and after the iteration pp of lines L5 to L7 the code equals ∑q≤pbq2q\sum_{q \le p} b_q 2^q, since line L7 adds 2p2^p exactly when gp−gc≥0g_p - g_c \ge 0. After the loop the code is LBPP,R(c)\mathrm{LBP}_{P,R}(c). Line L8 adds 1 to the bin of its label. Line L3 visits each pixel with its circle inside the image once, so each such pixel adds 1 to exactly one bin, the bin of its label. □\square

Lemma 2 (gray-scale invariance). Let ff be strictly increasing. If all neighbors are pixel centers, the image f(I)f(I) has the same codes as II. With interpolation, the same holds for f(x)=ax+bf(x) = a x + b with a>0a > 0.

Proof. If gpg_p and gcg_c are pixel values, f(gp)≥f(gc)f(g_p) \ge f(g_c) holds exactly when gp≥gcg_p \ge g_c, since ff is strictly increasing. So each bit is the same. Bilinear interpolation is a weighted sum ∑kwkxk\sum_k w_k x_k with weights wk≥0w_k \ge 0 and ∑kwk=1\sum_k w_k = 1. So the interpolated value of aI+ba I + b is agp+ba g_p + b, and agp+b−(agc+b)=a(gp−gc)a g_p + b - (a g_c + b) = a (g_p - g_c) has the sign of gp−gcg_p - g_c for a>0a > 0. So each bit is the same. □\square

Lemma 3 (uniform codes). For P≥2P \ge 2 there are exactly P(P−1)+2P(P - 1) + 2 codes with U≤2U \le 2. The u2 mapping has P(P−1)+3P(P - 1) + 3 labels.

Proof. UU counts the positions pp with bp≠bp−1b_p \ne b_{p-1} on a circle, so UU is even. The codes with U=0U = 0 are the two constant codes. A code with U=2U = 2 has exactly one run of ones and one run of zeros on the circle. It is fixed by the start of the run of ones (PP choices) and the length of the run, from 1 to P−1P - 1 (P−1P - 1 choices), and different choices give different codes. So there are P(P−1)P(P - 1) such codes, and P(P−1)+2P(P - 1) + 2 uniform codes. The u2 mapping gives each one its own label and adds one shared label. □\square

Lemma 4 (riu2). UU and the number of ones do not change under rotation of the code. Two uniform codes with the same number kk of ones are rotations of each other. So riu2 is constant on rotation classes, and it has exactly P+2P + 2 labels.

Proof. A rotation moves the bits around the circle and keeps both the multiset of bits and the set of adjacent pairs, so it keeps the number of ones and UU. So the riu2 label, which depends only on these two numbers, is constant on a rotation class. A uniform code with 0<k<P0 < k < P ones is one run of kk ones, and any two runs of the same length differ by a rotation. The constant codes are the only codes with k=0k = 0 and k=Pk = P. So the uniform codes give the labels 0,…,P0, \dots, P, each one used, and the other codes give the label P+1P + 1, which is used for P≥4P \ge 4 (the code 0101…0101\dots restricted to the first four bits, with the other bits 0, has U=4U = 4). This gives P+2P + 2 labels. □\square

Lemma 5 (rotation by 90 degrees). Let 44 divide PP and let JJ be the image II turned by 90 degrees, so that the pixel at the offset (Δu,Δv)(\Delta u, \Delta v) from a center goes to the offset (Δv,−Δu)(\Delta v, -\Delta u) from the new center. Then the code of each center in JJ is the rotation by P/4P/4 of the code of the same center in II.

Proof. Neighbor pp is at the angle αp=2πp/P\alpha_p = 2\pi p / P, at the offset (Rcos⁡αp,−Rsin⁡αp)(R\cos\alpha_p, -R\sin\alpha_p). The turn maps it to (−Rsin⁡αp,−Rcos⁡αp)=(Rcos⁡(αp+π/2),−Rsin⁡(αp+π/2))(-R\sin\alpha_p, -R\cos\alpha_p) = (R\cos(\alpha_p + \pi/2), -R\sin(\alpha_p + \pi/2)), which is the offset of neighbor p+P/4p + P/4. The turn maps the grid to itself and each unit cell to a unit cell. Bilinear interpolation in a cell is the unique function of the form α+βx+γy+δxy\alpha + \beta x + \gamma y + \delta x y that takes the four corner values, and this form is kept by the map (x,y)↦(y,−x)(x, y) \mapsto (y, -x). So the interpolated value of JJ at the new position equals the interpolated value of II at the old position. So bit p+P/4p + P/4 of the new code equals bit pp of the old code. □\square

Theorem. LBP returns the histogram of the labels of the codes. The codes are invariant under the changes of Lemma 2. For P=8P = 8 the u2, riu2 and ri mappings have 59, 10 and 36 labels. If 44 divides PP, the riu2 and ri histograms do not change when the image turns by 90 degrees.

Proof. Lemma 1 gives the histogram and Lemma 2 the invariance. Lemma 3 gives 8⋅7+3=598 \cdot 7 + 3 = 59 and Lemma 4 gives 8+2=108 + 2 = 10. The ri labels are the rotation classes of 8-bit strings, the binary necklaces of length 8. By Burnside's lemma their number is 18∑d∣8φ(d)28/d=18(256+16+2⋅4+4⋅2)=36\frac{1}{8}\sum_{d \mid 8} \varphi(d) 2^{8/d} = \frac{1}{8}(256 + 16 + 2 \cdot 4 + 4 \cdot 2) = 36. By Lemma 5 each code of the turned image is a rotation of a code of the original image, and the turned image has the same set of centers with the circle inside. By Lemma 4, riu2 is constant on rotation classes, and so is ri by its definition. So each pixel adds 1 to the same bin in both histograms. □\square

The code rounds gp−gcg_p - g_c to 9 decimals before the sign test. In exact arithmetic Lemma 5 is exact. In floating point the two interpolations can round differently, and the rounding keeps a difference that is zero in exact arithmetic at zero in both images.

Complexity

The model is the word RAM with gray values in one word and P≤wP \le w for the word size ww.

  • Line L1 takes O(P)O(P) time. Building the table of the mapping takes O(2PP)O(2^P P) time, since each code needs O(P)O(P) time to count changes or to find the smallest rotation. The table needs O(2P)O(2^P) words.
  • Lines L5 to L7 take O(P)O(P) time per pixel, with O(1)O(1) time for each bilinear value. Over at most WHW H pixels this is O(WHP)O(W H P).
  • The histogram needs at most 2P2^P words, and P+2P + 2 words for riu2.

So the time is O(WHP+2PP)O(W H P + 2^P P) and the extra space is O(2P)O(2^P). For P=8P = 8 the table has 256 entries, and the cost is close to 8 comparisons per pixel. Large PP, such as 24, makes the table large, and implementations then compute UU and the number of ones on the fly.

Properties

  • Gray-scale invariance. Only signs of differences enter the code. Without interpolation, any strictly increasing change of the gray values keeps every code. With interpolation, an affine change with positive gain keeps every code; a nonlinear increasing change can move an interpolated value across the center value.
  • Rotation. The plain code depends on the orientation of the texture. The ri and riu2 mappings remove the dependence for rotations by multiples of 360/P360/P degrees about pixel centers, and only approximately for other angles, since the image grid is not rotation invariant.
  • Locality. Each code depends on a disk of radius RR. The histogram loses the position of the codes; a grid of regions with one histogram per region keeps a coarse position.
  • Noise. On flat areas small noise flips many bits, because a difference near zero has a random sign. The uniform mappings move these random codes into the shared bin.
  • Not a contrast measure. LBP keeps the pattern but drops the strength of the differences. The 1996 and 2002 papers pair it with a local variance or contrast measure for that reason.

Variants and improvements

  • Multiresolution LBP. Ojala, Pietikainen and Maenpaa combine histograms for several (P,R)(P, R), such as (8,1)(8, 1), (16,2)(16, 2) and (24,3)(24, 3).
  • LBP with contrast. The joint histogram of the code and the local variance, LBP/VAR, adds the strength of the texture.
  • Spatially enhanced histograms. Ahonen and his coauthors split a face into a grid of regions, take one u2 histogram per region and join them. A weighted chi-square distance gives more weight to regions such as the eyes. Compare the cells of HOG and spatial pyramid matching.
  • Census transform. The census transform uses the same comparisons with a square window and compares the bit strings by Hamming distance for stereo, without a histogram.
  • Binary descriptors. BRIEF compares pairs of points in a patch with each other, not with the center, and keeps the bit string as the descriptor.
  • Other variants. Local ternary patterns add a dead zone around the center value against noise, and LBP-TOP takes codes on three orthogonal planes of a video volume.

When to use it

Use LBP for texture classification and for face description when you need a cheap descriptor that does not change with lighting. It works well on small regions with a lot of texture and on hardware with integer arithmetic only. Use riu2 when the texture can be rotated, and u2 when the orientation carries information. For matching keypoints between views, a descriptor made for keypoints, such as SIFT or ORB, is a better choice, because LBP histograms need large regions to be stable.

Pitfalls

  • The sign at zero. The code uses s(0)=1s(0) = 1. A library that uses a strict test gives different codes on flat areas. Flat areas are common in 8-bit images.
  • Floating point ties. An interpolated value can equal the center in exact arithmetic but differ from it by a rounding error. In the example above neighbor 3 is such a tie. Our code rounds the difference to 9 decimals before the sign test. Without this, the code of a pixel can change under a rotation of the image by 90 degrees.
  • Interpolation and monotone changes. Interpolation breaks the invariance under nonlinear increasing changes. If you need that invariance, use integer offsets, such as P=4P = 4 or P=8P = 8 on the square of radius 1.
  • Bit order. Libraries differ in the start neighbor and the direction. The ri and riu2 labels do not depend on this, but u2 labels and plain codes do. Do not compare histograms from two libraries.
  • The u2 label order. The order of the 58 uniform labels is a convention. Our table numbers them in increasing code order.
  • Normalization. Histograms of regions of different sizes need normalization to sum 1 before a distance.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

local_binary_patterns.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-binary-patterns/. The authors are listed in prov/BQGMR7.jsonl.

"""Local binary patterns LBP_{P,R} with the u2, riu2 and ri mappings.

An image is a list of H rows of W numbers; pixel (u, v) is img[v][u], with u
the column (to the right) and v the row (down). Neighbor p of a center pixel
is at the offset (R cos(2 pi p / P), -R sin(2 pi p / P)), so p = 0 is to the
right and the neighbors go counterclockwise on the screen. A neighbor that is
not on a pixel center gets its value by bilinear interpolation.

Bit p of the code is s(g_p - g_c), with s(x) = 1 for x >= 0 and 0 otherwise
(Ojala, Pietikainen and Maenpaa 2002). The interpolated difference is rounded
to 9 decimals before the sign test, so that a difference that is zero in exact
arithmetic is not turned into a tiny positive or negative number by floating
point rounding.

Mappings of a P-bit code to a histogram label:
- "none": the code itself, 2^P labels.
- "u2": one label per uniform code (at most 2 circular 0/1 changes) and one
  shared label for all other codes, P (P - 1) + 3 labels.
- "riu2": the number of ones for a uniform code, P + 1 otherwise, P + 2 labels.
- "ri": the smallest circular rotation of the code, one label per necklace.
"""

import math
from typing import Dict, List, Sequence, Tuple

Image = Sequence[Sequence[float]]


def transitions(code: int, p_count: int) -> int:
    """U(code): the number of circular 0/1 changes in the P-bit code."""
    u = 0
    for p in range(p_count):
        a = (code >> p) & 1
        b = (code >> ((p + 1) % p_count)) & 1
        u += a ^ b
    return u


def min_rotation(code: int, p_count: int) -> int:
    """The smallest value among the P circular rotations of the code."""
    mask = (1 << p_count) - 1
    best = code
    c = code
    for _ in range(p_count - 1):
        c = ((c >> 1) | ((c & 1) << (p_count - 1))) & mask
        best = min(best, c)
    return best


def build_mapping(p_count: int, kind: str) -> Tuple[List[int], int]:
    """Return (table, number of labels): table[code] is the label of the code."""
    size = 1 << p_count
    if kind == "none":
        return list(range(size)), size
    if kind == "riu2":
        table = []
        for code in range(size):
            if transitions(code, p_count) <= 2:
                table.append(bin(code).count("1"))
            else:
                table.append(p_count + 1)
        return table, p_count + 2
    if kind == "u2":
        table = [0] * size
        nxt = 0
        uniform_label: Dict[int, int] = {}
        for code in range(size):
            if transitions(code, p_count) <= 2:
                uniform_label[code] = nxt
                nxt += 1
        other = nxt
        for code in range(size):
            table[code] = uniform_label.get(code, other)
        return table, nxt + 1
    if kind == "ri":
        labels: Dict[int, int] = {}
        table = []
        for code in range(size):
            r = min_rotation(code, p_count)
            if r not in labels:
                labels[r] = len(labels)
            table.append(labels[r])
        return table, len(labels)
    raise ValueError("unknown mapping: " + kind)


def offsets(p_count: int, radius: float) -> List[Tuple[float, float]]:
    """Offsets (du, dv) of the P neighbors, rounded to 12 decimals."""
    out = []
    for p in range(p_count):
        a = 2.0 * math.pi * p / p_count
        du = round(radius * math.cos(a), 12) + 0.0
        dv = round(-radius * math.sin(a), 12) + 0.0
        out.append((du, dv))
    return out


def bilinear(img: Image, x: float, y: float) -> float:
    """Bilinear value at (x, y) = (u, v). Exact for a constant cell."""
    u0 = math.floor(x)
    v0 = math.floor(y)
    fx = x - u0
    fy = y - v0
    if fx == 0.0 and fy == 0.0:
        return img[v0][u0]
    u1 = u0 + 1 if fx > 0.0 else u0
    v1 = v0 + 1 if fy > 0.0 else v0
    a, b = img[v0][u0], img[v0][u1]
    c, d = img[v1][u0], img[v1][u1]
    top = a + fx * (b - a)
    bottom = c + fx * (d - c)
    return top + fy * (bottom - top)


def lbp_codes(img: Image, p_count: int = 8, radius: float = 1.0) -> List[List[int]]:
    """The LBP code of each pixel whose circle lies inside the image.

    Row j of the result holds the codes of the pixels v = m + j, u = m, m + 1, ...
    with the margin m = ceil(R).
    """
    h, w = len(img), len(img[0])
    m = int(math.ceil(radius))
    offs = offsets(p_count, radius)  # @line L1
    rows = []
    for v in range(m, h - m):  # @line L3
        row = []
        for u in range(m, w - m):
            gc = img[v][u]
            code = 0  # @line L4
            for p in range(p_count):  # @line L5
                gp = bilinear(img, u + offs[p][0], v + offs[p][1])  # @line L6
                if round(gp - gc, 9) >= 0:  # @line L7
                    code |= 1 << p
            row.append(code)
        rows.append(row)
    return rows


def lbp_histogram(img: Image, p_count: int = 8, radius: float = 1.0, kind: str = "riu2") -> List[int]:
    """The histogram of the mapped LBP codes over the image."""
    table, nbins = build_mapping(p_count, kind)
    hist = [0] * nbins  # @line L2
    for row in lbp_codes(img, p_count, radius):
        for code in row:
            hist[table[code]] += 1  # @line L8
    return hist  # @line L9


def chi_square(h1: Sequence[float], h2: Sequence[float]) -> float:
    """Chi-square distance sum (a - b)^2 / (a + b), with 0/0 taken as 0."""
    d = 0.0
    for a, b in zip(h1, h2):
        if a + b > 0:
            d += (a - b) * (a - b) / (a + b)
    return d
test_local_binary_patterns.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-binary-patterns/. The authors are listed in prov/BQGMR7.jsonl.

import math
import random

from local_binary_patterns import (
    bilinear,
    build_mapping,
    chi_square,
    lbp_codes,
    lbp_histogram,
    min_rotation,
    offsets,
    transitions,
)


def random_image(rng, w, h, hi=255):
    return [[rng.randint(0, hi) for _ in range(w)] for _ in range(h)]


def rot90(img):
    """Turn the image by 90 degrees: the offset (du, dv) goes to (dv, -du)."""
    h, w = len(img), len(img[0])
    return [[img[v][w - 1 - vv] for v in range(h)] for vv in range(w)]


def necklaces(p):
    """Number of binary necklaces of length p, by Burnside's lemma."""
    total = 0
    for d in range(1, p + 1):
        if p % d == 0:
            phi = sum(1 for k in range(1, d + 1) if math.gcd(k, d) == 1)
            total += phi * 2 ** (p // d)
    return total // p


def test_label_counts_for_p8():
    assert build_mapping(8, "u2")[1] == 59
    assert build_mapping(8, "riu2")[1] == 10
    assert build_mapping(8, "ri")[1] == 36
    assert build_mapping(8, "none")[1] == 256


def test_label_counts_general():
    for p in range(3, 13):
        assert build_mapping(p, "u2")[1] == p * (p - 1) + 3
        assert build_mapping(p, "riu2")[1] == p + 2
        assert build_mapping(p, "ri")[1] == necklaces(p)


def test_transitions_and_rotation_brute_force():
    for p in (4, 6, 8):
        for code in range(1 << p):
            bits = [(code >> i) & 1 for i in range(p)]
            u = sum(1 for i in range(p) if bits[i] != bits[i - 1])
            assert transitions(code, p) == u
            rots = []
            for s in range(p):
                b = bits[s:] + bits[:s]
                rots.append(sum(bit << i for i, bit in enumerate(b)))
            assert min_rotation(code, p) == min(rots)


def test_riu2_counts_ones_of_uniform_codes():
    table, _ = build_mapping(8, "riu2")
    assert table[0b00000000] == 0
    assert table[0b00011100] == 3
    assert table[0b11111111] == 8
    assert table[0b01010101] == 9


def test_offsets_on_axes_are_integers():
    offs = offsets(8, 1.0)
    assert offs[0] == (1.0, 0.0)
    assert offs[2] == (0.0, -1.0)
    assert offs[4] == (-1.0, 0.0)
    assert offs[6] == (0.0, 1.0)


def test_codes_match_direct_comparisons_p4():
    rng = random.Random(1)
    img = random_image(rng, 12, 10, hi=5)
    codes = lbp_codes(img, 4, 1.0)
    nbr = [(1, 0), (0, -1), (-1, 0), (0, 1)]
    for v in range(1, 9):
        for u in range(1, 11):
            want = 0
            for p, (du, dv) in enumerate(nbr):
                if img[v + dv][u + du] >= img[v][u]:
                    want |= 1 << p
            assert codes[v - 1][u - 1] == want


def test_bilinear_is_exact_on_constant_cells_and_corners():
    img = [[7, 7], [7, 7]]
    assert bilinear(img, 0.2928932188, 0.7071067812) == 7
    img = [[0, 10], [20, 30]]
    assert bilinear(img, 1.0, 0.0) == 10
    assert abs(bilinear(img, 0.5, 0.5) - 15.0) < 1e-12


def test_monotone_change_keeps_codes_p4():
    rng = random.Random(2)
    img = random_image(rng, 16, 16, hi=40)
    out = [[x * x * x + 3 * x + 11 for x in row] for row in img]
    assert lbp_codes(img, 4, 1.0) == lbp_codes(out, 4, 1.0)


def test_gray_offset_keeps_codes_p8():
    rng = random.Random(3)
    img = random_image(rng, 16, 16)
    shifted = [[x + 37 for x in row] for row in img]
    assert lbp_codes(img, 8, 1.0) == lbp_codes(shifted, 8, 1.0)


def test_rot90_rotates_codes_and_keeps_riu2_and_ri():
    rng = random.Random(4)
    img = random_image(rng, 20, 20)
    r = rot90(img)
    for kind in ("riu2", "ri"):
        assert lbp_histogram(img, 8, 1.0, kind) == lbp_histogram(r, 8, 1.0, kind)
    # Pixel (u, v) of img goes to (v, W - 1 - u) of r; neighbor p goes to p + 2.
    a = lbp_codes(img, 8, 1.0)
    b = lbp_codes(r, 8, 1.0)
    w = 20
    mask = 255
    for v in range(1, 19):
        for u in range(1, 19):
            code = a[v - 1][u - 1]
            turned = ((code << 2) | (code >> 6)) & mask
            assert b[(w - 1 - u) - 1][v - 1] == turned


def test_histogram_total_and_chi_square():
    rng = random.Random(5)
    img = random_image(rng, 18, 14)
    h = lbp_histogram(img, 8, 2.0, "u2")
    assert len(h) == 59
    assert sum(h) == (18 - 4) * (14 - 4)
    assert chi_square(h, h) == 0.0
    assert abs(chi_square([1, 0, 3], [3, 0, 1]) - 2.0) < 1e-12


def test_texture_classes_are_separated():
    rng = random.Random(6)
    stripes = [[(255 if (u // 2) % 2 else 0) + rng.randint(0, 9) for u in range(24)] for v in range(24)]
    stripes2 = [[(255 if (u // 2) % 2 else 0) + rng.randint(0, 9) for u in range(24)] for v in range(24)]
    noise = random_image(rng, 24, 24)
    hs = lbp_histogram(stripes, 8, 1.0, "riu2")
    hs2 = lbp_histogram(stripes2, 8, 1.0, "riu2")
    hn = lbp_histogram(noise, 8, 1.0, "riu2")
    assert chi_square(hs, hs2) < chi_square(hs, hn)

History

Ojala, Pietikainen and Harwood introduced the local binary pattern in 1996 in a comparison of texture measures. Their code thresholded a 3×33 \times 3 neighborhood at the center value and used it with a contrast measure. In 2002 Ojala, Pietikainen and Maenpaa gave the circular form with PP neighbors at radius RR and bilinear interpolation, the uniformity measure UU, and the rotation invariant uniform code riu2. Ahonen, Hadid and Pietikainen used grids of u2 histograms for face recognition in 2004 and 2006, and LBP became a standard face and texture descriptor before learned features.

References

  1. Timo Ojala, Matti Pietikainen and David Harwood, A comparative study of texture measures with classification based on featured distributions, Pattern Recognition 29(1), 51-59, 1996, the whole paper (the 3 x 3 LBP code, the LBP/C pair with a contrast measure, classification by the distance of histograms)
  2. Timo Ojala, Matti Pietikainen and Topi Maenpaa, Multiresolution gray-scale and rotation invariant texture classification with local binary patterns, IEEE Transactions on Pattern Analysis and Machine Intelligence 24(7), 971-987, 2002, the section on gray-scale and rotation invariant local binary patterns (the circular neighbor set, the sign function, the ri and riu2 codes, the uniformity measure U)
  3. Timo Ahonen, Abdenour Hadid and Matti Pietikainen, Face description with local binary patterns, application to face recognition, IEEE Transactions on Pattern Analysis and Machine Intelligence 28(12), 2037-2041, 2006, the whole paper (a grid of regions, one u2 histogram per region, the concatenated histogram, the weighted chi-square distance)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example