Texture Feature Engineering: From Gray-Level Co-occurrence Matrices to Multi-Scale Fusion

    A practical guide to texture feature engineering: how GLCM and LBP work, how to select statistics, and why multi-scale fusion and rigorous preprocessing matter for industrial inspection, medical imaging, and remote sensing. Includes reference Python implementations.

    Texture Feature Engineering: From Gray-Level Co-occurrence Matrices to Multi-Scale Fusion

    1. What Texture Means in Engineering Terms

    Texture is not a subjective descriptor. It is the quasi-periodic, quasi-statistical visual pattern formed by the spatial distribution of gray levels (or colors) in an image. It captures how the structure of a surface is organized: the shape of the primitive elements (texels), their relative positions, and the density and orientation of the texel ensemble. In engineering, texture features are judged by a single criterion — whether they can separate homogeneous regions from heterogeneous regions in feature space.

    By origin and statistical behavior, textures fall into three classes:

    • Natural textures: formed by physical processes, such as wood grain, stone, fabric, leaves, and clouds. Their statistical regularities exist but have fuzzy boundaries, irregular primitives, and weak repetition.
    • Artificial textures: generated by deliberate design or regular processes, such as brick walls, gratings, printed halftone patterns, and chip layouts. Primitives are regular and highly directional; in the frequency domain they often appear as discrete peaks.
    • Mixed textures: artificial structures layered on natural backgrounds, or vice versa — stained tiles, corroded metal sheets, scratched fabric. These are the hardest cases in industrial inspection and remote sensing interpretation, because a defect is essentially a local disruption of the texture’s statistical regularity.

    The engineering takeaway from this classification is that defect detection is fundamentally the detection of texture homogeneity breakdown. The design goal of a feature extractor is therefore not to “describe how complex the texture is,” but to keep the feature distribution of normal samples tight enough that anomalous samples naturally fall into the distribution’s tail.

    2. Three Technical Approaches and Their Boundaries

    Texture description methods fall into three main lines, and choosing the right approach matters more than tuning parameters.

    Statistical methods — represented by the gray-level co-occurrence matrix (GLCM), the gray-level gradient co-occurrence matrix, and local binary patterns (LBP) — directly quantify gray-level relationships in pixel neighborhoods. They offer clear physical meaning, controllable dimensionality, and stability on small samples, but are sensitive to scale and orientation changes, so invariance must be engineered manually.

    Model-based methods assume a texture is generated by some random field and characterize it by estimating model parameters — typical examples include autoregressive models and Markov random fields. They are compact and generative, but their assumptions are strong, and they often fail to fit mixed textures.

    Frequency-domain / multi-scale methods — Fourier transforms, wavelet transforms, and dual-tree complex wavelet transforms — decompose texture energy across scales and orientations. They natively provide multi-scale description and are highly sensitive to the periodicity of artificial textures, but they do not preserve precise spatial localization, so they complement rather than replace statistical methods.

    The consensus in practice: a single method rarely balances discriminative power, stability, and computational cost at the same time, so multi-feature fusion is the mainstream approach.

    3. Gray-Level Co-occurrence Matrix: The Foundation of Texture Statistics

    3.1 How It Is Built

    The GLCM answers one question: given a spatial relationship, how frequently does a particular pair of gray levels co-occur? Research on its effectiveness dates back to the mid-1970s, making it one of the most thoroughly validated methods for statistical texture description.

    The construction pipeline:

    1. Gray-level quantization: compress raw gray levels to $L$ levels (commonly 8, 16, 32, or 64). The number of levels directly determines matrix size and statistical reliability; a large $L$ yields a sparse matrix dominated by statistical noise.
    2. Define the spatial relationship: specified by an orientation $\theta \in {0°, 45°, 90°, 135°}$ and a step distance $d$. Small $d$ captures fine-grained texture; large $d$ captures coarse structure.
    3. Count co-occurrence frequencies and normalize to obtain $P(i, j)$.
    4. Derive statistics to form a feature vector.

    3.2 Statistics and Their Physical Meaning

    The GLCM supports up to 14 derived statistics. The most commonly used subset:

    • Contrast: $ \sum (i-j)^2 P(i,j) $ — reflects local gray-scale contrast and texture sharpness.
    • Energy / angular second moment: $ \sum P(i,j)^2 $ — reflects the uniformity and regularity of the gray-level distribution.
    • Entropy: $ -\sum P(i,j)\log P(i,j) $ — reflects the information content and disorder of the texture.
    • Correlation: measures the linear correlation of gray levels along rows and columns.
    • Homogeneity: $ \sum P(i,j)/(1+|i-j|) $ — measures how similar neighboring gray levels are.
    • Other statistics include variance, mean, sum and difference variance and entropy, and inverse difference moments (including normalized forms).

    3.3 Reference Implementation

    1. import numpy as np
    2. def glcm(gray, levels=32, dist=1, angle=0):
    3. """gray: 2D uint8 array; returns the normalized co-occurrence matrix"""
    4. q = (gray.astype(np.int32) * levels // 256).clip(0, levels - 1)
    5. dx, dy = int(round(dist * np.cos(angle))), int(round(dist * np.sin(angle)))
    6. h, w = q.shape
    7. m = np.zeros((levels, levels), dtype=np.float64)
    8. for y in range(h):
    9. for x in range(w):
    10. ny, nx = y + dy, x + dx
    11. if 0 <= ny < h and 0 <= nx < w:
    12. m[q[y, x], q[ny, nx]] += 1
    13. s = m.sum()
    14. return m / s if s > 0 else m
    15. def glcm_features(P):
    16. i = np.arange(P.shape[0])[:, None]
    17. j = np.arange(P.shape[1])[None, :]
    18. contrast = (np.sum((i - j) ** 2 * P),)
    19. energy = (np.sum(P ** 2),)
    20. entropy = (-np.sum(P[P > 0] * np.log(P[P > 0])),)
    21. homo = (np.sum(P / (1.0 + np.abs(i - j))),)
    22. return np.concatenate(contrast + energy + entropy + homo)

    Practical tip: compute each orientation and step distance separately, then aggregate with the mean and the range (max − min). The mean describes the dominant texture; the range captures directional anisotropy.

    4. Local Binary Patterns: Encoding Local Gray-Level Differences

    4.1 Basic Encoding

    LBP was systematically proposed by Ojala et al. in 2002 and has evolved continuously since. For each pixel, sample $P$ points on a circle of radius $R$ around it. Compare each neighbor’s gray level with the center’s: assign 1 if greater, 0 otherwise, producing a $P$-bit binary code that is converted to a decimal label for that pixel. Histograms over a region then serve as the texture feature.

    Its strengths: invariance to monotonic gray-level transforms, extremely fast computation, and insensitivity to illumination changes — which is why it is widely used in medical image analysis and face recognition.

    4.2 The Uniform Pattern and Dimensionality Reduction

    The original LBP yields 256 patterns for 8 neighbors — high-dimensional and sparse. A pattern is defined as uniform if the number of 0/1 transitions in the circular binary code is at most 2. These patterns correspond to local extrema, flat areas, and gradual transitions, and carry most of the discriminative information. Merging all other patterns into a single “miscellaneous” bin reduces the 8-neighbor feature dimension from 256 to 59, cutting storage and training costs significantly while preserving discriminative power.

    1. def lbp_uniform(gray, P=8, R=1):
    2. h, w = gray.shape
    3. g = gray.astype(np.int32)
    4. codes = np.zeros((h, w), dtype=np.int32)
    5. for k in range(P):
    6. ang = 2 * np.pi * k / P
    7. y = int(round(-R * np.sin(ang)))
    8. x = int(round(R * np.cos(ang)))
    9. shifted = np.roll(np.roll(g, y, axis=0), x, axis=1)
    10. codes |= (shifted >= g) << k
    11. # count 0/1 transitions; a code with <= 2 transitions is uniform
    12. b = ((codes[:, :, None] >> np.arange(P)) & 1)
    13. rot = np.roll(b, 1, axis=2)
    14. jumps = np.sum(b != rot, axis=2)
    15. hist = np.bincount(codes[jumps <= 2].ravel(), minlength=2 ** P)
    16. return hist / max(hist.sum(), 1)

    4.3 Rotation Invariance and Noise Robustness

    The two long-standing pain points of classic LBP are orientation sensitivity and noise sensitivity. Rotation-invariant LBP assigns the minimum value over all circular shifts of the code as the label, achieving orientation independence. Uniform patterns further compress the dimension. To handle noise, follow-up research has introduced multi-direction block comparisons, center-symmetric coding, thresholding strategies that incorporate neighborhood means or medians, and multi-scale LBP fusion. The core idea is always the same: replace single-point comparisons with more robust thresholds, and replace a single radius with multi-scale context.

    5. Multi-Scale and Multi-Feature Fusion

    5.1 Wavelets and the Dual-Tree Complex Wavelet Transform

    The wavelet transform decomposes an image into approximation and detail sub-bands at different scales; computing statistics per sub-band captures both coarse and fine texture simultaneously. The dual-tree complex wavelet transform adds approximate shift invariance and better directional selectivity (distinguishing directions such as ±15°, ±45°, and ±75°). Combining it with GLCM to form joint texture features is widely used in remote sensing image segmentation: wavelets handle multi-scale decomposition and orientation separation, while GLCM handles statistical characterization within each sub-band. The two are complementary.

    5.2 The Gray-Level Gradient Co-occurrence Matrix

    The GLCM only describes gray-level relationships and ignores gradient information. The gray-level gradient co-occurrence matrix jointly counts gray level and gradient magnitude in a 2D space, from which statistics such as gray-level mean, gradient mean, gray-level entropy, gradient entropy, energy, inertia, and inverse difference moments can be derived. In industrial surface defect detection, scratches, pits, and stains typically manifest as simultaneous gray-level and gradient anomalies, so such fused features are usually more stable than either feature alone.

    5.3 Levels of Fusion

    • Feature-level fusion: normalize each method’s feature vector, concatenate, then apply dimensionality reduction and regularization.
    • Decision-level fusion: train each method independently and combine outputs via weighted probability voting — more robust and more interpretable.

    6. Engineering Best Practices

    1. Preprocessing comes first: denoising, illumination normalization, and geometric registration should precede feature extraction; otherwise statistical features are contaminated by acquisition conditions.
    2. Grid-search parameters: GLCM quantization levels and step distances, and LBP’s $P/R$ combinations, should be searched systematically as hyperparameters rather than fixed by experience.
    3. Normalize and reduce features: statistics with vastly different scales must be standardized; high-dimensional concatenations can be compressed with PCA or LDA.
    4. Sliding windows and multi-scale pyramids: when defect scale is unknown, extract features at multiple window sizes and aggregate.
    5. Interpretable output: keep the per-statistic contributions so inspection workflows can trace the cause of misclassifications.
    6. Cloud deployment: image data can live in object storage, algorithms can run on container platforms with elastic scaling, task scheduling can be decoupled via message queues, and runtime metrics can feed logging services and monitoring alerts — forming an observable batch-processing pipeline.
    7. Relationship to deep models: the first layer of a convolutional network essentially learns adaptive texture primitives. But in small-sample, high-interpretability, or low-compute scenarios, handcrafted texture features remain a cost-effective choice, and the two can be used in cascade.

    7. Troubleshooting Common Issues

    • Poor feature discriminability: usually caused by too many quantization levels (sparse matrices) or a step distance mismatched to the texture scale.
    • Unstable results: check whether rotation/scale normalization was applied, and whether directional statistics were averaged away unintentionally.
    • Dimensionality explosion: enable the uniform pattern, limit the number of orientations, and apply dimensionality reduction first.
    • Noise sensitivity: switch to median- or mean-thresholded encoding, and apply light smoothing before extraction.

    The core methodology of texture analysis condenses into one sentence: first clarify the texture’s scale and orientation properties, then choose matching statistical, model-based, or frequency-domain descriptors, and finally trade preprocessing rigor and multi-feature fusion for stability. Mastering the two main lines — GLCM and LBP — plus the supporting role of multi-scale decomposition covers the vast majority of texture engineering needs in industrial inspection, medical imaging, and remote sensing.