杰瑞科技汇

Python greycoprops如何计算图像纹理特征?

Of course! Let's dive deep into skimage.measure.regionprops and its companion function, skimage.measure.greycoprops.

Python greycoprops如何计算图像纹理特征?-图1
(图片来源网络,侵删)

What is greycoprops?

greycoprops is a function from the scikit-image library in Python. Its name is a portmanteau of "Gray-Level Co-occurrence Matrix Properties".

In simple terms, it's a tool for calculating specific statistical features (called "haralick features") from a Gray-Level Co-occurrence Matrix (GLCM). These features are very powerful for image analysis, especially for texture analysis.


The Big Picture: GLCM -> greycoprops

To understand greycoprops, you first need to understand its input: the Gray-Level Co-occurrence Matrix (GLCM).

What is a Gray-Level Co-occurrence Matrix (GLCM)?

An image is a grid of pixels. The GLCM is a way to quantify the spatial relationship between pixels.

Python greycoprops如何计算图像纹理特征?-图2
(图片来源网络,侵删)
  • Concept: It counts how often pairs of pixels with specific gray-level values occur in a specific spatial relationship (e.g., one pixel is to the immediate right of the other, or one pixel is one pixel below and to the right of the other).

  • How it works:

    1. You define a distance (e.g., 1 pixel) and an angle (e.g., 0° for horizontal, 45° for diagonal).
    2. You scan the image and, for every pixel, you look at the pixel that is distance pixels away at the specified angle.
    3. You increment the count in a matrix at the position corresponding to the gray-level of the first pixel and the gray-level of the second pixel.
  • Example: Imagine a tiny 3x3 image with 4 gray levels (0, 1, 2, 3). If you calculate the GLCM with a distance of 1 and an angle of 0° (horizontal), you are looking at pairs like (pixel[0,0], pixel[0,1]), (pixel[0,1], pixel[0,2]), (pixel[1,0], pixel[1,1]), etc. The resulting GLCM will be a 4x4 matrix where GLCM[i, j] is the count of how many times a pixel with value i was immediately to the left of a pixel with value j.

What are the "Properties"?

The raw GLCM is a large matrix and not very useful on its own. greycoprops computes a set of single numerical values that summarize the texture information within the GLCM. These are known as Haralick Textures. The most common properties are:

Property Name What it Measures Interpretation
Contrast The local variation between a pixel and its neighbor. High contrast means sharp differences in texture. Low contrast means smooth, uniform areas.
Dissimilarity The absolute difference between a pixel and its neighbor, averaged. Similar to contrast, but its scale is related to the gray-level difference.
Homogeneity The closeness of the distribution of elements in the GLCM to the GLCM diagonal. High homogeneity means a uniform texture (pixels are similar to their neighbors). Low homogeneity means a lot of variation.
Energy The sum of squared elements in the GLCM. High energy means a very uniform or repetitive texture. Low energy means a chaotic or varied texture.
Correlation A measure of linear dependency between gray-level values of a pixel and its neighbor. High correlation means a linear relationship between pixel pairs. Low correlation means a more random relationship.
ASM (Angular Second Moment) The sum of squared elements in the GLCM. This is identical to Energy. Same as Energy.

How to Use greycoprops (with Code)

Here is a step-by-step guide with a complete, runnable example.

Step 1: Install scikit-image

If you don't have it installed, open your terminal or command prompt and run:

pip install scikit-image

Step 2: The Full Workflow

The typical workflow is:

  1. Load an image.
  2. Convert it to grayscale.
  3. Calculate the GLCM using skimage.feature.graycomatrix.
  4. Calculate the properties from the GLCM using skimage.feature.greycoprops.
import numpy as np
import matplotlib.pyplot as plt
from skimage import data, feature, io
# --- 1. Load and Prepare an Image ---
# We'll use a built-in texture image from scikit-image
image = data.checkerboard()
# Convert to 8-bit unsigned integer if it's not already
if image.dtype != np.uint8:
    image = (image * 255).astype(np.uint8)
