281 lines
7.1 KiB
Markdown
281 lines
7.1 KiB
Markdown
# Data Extraction from Diagram Images
|
||
|
||
This toolkit extracts data points from PNG diagrams containing plots with x and y axes and curves/waves.
|
||
|
||
## Requirements
|
||
|
||
- Python 3.9 or higher
|
||
- [UV](https://github.com/astral-sh/uv) - Fast Python package manager
|
||
|
||
## Installation
|
||
|
||
### Install UV (if not already installed)
|
||
|
||
```bash
|
||
# On macOS/Linux
|
||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||
|
||
# On Windows
|
||
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
|
||
```
|
||
|
||
### Install Project Dependencies
|
||
|
||
```bash
|
||
# Navigate to project directory
|
||
cd extract_plot_data_from_pic
|
||
|
||
# Create virtual environment and install dependencies
|
||
uv sync
|
||
|
||
# Or install in development mode
|
||
uv pip install -e .
|
||
```
|
||
|
||
## Usage
|
||
|
||
### Command Line Interface
|
||
|
||
Run the extraction tool directly:
|
||
|
||
```bash
|
||
# Using uv
|
||
uv run extract-plot-data
|
||
|
||
# Or activate the virtual environment
|
||
source .venv/bin/activate # On Unix/macOS
|
||
# or
|
||
.venv\Scripts\activate # On Windows
|
||
|
||
# Then run
|
||
extract-plot-data
|
||
```
|
||
|
||
### Python API
|
||
|
||
Use the extraction functionality in your own Python code:
|
||
|
||
```python
|
||
from extract_plot_data import DiagramExtractor
|
||
|
||
# Create extractor with calibration
|
||
extractor = DiagramExtractor(calibration={
|
||
'x_min': 0,
|
||
'x_max': 100,
|
||
'y_min': -10,
|
||
'y_max': 10
|
||
})
|
||
|
||
# Extract data from image
|
||
result = extractor.extract('path/to/diagram.png')
|
||
|
||
# Access extracted points
|
||
for point in result['data_points']:
|
||
print(f"x={point['x']:.4f}, y={point['y']:.4f}")
|
||
```
|
||
|
||
## Files Overview
|
||
|
||
- **src/extract_plot_data/** - Main package directory
|
||
- **extractor.py** - Core extraction class with axis detection
|
||
- **cli.py** - Command-line interface
|
||
- **pyproject.toml** - Project configuration and dependencies
|
||
- **extract_data_absolute.py** - Legacy standalone script (kept for reference)
|
||
|
||
## Quick Start
|
||
|
||
### Step 1: Prepare Your Images
|
||
|
||
Place PNG diagram files in your working directory.
|
||
|
||
### Step 2: Run Extraction
|
||
|
||
```bash
|
||
uv run extract-plot-data
|
||
```
|
||
|
||
The tool will:
|
||
1. Ask for an images folder (defaults to the current directory)
|
||
2. Ask for axis calibration values (min/max for X and Y axes)
|
||
3. Optionally prompt per image to override detected axis pixel positions
|
||
4. Process all PNG files in the chosen images folder
|
||
5. Extract data points and convert to real-world coordinates
|
||
6. Save results to JSON and CSV files in `extracted_output/`
|
||
|
||
### Step 3: Review Results
|
||
|
||
The extraction creates (in `extracted_output/`):
|
||
- `extracted_data.json` - Complete extraction results with metadata
|
||
- `{image_name}_data.csv` - CSV files with real-world coordinates
|
||
- `{image_name}_overlay.png` - Visualizations with detected axes and plot bounds (if requested)
|
||
|
||
## Understanding the Extracted Data
|
||
|
||
### Direct Real-World Coordinates
|
||
|
||
The extractor directly converts pixel coordinates to real-world values based on your calibration. You provide the axis ranges at the start, and all extracted points are immediately converted to actual values.
|
||
|
||
Example output in `extracted_data.json`:
|
||
```json
|
||
"data_points": [
|
||
{"x": 12.5, "y": 6.4},
|
||
{"x": 13.2, "y": 5.7},
|
||
{"x": 14.0, "y": 6.1}
|
||
]
|
||
```
|
||
|
||
### Axis Calibration
|
||
|
||
When running the tool, provide the axis ranges shown in your diagrams:
|
||
|
||
- **X-axis**: minimum and maximum values (e.g., 0 to 100 Hz)
|
||
- **Y-axis**: minimum and maximum values (e.g., -10 to 10 dB)
|
||
|
||
The tool directly converts pixel coordinates to these ranges.
|
||
|
||
## Output Files
|
||
|
||
### Extracted Data
|
||
- **extracted_data.json** - Complete extraction with plot boundaries and real-world coordinates
|
||
- **{image}_data.csv** - Data points in CSV format with real-world values
|
||
|
||
CSV Format:
|
||
```
|
||
x,y
|
||
12.5,6.4
|
||
13.2,5.7
|
||
14.0,6.1
|
||
...
|
||
```
|
||
|
||
### Visualizations (Optional)
|
||
- **{image}_overlay.png** - Original image with extracted points, plot area, and detected X/Y axes
|
||
|
||
## Advanced Usage
|
||
|
||
### Programmatic Usage
|
||
|
||
Load and process the extracted data:
|
||
|
||
```python
|
||
import json
|
||
|
||
with open('extracted_data.json', 'r') as f:
|
||
data = json.load(f)
|
||
|
||
for image_name, results in data.items():
|
||
print(f"Image: {image_name}")
|
||
print(f"Points: {results['num_points']}")
|
||
print(f"Calibration: X=[{results['calibration']['x_min']}, {results['calibration']['x_max']}]")
|
||
|
||
# Access the data points (already in real-world coordinates)
|
||
for point in results['data_points'][:5]:
|
||
print(f" x={point['x']:.4f}, y={point['y']:.4f}")
|
||
```
|
||
|
||
### Using in Your Own Code
|
||
|
||
```python
|
||
from extract_plot_data import DiagramExtractor
|
||
|
||
# Create extractor with custom calibration
|
||
extractor = DiagramExtractor()
|
||
extractor.set_calibration(x_min=0, x_max=100, y_min=-10, y_max=10)
|
||
|
||
# Process multiple images
|
||
import glob
|
||
for image_path in glob.glob('*.png'):
|
||
result = extractor.extract(image_path)
|
||
if result:
|
||
# Work with extracted data
|
||
points = result['data_points']
|
||
# ... your processing code ...
|
||
|
||
# Override detected axes for a single image
|
||
result = extractor.extract(
|
||
'path/to/diagram.png',
|
||
axes_override={'y_axis_x': 42, 'x_axis_y': 310}
|
||
)
|
||
```
|
||
|
||
## Technical Details
|
||
|
||
### Detection Method
|
||
|
||
1. **Axis Detection**: Uses Hough line detection (with morphology fallback) to find axes
|
||
2. **Edge Detection**: Applies Canny edge detection to find curve boundaries
|
||
3. **Point Extraction**: Converts edge pixels to real-world coordinates using calibration
|
||
4. **Clustering**: Groups nearby pixels into single data points using DBSCAN
|
||
5. **Sorting**: Orders points by x-coordinate for consistency
|
||
6. **Coordinate Conversion**: Direct transformation from pixels to real-world values
|
||
|
||
### Parameters
|
||
|
||
Key parameters in `extract_data.py`:
|
||
|
||
| Parameter | Purpose | Default |
|
||
|-----------|---------|---------|
|
||
| `Canny low/high thresholds` | Edge detection sensitivity | 50, 150 |
|
||
| `DBSCAN eps` | Clustering radius for point grouping | 3 pixels |
|
||
| `Kernel sizes` | Morphological operation sizes | 50×1, 1×50 |
|
||
|
||
Adjust these if extraction quality is poor for your specific images.
|
||
|
||
## Troubleshooting
|
||
|
||
### Too few points extracted
|
||
- Increase Canny edge detection thresholds lower
|
||
- Reduce DBSCAN eps value for finer clustering
|
||
- Check that curves aren't too light/faint
|
||
|
||
### Too many noisy points
|
||
- Increase DBSCAN eps value
|
||
- Increase Canny high threshold
|
||
|
||
### Axes not detected properly
|
||
- Check that axes are clearly visible dark lines
|
||
- May need to adjust morphological kernel sizes
|
||
|
||
## Dependencies
|
||
|
||
All dependencies are automatically managed by UV and specified in [pyproject.toml](pyproject.toml):
|
||
|
||
- opencv-python - Image processing and computer vision
|
||
- numpy - Numerical computing
|
||
- pillow - Image manipulation
|
||
- matplotlib - Visualization
|
||
- scipy - Scientific computing
|
||
- scikit-learn - Machine learning (DBSCAN clustering)
|
||
|
||
Install with:
|
||
```bash
|
||
uv sync
|
||
```
|
||
|
||
## Development
|
||
|
||
### Adding Dependencies
|
||
|
||
```bash
|
||
# Add a new dependency
|
||
uv add package-name
|
||
|
||
# Add a dev dependency
|
||
uv add --dev package-name
|
||
```
|
||
|
||
### Running Tests
|
||
|
||
```bash
|
||
uv run pytest
|
||
```
|
||
|
||
## Questions or Issues?
|
||
|
||
The extraction is based on image processing techniques:
|
||
- Digital diagrams work best (PNG format recommended)
|
||
- If your diagrams have unusual axis formats or colors, the detection may need adjustment
|
||
- Scanned/photographed diagrams with poor quality may not extract well
|
||
- For best results, ensure axes and curves are clearly visible with good contrast
|
||
|