grainstat


Namegrainstat JSON
Version 1.0.2 PyPI version JSON
download
home_pagehttps://github.com/pranavkokati/grainstat
SummaryProfessional grain size analysis for materials science
upload_time2025-07-20 17:45:29
maintainerNone
docs_urlNone
authorpranavkokati
requires_python>=3.8
licenseMIT License Copyright (c) 2024 pranavkokati Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords materials science grain analysis microstructure image processing metallurgy microscopy sem optical microscopy astm grain size
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # GrainStat

**Professional grain size analysis for materials science**

GrainStat is a comprehensive Python package for analyzing grain microstructures in materials science. It provides robust tools for image processing, grain segmentation, statistical analysis, and report generation that are essential for materials characterization.

## Features

### 🔬 **Image Processing & Segmentation**
- Support for TIFF, PNG, JPEG, BMP, and multi-page TIFF files
- Spatial calibration for converting pixel measurements to physical units
- Advanced preprocessing filters (Gaussian smoothing, CLAHE contrast enhancement)
- Multiple thresholding methods (Otsu, adaptive)
- Watershed segmentation for separating touching grains
- Morphological operations for noise reduction

### 📊 **Comprehensive Grain Analysis**
- **Basic properties**: Area, perimeter, centroid, bounding box
- **Shape descriptors**: Eccentricity, solidity, aspect ratio, orientation
- **Derived metrics**: Equivalent circular diameter (ECD), shape factor, compactness
- **ASTM E112 grain size number** calculation
- **Size classification**: Ultrafine, fine, medium, coarse, very coarse

### 📈 **Statistical Analysis**
- Complete distribution statistics (mean, median, std, percentiles)
- Skewness and kurtosis analysis
- Population-level metrics and size uniformity
- Spatial distribution analysis
- Distribution fitting (normal, lognormal, gamma, Weibull)

### 🎨 **Visualization Suite**
- Size distribution histograms
- Cumulative distribution plots
- Grain overlay visualization with boundaries and labels
- Shape analysis scatter plots
- Multi-panel summary figures
- Interactive grain viewer with click-to-inspect functionality

### 📄 **Export & Reporting**
- CSV/Excel export for grain data
- JSON export for complete analysis results
- Professional HTML/Markdown/PDF reports
- Batch processing summaries
- Grain boundary coordinate export

### 🔧 **Advanced Features**
- **Plugin system** for custom feature calculations
- **Batch processing** with parallel execution
- **Command-line interface** for automated workflows
- **Interactive viewer** for detailed grain inspection
- **Condition comparison** for experimental analysis

## Installation

```bash
# Basic installation
pip install grainstat

# With all optional dependencies
pip install grainstat[all]

# For development
pip install grainstat[dev]
```

### Requirements
- Python 3.8+
- NumPy, SciPy, scikit-image
- Matplotlib, Pandas, Pillow
- Seaborn (for enhanced plotting)

## Quick Start

### Basic Analysis

```python
from grainstat import GrainAnalyzer

# Initialize analyzer
analyzer = GrainAnalyzer()

# Analyze a microstructure image
results = analyzer.analyze(
    image_path="microstructure.tif",
    scale=0.5,  # micrometers per pixel
    min_area=50  # minimum grain area in pixels
)

# Export results
analyzer.export_csv("grain_data.csv")
analyzer.generate_report("analysis_report.html")

# Generate plots
analyzer.plot_histogram(save_path="size_distribution.png")
analyzer.plot_overlay(save_path="grain_overlay.png")
```

### Command Line Usage

```bash
# Single image analysis
grainstat analyze image.tif --scale 0.2 --export-csv results.csv --report report.html

# Batch processing
grainstat batch input_folder/ output_folder/ --scale 0.2 --workers 4

# Interactive viewer
grainstat interactive image.tif --scale 0.2

# Compare different conditions
grainstat compare --conditions condition1:path1 condition2:path2 output_dir/
```

### Batch Processing

```python
from grainstat.processing.batch import BatchProcessor

processor = BatchProcessor(n_workers=4)

results = processor.process_directory(
    input_dir="sample_images/",
    output_dir="batch_results/",
    scale=0.5,
    pattern="*.tif"
)
```

### Custom Features with Plugins

```python
from grainstat import feature

@feature
def custom_roundness(region):
    """Calculate custom roundness metric"""
    area = region.area
    perimeter = region.perimeter
    return (4 * 3.14159 * area) / (perimeter ** 2)

@feature(name="grain_complexity")
def calculate_complexity(region):
    """Multi-parameter complexity measure"""
    return {
        'shape_complexity': region.eccentricity * (2 - region.solidity),
        'size_factor': region.area / region.convex_area
    }
```