# Display the original image
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.imshow(image, cmap='gray')'Original Image (Checkerboard)')
plt.axis('off')
# --- 2. Calculate the Gray-Level Co-occurrence Matrix (GLCM) ---
# Parameters for GLCM:
#   - distances: List of pixel pair distances.
#   - angles: List of pixel pair angles in radians.
#   - levels: The number of gray levels. We use 256 for a standard 8-bit image.
#   - symmetric: If True, the output matrix is symmetric.
#   - normed: If True, the output matrix is normalized to sum to 1.
distances = [1]
angles = [0, np.pi/4, np.pi/2, 3*np.pi/4] # 0°, 45°, 90°, 135°
levels = 256
glcm = feature.graycomatrix(image, distances=distances, angles=angles, levels=levels, symmetric=True, normed=True)
print(f"Shape of the GLCM: {glcm.shape}")
# The shape is (num_levels, num_levels, num_distances, num_angles)
# For our case: (256, 256, 1, 4)
# --- 3. Calculate the Properties using greycoprops ---
# We will calculate a few properties for all our angles
properties = ['contrast', 'dissimilarity', 'homogeneity', 'energy', 'correlation']
props = feature.greycoprops(glcm, properties)
print("\nCalculated Properties:")
print(f"Shape of the props array: {props.shape}")
# The shape is (num_properties, num_distances, num_angles)
# For our case: (5, 1, 4)
# --- 4. Interpret and Display the Results ---
# The results are averaged over the specified distances (we only used 1).
# We can reshape for easier viewing.
props_avg = props[:, 0, :] # Get the properties for distance=1
print("\n--- Property Values ---")
for i, prop_name in enumerate(properties):
    print(f"{prop_name.capitalize()}:")
    for j, angle_deg in enumerate([0, 45, 90, 135]):
        print(f"  {angle_deg}°: {props_avg[i, j]:.4f}")
    print("-" * 20)
# Visualize the results
plt.subplot(122)
x_pos = np.arange(len(properties))
bar_width = 0.2
colors = ['b', 'g', 'r', 'c']
for i, angle_deg in enumerate([0, 45, 90, 135]):
    plt.bar(x_pos + i * bar_width, props_avg[:, i], width=bar_width, color=colors[i], label=f'{angle_deg}°')
plt.xlabel('Texture Properties')
plt.ylabel('Value')'Texture Properties by Angle')
plt.xticks(x_pos + bar_width * 1.5, properties)
plt.legend()
plt.tight_layout()
plt.show()

Output of the Code:

Shape of the GLCM: (256, 256, 1, 4)
Calculated Properties:
Shape of the props array: (5, 1, 4)
--- Property Values ---
Contrast:
  0°: 0.5165
  45°: 0.2500
  90°: 0.5165
  135°: 0.2500
--------------------
Dissimilarity:
  0°: 0.1250
  45°: 0.0625
  90°: 0.1250
  135°: 0.0625
--------------------
Homogeneity:
  0°: 0.8438
  45°: 0.9219
  90°: 0.8438
  135°: 0.9219
--------------------
Energy:
  0°: 0.4971
  45°: 0.7031
  90°: 0.4971
  135°: 0.7031
--------------------
Correlation:
  0°: 0.9975
  45°: 0.9984
  90°: 0.9975
  135°: 0.9984
--------------------

Analysis of the Results (Checkerboard Example)

The checkerboard is a great example for seeing how angle affects the texture properties.

  • Contrast & Dissimilarity: The values are higher for and 90° (horizontal and vertical) than for 45° and 135°. This makes perfect sense because the sharp black-to-white transitions are aligned with the horizontal and vertical axes.
  • Homogeneity & Energy: These values are the inverse of contrast. They are lower for and 90° because the texture is less uniform (more variation). They are higher for the diagonal angles.
  • Correlation: This is very high for all angles, which is expected since the pattern is highly regular and predictable.

Key Parameters for graycomatrix (The Input to greycoprops)

When you call graycomatrix, you must choose its parameters wisely, as they dramatically affect the GLCM and, therefore, the final properties.

  1. distances: A list of pixel pair distances. [1] is common. [1, 2, 3] would capture texture at multiple scales.
  2. angles: A list of angles in radians. [0, 45, 90, 135] is the standard set, as it covers all primary directions without redundancy.
  3. levels: The number of gray levels. For 8-bit images, 256 is standard. Reducing levels (e.g., to 32) can speed up computation and sometimes improve results by reducing noise.
  4. symmetric: If True, the GLCM is symmetric (i.e., it counts (i,j) and (j,i) pairs). This is almost always what you want.
  5. normed: If True, the GLCM is normalized so that all elements sum to 1. This makes the properties (like Energy) directly comparable between images of different sizes.

Practical Applications

greycoprops is fundamental in many computer vision tasks, especially when texture is a key differentiator:

  • Medical Imaging: Differentiating between healthy and diseased tissue (e.g., tumors in an MRI scan often have a unique texture).
  • Remote Sensing: Classifying land cover types (e.g., distinguishing between a forest, a city, and a farm based on their surface textures).
  • Material Science: Analyzing the surface of materials to detect defects or classify different types of fabric.
  • Biometrics: Analyzing skin texture for recognition systems.

Summary

Function Purpose Key Inputs Key Outputs
graycomatrix Calculates the Gray-Level Co-occurrence Matrix from an image. image, distances, angles, levels A multi-dimensional array (the GLCM)
greycoprops Calculates texture features (Haralick features) from a GLCM. glcm, properties (e.g., 'contrast', 'energy') A NumPy array of the calculated feature values

In short, graycomatrix does the heavy lifting of counting pixel pairs, and greycoprops distills that complex matrix into a set of meaningful, interpretable numbers that describe the image's texture.

分享:
扫描分享到社交APP
上一篇
下一篇