304 lines
7.9 KiB
Markdown
304 lines
7.9 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}")
|
|
```
|
|
|
|
#### Controlling Point Density
|
|
|
|
To extract fewer points (less dense sampling):
|
|
|
|
```python
|
|
from extract_plot_data import DiagramExtractor
|
|
|
|
# Extract only 30 points (sparse sampling)
|
|
extractor = DiagramExtractor(
|
|
calibration={'x_min': 0, 'x_max': 100, 'y_min': -10, 'y_max': 10},
|
|
max_points=30
|
|
)
|
|
|
|
result = extractor.extract('path/to/diagram.png')
|
|
print(f"Extracted {len(result['data_points'])} points") # Will be 30 or fewer
|
|
```
|
|
|
|
Without `max_points`, automatic sampling extracts 50-200 points depending on curve complexity.
|
|
|
|
## 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. Ask for maximum points to extract (blank for automatic sampling)
|
|
4. Optionally prompt per image to override detected axis pixel positions
|
|
5. Process all PNG files in the chosen images folder
|
|
6. Extract data points and convert to real-world coordinates
|
|
7. 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 and sampling density
|
|
extractor = DiagramExtractor(
|
|
calibration={'x_min': 0, 'x_max': 100, 'y_min': -10, 'y_max': 10},
|
|
max_points=50 # Extract only 50 points for less dense sampling
|
|
)
|
|
|
|
# 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**: Divides x-axis into bins and takes median of detected points in each bin
|
|
4. **Line Centering**: Uses median y-values to center points on thick lines (handles edges on both sides)
|
|
5. **Sorting**: Orders points by x-coordinate for consistency
|
|
6. **Coordinate Conversion**: Direct transformation from pixels to real-world values
|
|
|
|
### Parameters
|
|
|
|
Key parameters in `extractor.py`:
|
|
|
|
| Parameter | Purpose | Default |
|
|
|-----------|---------|---------|
|
|
| `Canny low/high thresholds` | Edge detection sensitivity | 50, 150 |
|
|
| `max_points` | Maximum number of points to extract | Auto (50-200) |
|
|
Adjust these if extraction quality is poor for your specific images.
|
|
|
|
## Troubleshooting
|
|
|
|
### Too few points extracted
|
|
- Increase the `max_points` parameter or leave blank for automatic sampling
|
|
- Lower Canny edge detection thresholds
|
|
- Check that curves aren't too light/faint
|
|
|
|
### Too many noisy or dense points
|
|
- Set `max_points` to a lower value (e.g., 20, 30, 50) to get sparser sampling
|
|
- Increase Canny high threshold
|
|
|
|
### Points not centered on line
|
|
- The algorithm now uses median binning to automatically center points on thick lines
|
|
- If still having issues, try adjusting Canny thresholds or check image quality
|
|
|
|
### 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
|
|
|
|
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
|
|
|