Grain Size Analysis Using Python

Sep 12, 2024

Python Tutorial: Grain Size Analysis

Overview

  • Presenter: Srini from "Python for Microscopists"
  • Topic: Real-life application of Python in grain size analysis

Key Concepts

  • Grain Size Analysis:
    • Loading an image with grains and deriving statistics.
    • Material scientists and geologists use this, while life scientists can apply similar concepts to cell size distribution.

Steps in Analysis

Step 0: Import Required Libraries

  • import cv2
  • import numpy as np
  • from matplotlib import pyplot as plt
  • from skimage import ndimage
  • from scipy import ndimage
  • from skimage import io, color, measure

Step 1: Read the Image and Define Pixel Size

  • Load the image using cv2.imread and convert to grayscale.
  • Define pixel to micron ratio (i.e., 1 pixel = 0.5 microns).
  • If there's a scale bar, crop the image accordingly.

Step 2: Image Preprocessing

Denoising

  • If the image is noisy, apply a median filter or non-local means filter.

Thresholding

  • Generate a histogram of the image to identify optimal threshold.
  • Use Otsu's method for thresholding to separate grains from boundaries.
  • Convert the thresholded image to a binary image.

Step 3: Clean Up the Image

  • Use erosion and dilation to refine grain boundaries.
  • Define a kernel for these operations (e.g., np.ones((3,3), np.uint8)).

Step 4: Label Grains

  • Use ndimage.label to label connected components in the binary mask.
  • Structure parameters define connectivity (4-connectivity vs 8-connectivity).

Step 5: Measure Properties of Each Grain

  • Use measure.regionprops to extract properties such as area, equivalent diameter, orientation, etc.
  • Example of properties to measure:
    • Area
    • Equivalent Diameter
    • Orientation
    • Major Axis Length
    • Minor Axis Length

Step 6: Output Results to CSV

  • Write properties to a CSV file using Python's file handling.
  • Include headers in the CSV for clarity.

Conclusion

  • Emphasis on the importance of understanding the pixel scale when analyzing images.
  • Future applications may include cell size analysis for life scientists.
  • Encouragement to subscribe for more tutorials and content.