## Analysis Workflow

1. **Image Loading**: Automatic format detection and conversion to grayscale
2. **Preprocessing**: Gaussian smoothing and contrast enhancement (CLAHE)
3. **Segmentation**: Otsu or adaptive thresholding followed by watershed
4. **Morphological Cleaning**: Opening, closing, and small object removal
5. **Property Calculation**: Comprehensive geometric and shape analysis
6. **Statistical Analysis**: Population statistics and distribution fitting
7. **Visualization**: Multiple plot types for data exploration
8. **Export**: Professional reports and data files

## Key Formulas

### Equivalent Circular Diameter (ECD)
```
ECD = 2√(A/π)
```

### ASTM E112 Grain Size Number
```
G = -6.6438 × log₂(L) - 3.293
```
where L is the mean lineal intercept length in mm.

### Shape Factor (Circularity)
```
φ = 4πA/P²
```

### Aspect Ratio
```
AR = a/b
```
where a and b are the major and minor axis lengths.

## Output Examples

### Statistical Summary
```
GRAIN ANALYSIS SUMMARY
======================
Total grains detected: 1,247
Mean ECD: 12.3 μm
Median ECD: 10.8 μm
ASTM Grain Size Number: 8.2

Size Class Distribution:
  Fine: 423 grains (33.9%)
  Medium: 681 grains (54.6%)
  Coarse: 143 grains (11.5%)
```

### Exported Data
The CSV output includes all measured properties:
- `grain_id`, `ecd_um`, `area_um2`, `perimeter_um`
- `aspect_ratio`, `shape_factor`, `eccentricity`, `solidity`
- `major_axis_um`, `minor_axis_um`, `orientation`
- Custom plugin features

## Applications

GrainStat is designed for materials scientists, metallurgists, and researchers working with:

- **Optical microscopy** of polished and etched samples
- **SEM imaging** of microstructures
- **Quality control** in materials processing
- **Research** on grain growth, recrystallization, and phase transformations
- **Standards compliance** (ASTM E112, ISO 643)

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Citation

If you use GrainStat in your research, please cite:

```bibtex
@software{grainstat2024,
  title={GrainStat: Professional grain size analysis for materials science},
  author={Materials Science Lab},
  year={2024},
  url={https://github.com/materialslab/grainstat}
}
```

## Support

- 📚 [Documentation](https://grainstat.readthedocs.io/)
- 🐛 [Issue Tracker](https://github.com/materialslab/grainstat/issues)
- 💬 [Discussions](https://github.com/materialslab/grainstat/discussions)

---

**Made with ❤️ for the materials science community**

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/pranavkokati/grainstat",
    "name": "grainstat",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "pranav kokati <pranav@example.com>",
    "keywords": "materials science, grain analysis, microstructure, image processing, metallurgy, microscopy, SEM, optical microscopy, ASTM, grain size",
    "author": "pranavkokati",
    "author_email": "pranavkokati <pranav@example.com>",
    "download_url": "https://files.pythonhosted.org/packages/c5/7e/3fd4901fc0040ba561001b74297d95f86515071b61a956735bfe3c785cc2/grainstat-1.0.2.tar.gz",
    "platform": null,
    "description": "# GrainStat\n\n**Professional grain size analysis for materials science**\n\nGrainStat is a comprehensive Python package for analyzing grain microstructures in materials science. It provides robust tools for image processing, grain segmentation, statistical analysis, and report generation that are essential for materials characterization.\n\n## Features\n\n### \ud83d\udd2c **Image Processing & Segmentation**\n- Support for TIFF, PNG, JPEG, BMP, and multi-page TIFF files\n- Spatial calibration for converting pixel measurements to physical units\n- Advanced preprocessing filters (Gaussian smoothing, CLAHE contrast enhancement)\n- Multiple thresholding methods (Otsu, adaptive)\n- Watershed segmentation for separating touching grains\n- Morphological operations for noise reduction\n\n### \ud83d\udcca **Comprehensive Grain Analysis**\n- **Basic properties**: Area, perimeter, centroid, bounding box\n- **Shape descriptors**: Eccentricity, solidity, aspect ratio, orientation\n- **Derived metrics**: Equivalent circular diameter (ECD), shape factor, compactness\n- **ASTM E112 grain size number** calculation\n- **Size classification**: Ultrafine, fine, medium, coarse, very coarse\n\n### \ud83d\udcc8 **Statistical Analysis**\n- Complete distribution statistics (mean, median, std, percentiles)\n- Skewness and kurtosis analysis\n- Population-level metrics and size uniformity\n- Spatial distribution analysis\n- Distribution fitting (normal, lognormal, gamma, Weibull)\n\n### \ud83c\udfa8 **Visualization Suite**\n- Size distribution histograms\n- Cumulative distribution plots\n- Grain overlay visualization with boundaries and labels\n- Shape analysis scatter plots\n- Multi-panel summary figures\n- Interactive grain viewer with click-to-inspect functionality\n\n### \ud83d\udcc4 **Export & Reporting**\n- CSV/Excel export for grain data\n- JSON export for complete analysis results\n- Professional HTML/Markdown/PDF reports\n- Batch processing summaries\n- Grain boundary coordinate export\n\n### \ud83d\udd27 **Advanced Features**\n- **Plugin system** for custom feature calculations\n- **Batch processing** with parallel execution\n- **Command-line interface** for automated workflows\n- **Interactive viewer** for detailed grain inspection\n- **Condition comparison** for experimental analysis\n\n## Installation\n\n```bash\n# Basic installation\npip install grainstat\n\n# With all optional dependencies\npip install grainstat[all]\n\n# For development\npip install grainstat[dev]\n```\n\n### Requirements\n- Python 3.8+\n- NumPy, SciPy, scikit-image\n- Matplotlib, Pandas, Pillow\n- Seaborn (for enhanced plotting)\n\n## Quick Start\n\n### Basic Analysis\n\n```python\nfrom grainstat import GrainAnalyzer\n\n# Initialize analyzer\nanalyzer = GrainAnalyzer()\n\n# Analyze a microstructure image\nresults = analyzer.analyze(\n    image_path=\"microstructure.tif\",\n    scale=0.5,  # micrometers per pixel\n    min_area=50  # minimum grain area in pixels\n)\n\n# Export results\nanalyzer.export_csv(\"grain_data.csv\")\nanalyzer.generate_report(\"analysis_report.html\")\n\n# Generate plots\nanalyzer.plot_histogram(save_path=\"size_distribution.png\")\nanalyzer.plot_overlay(save_path=\"grain_overlay.png\")\n```\n\n### Command Line Usage\n\n```bash\n# Single image analysis\ngrainstat analyze image.tif --scale 0.2 --export-csv results.csv --report report.html\n\n# Batch processing\ngrainstat batch input_folder/ output_folder/ --scale 0.2 --workers 4\n\n# Interactive viewer\ngrainstat interactive image.tif --scale 0.2\n\n# Compare different conditions\ngrainstat compare --conditions condition1:path1 condition2:path2 output_dir/\n```\n\n### Batch Processing\n\n```python\nfrom grainstat.processing.batch import BatchProcessor\n\nprocessor = BatchProcessor(n_workers=4)\n\nresults = processor.process_directory(\n    input_dir=\"sample_images/\",\n    output_dir=\"batch_results/\",\n    scale=0.5,\n    pattern=\"*.tif\"\n)\n```\n\n### Custom Features with Plugins\n\n```python\nfrom grainstat import feature\n\n@feature\ndef custom_roundness(region):\n    \"\"\"Calculate custom roundness metric\"\"\"\n    area = region.area\n    perimeter = region.perimeter\n    return (4 * 3.14159 * area) / (perimeter ** 2)\n\n@feature(name=\"grain_complexity\")\ndef calculate_complexity(region):\n    \"\"\"Multi-parameter complexity measure\"\"\"\n    return {\n        'shape_complexity': region.eccentricity * (2 - region.solidity),\n        'size_factor': region.area / region.convex_area\n    }\n```\n\n## Analysis Workflow\n\n1. **Image Loading**: Automatic format detection and conversion to grayscale\n2. **Preprocessing**: Gaussian smoothing and contrast enhancement (CLAHE)\n3. **Segmentation**: Otsu or adaptive thresholding followed by watershed\n4. **Morphological Cleaning**: Opening, closing, and small object removal\n5. **Property Calculation**: Comprehensive geometric and shape analysis\n6. **Statistical Analysis**: Population statistics and distribution fitting\n7. **Visualization**: Multiple plot types for data exploration\n8. **Export**: Professional reports and data files\n\n## Key Formulas\n\n### Equivalent Circular Diameter (ECD)\n```\nECD = 2\u221a(A/\u03c0)\n```\n\n### ASTM E112 Grain Size Number\n```\nG = -6.6438 \u00d7 log\u2082(L) - 3.293\n```\nwhere L is the mean lineal intercept length in mm.\n\n### Shape Factor (Circularity)\n```\n\u03c6 = 4\u03c0A/P\u00b2\n```\n\n### Aspect Ratio\n```\nAR = a/b\n```\nwhere a and b are the major and minor axis lengths.\n\n## Output Examples\n\n### Statistical Summary\n```\nGRAIN ANALYSIS SUMMARY\n======================\nTotal grains detected: 1,247\nMean ECD: 12.3 \u03bcm\nMedian ECD: 10.8 \u03bcm\nASTM Grain Size Number: 8.2\n\nSize Class Distribution:\n  Fine: 423 grains (33.9%)\n  Medium: 681 grains (54.6%)\n  Coarse: 143 grains (11.5%)\n```\n\n### Exported Data\nThe CSV output includes all measured properties:\n- `grain_id`, `ecd_um`, `area_um2`, `perimeter_um`\n- `aspect_ratio`, `shape_factor`, `eccentricity`, `solidity`\n- `major_axis_um`, `minor_axis_um`, `orientation`\n- Custom plugin features\n\n## Applications\n\nGrainStat is designed for materials scientists, metallurgists, and researchers working with:\n\n- **Optical microscopy** of polished and etched samples\n- **SEM imaging** of microstructures\n- **Quality control** in materials processing\n- **Research** on grain growth, recrystallization, and phase transformations\n- **Standards compliance** (ASTM E112, ISO 643)\n\n## Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Citation\n\nIf you use GrainStat in your research, please cite:\n\n```bibtex\n@software{grainstat2024,\n  title={GrainStat: Professional grain size analysis for materials science},\n  author={Materials Science Lab},\n  year={2024},\n  url={https://github.com/materialslab/grainstat}\n}\n```\n\n## Support\n\n- \ud83d\udcda [Documentation](https://grainstat.readthedocs.io/)\n- \ud83d\udc1b [Issue Tracker](https://github.com/materialslab/grainstat/issues)\n- \ud83d\udcac [Discussions](https://github.com/materialslab/grainstat/discussions)\n\n---\n\n**Made with \u2764\ufe0f for the materials science community**\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2024 pranavkokati\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.\n        ",
    "summary": "Professional grain size analysis for materials science",
    "version": "1.0.2",
    "project_urls": {
        "Bug Reports": "https://github.com/pranavkokati/grainstat/issues",
        "Documentation": "https://grainstat.readthedocs.io/",
        "Homepage": "https://github.com/pranavkokati/grainstat",
        "Source": "https://github.com/pranavkokati/grainstat"
    },
    "split_keywords": [
        "materials science",
        " grain analysis",
        " microstructure",
        " image processing",
        " metallurgy",
        " microscopy",
        " sem",
        " optical microscopy",
        " astm",
        " grain size"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "5f806a927d6551fe09abceccde6bfb04ab94836c32164cda9beee48cadf08317",
                "md5": "39d90482fe8592842b1f4e71141b65db",
                "sha256": "85ff106a945232bd752f56dd6ac04e280fb9886b78a3e63f27fea968c064cfac"
            },
            "downloads": -1,
            "filename": "grainstat-1.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "39d90482fe8592842b1f4e71141b65db",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 12577,
            "upload_time": "2025-07-20T17:45:28",
            "upload_time_iso_8601": "2025-07-20T17:45:28.753501Z",
            "url": "https://files.pythonhosted.org/packages/5f/80/6a927d6551fe09abceccde6bfb04ab94836c32164cda9beee48cadf08317/grainstat-1.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "c57e3fd4901fc0040ba561001b74297d95f86515071b61a956735bfe3c785cc2",
                "md5": "eab3f974ef15ba6a628d627b1d5ff592",
                "sha256": "5ae6a3d3cce0dfe006c367464f5da141372c347fc04439582949666f422cf743"
            },
            "downloads": -1,
            "filename": "grainstat-1.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "eab3f974ef15ba6a628d627b1d5ff592",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 16102,
            "upload_time": "2025-07-20T17:45:29",
            "upload_time_iso_8601": "2025-07-20T17:45:29.809486Z",
            "url": "https://files.pythonhosted.org/packages/c5/7e/3fd4901fc0040ba561001b74297d95f86515071b61a956735bfe3c785cc2/grainstat-1.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-20 17:45:29",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pranavkokati",
    "github_project": "grainstat",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "grainstat"
}
        
Elapsed time: 1.03759s