Compare commits

..

4 Commits

Author SHA1 Message Date
f20fbc9d0b improved point detection 2026-02-13 00:01:27 +03:30
44d35ebc86 added license file 2026-02-12 17:16:23 +03:30
ca779b3d33 made uv package 2026-02-12 03:18:47 +03:30
793afaffa4 add gitignore 2026-02-11 21:13:10 +03:30
9 changed files with 893 additions and 119 deletions

60
.gitignore vendored Normal file
View File

@@ -0,0 +1,60 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual environments
.venv/
venv/
ENV/
env/
# UV
.uv/
uv.lock
# IDEs
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# Project specific
extracted_data.json
*_data.csv
*_overlay.png
*_extracted.csv
Picture*.png
# Jupyter
.ipynb_checkpoints/
*.ipynb
# Testing
.pytest_cache/
.coverage
htmlcov/
# Distribution / packaging
.Python
*.egg-info/
dist/

1
.python-version Normal file
View File

@@ -0,0 +1 @@
3.9

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026
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.

341
README.md
View File

@@ -2,127 +2,180 @@
This toolkit extracts data points from PNG diagrams containing plots with x and y axes and curves/waves. This toolkit extracts data points from PNG diagrams containing plots with x and y axes and curves/waves.
## Files Overview ## Requirements
- **extract_data.py** - Main extraction script that detects axes and extracts curve data points - Python 3.9 or higher
- **calibrate_and_visualize.py** - Visualization and calibration tool for converting normalized coordinates to actual values - [UV](https://github.com/astral-sh/uv) - Fast Python package manager
- **extracted_data.json** - JSON file containing all extracted data points in normalized coordinates (0-1 range)
- **1_extracted.csv / 3_extracted.csv** - CSV files with extracted normalized data points
## Quick Start ## Installation
### Step 1: Extract Data from Your Images ### Install UV (if not already installed)
The extraction script has already been run. It processes all PNG files in the directory and creates:
```bash ```bash
python extract_data.py # On macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# On Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
``` ```
This will generate: ### Install Project Dependencies
- `extracted_data.json` - Complete extraction results
- `{image_name}_extracted.csv` - CSV files with normalized coordinates
### Step 2: Calibrate and Visualize
The extracted data is in **normalized coordinates** (x and y range from 0 to 1). To convert these to actual values from your diagrams:
```bash ```bash
python calibrate_and_visualize.py # 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 .
``` ```
This tool will: ## Usage
1. Generate visualization plots showing extracted points
2. Ask you to calibrate the axes by providing real-world values
3. Convert normalized coordinates to actual values
4. Save calibrated data to CSV files
## Understanding the Extracted Data ### Command Line Interface
### Normalized Coordinates Run the extraction tool directly:
The extraction produces coordinates in the range [0, 1]:
- `x=0` is the left edge of the plot area
- `x=1` is the right edge of the plot area
- `y=0` is the bottom of the plot area
- `y=1` is the top of the plot area
Example from extracted_data.json: ```bash
```json # Using uv
"normalized_data_points": [ uv run extract-plot-data
{"x": 0.0120, "y": 0.6439},
{"x": 0.0130, "y": 0.5682}, # Or activate the virtual environment
{"x": 0.0130, "y": 0.6061} source .venv/bin/activate # On Unix/macOS
] # or
.venv\Scripts\activate # On Windows
# Then run
extract-plot-data
``` ```
### Calibration to Real Values ### Python API
To convert normalized coordinates to actual values, you need to know what the axes represent. Use the extraction functionality in your own Python code:
If your diagram shows:
- **X-axis**: ranges from 0 to 100 Hz
- **Y-axis**: ranges from -10 to 10 dB
Then calibration would be:
```
X-axis minimum: 0
X-axis maximum: 100
Y-axis minimum: -10
Y-axis maximum: 10
```
And normalized point `{x: 0.5, y: 0.5}` would become `{x: 50, y: 0}` (middle of both axes)
## Extraction Results Summary
### 1.png
- **Image size**: 500×286 pixels
- **Points extracted**: 269 data points
- **Plot area dimensions**: 460×264 pixels
### 3.png
- **Image size**: 971×666 pixels
- **Points extracted**: 1188 data points
- **Plot area dimensions**: 893×612 pixels
## Output Files
### Normalized Data (Raw Extraction)
- **extracted_data.json** - Complete extraction with plot boundaries and raw coordinates
- **{image}_extracted.csv** - Quick reference CSV format
Format:
```
x,y
0.0120,0.6439
0.0130,0.5682
...
```
### Calibrated Data (After Running calibrate_and_visualize.py)
- **calibrated_data.json** - Extraction with calibration parameters and actual values
- **{image}_calibrated.csv** - Calibrated data in CSV format
- **calibration_info.json** - Calibration parameters used
- **comparison_{image}.png** - Visualization plots
## Advanced Usage
### Manual Calibration
To manually calibrate without the interactive prompt, edit `calibrate_and_visualize.py`:
```python ```python
calibration = { from extract_plot_data import DiagramExtractor
# Create extractor with calibration
extractor = DiagramExtractor(calibration={
'x_min': 0, 'x_min': 0,
'x_max': 100, 'x_max': 100,
'y_min': -10, 'y_min': -10,
'y_max': 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}")
``` ```
### Working with the JSON Data #### Controlling Point Density
Load and process the extracted data programmatically: 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 ```python
import json import json
@@ -133,64 +186,118 @@ with open('extracted_data.json', 'r') as f:
for image_name, results in data.items(): for image_name, results in data.items():
print(f"Image: {image_name}") print(f"Image: {image_name}")
print(f"Points: {results['num_points']}") print(f"Points: {results['num_points']}")
print(f"Calibration: X=[{results['calibration']['x_min']}, {results['calibration']['x_max']}]")
# Access the data points # Access the data points (already in real-world coordinates)
for point in results['normalized_data_points'][:5]: for point in results['data_points'][:5]:
print(f" x={point['x']:.4f}, y={point['y']:.4f}") 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 ## Technical Details
### Detection Method ### Detection Method
1. **Axis Detection**: Uses morphological operations to find horizontal and vertical lines 1. **Axis Detection**: Uses Hough line detection (with morphology fallback) to find axes
2. **Edge Detection**: Applies Canny edge detection to find curve boundaries 2. **Edge Detection**: Applies Canny edge detection to find curve boundaries
3. **Point Extraction**: Converts edge pixels to normalized coordinates 3. **Point Extraction**: Divides x-axis into bins and takes median of detected points in each bin
4. **Clustering**: Groups nearby pixels into single data points using DBSCAN 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 5. **Sorting**: Orders points by x-coordinate for consistency
6. **Coordinate Conversion**: Direct transformation from pixels to real-world values
### Parameters ### Parameters
Key parameters in `extract_data.py`: Key parameters in `extractor.py`:
| Parameter | Purpose | Default | | Parameter | Purpose | Default |
|-----------|---------|---------| |-----------|---------|---------|
| `Canny low/high thresholds` | Edge detection sensitivity | 50, 150 | | `Canny low/high thresholds` | Edge detection sensitivity | 50, 150 |
| `DBSCAN eps` | Clustering radius for point grouping | 3 pixels | | `max_points` | Maximum number of points to extract | Auto (50-200) |
| `Kernel sizes` | Morphological operation sizes | 50×1, 1×50 |
Adjust these if extraction quality is poor for your specific images. Adjust these if extraction quality is poor for your specific images.
## Troubleshooting ## Troubleshooting
### Too few points extracted ### Too few points extracted
- Increase Canny edge detection thresholds lower - Increase the `max_points` parameter or leave blank for automatic sampling
- Reduce DBSCAN eps value for finer clustering - Lower Canny edge detection thresholds
- Check that curves aren't too light/faint - Check that curves aren't too light/faint
### Too many noisy points ### Too many noisy or dense points
- Increase DBSCAN eps value - Set `max_points` to a lower value (e.g., 20, 30, 50) to get sparser sampling
- Increase Canny high threshold - 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 ### Axes not detected properly
- Check that axes are clearly visible dark lines - Check that axes are clearly visible dark lines
- May need to adjust morphological kernel sizes - May need to adjust morphological kernel sizes
## Dependencies ## Dependencies
- opencv-python All dependencies are automatically managed by UV and specified in [pyproject.toml](pyproject.toml):
- numpy
- pillow
- scipy
- scikit-learn
- matplotlib
All dependencies are pre-installed in the virtual environment. - 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? ## Questions or Issues?
The extraction is based on image processing techniques: 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 - If your diagrams have unusual axis formats or colors, the detection may need adjustment
- Scanned/photographed diagrams with poor quality may not extract well - Scanned/photographed diagrams with poor quality may not extract well
- Digital diagrams work best - For best results, ensure axes and curves are clearly visible with good contrast

View File

@@ -1,3 +1,9 @@
#!/bin/bash #!/bin/bash
# Wrapper script to run extract_data_absolute.py with the virtual environment # Wrapper script to run the package CLI with the virtual environment.
.venv/bin/python extract_data_absolute.py "$@" set -euo pipefail
if [[ -x .venv/bin/extract-plot-data ]]; then
.venv/bin/extract-plot-data "$@"
else
.venv/bin/python -m extract_plot_data.cli "$@"
fi

27
pyproject.toml Normal file
View File

@@ -0,0 +1,27 @@
[project]
name = "extract-plot-data"
version = "0.1.0"
description = "Extract data points from diagram images with automatic axis detection"
readme = "README.md"
license = {text = "MIT"}
requires-python = ">=3.9"
dependencies = [
"opencv-python>=4.8.0",
"numpy>=1.24.0",
"pillow>=10.0.0",
"matplotlib>=3.7.0",
"scipy>=1.11.0",
]
[project.scripts]
extract-plot-data = "extract_plot_data.cli:main"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.uv]
dev-dependencies = []
[tool.hatch.build.targets.wheel]
packages = ["src/extract_plot_data"]

View File

@@ -0,0 +1,7 @@
"""Extract plot data from diagram images."""
__version__ = "0.1.0"
from .extractor import DiagramExtractor
__all__ = ["DiagramExtractor"]

View File

@@ -0,0 +1,260 @@
"""Command-line interface for plot data extraction."""
import os
import json
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from .extractor import DiagramExtractor
def process_all_images(
directory, calibration=None, prompt_axis_override=False, max_points=None
):
"""Process all PNG images in the directory"""
extractor = DiagramExtractor(calibration, max_points=max_points)
all_results = {}
for filename in os.listdir(directory):
if filename.lower().endswith(".png"):
filepath = os.path.join(directory, filename)
result = extractor.extract(filepath)
if result and prompt_axis_override:
axes = result.get("axes", {})
detected_y_axis_x = axes.get("y_axis_x")
detected_x_axis_y = axes.get("x_axis_y")
print(f"Detected axes for {filename}:")
print(f" Y-axis x={detected_y_axis_x}px")
print(f" X-axis y={detected_x_axis_y}px")
raw_y = input("Override Y-axis x (pixels, blank to accept): ").strip()
raw_x = input("Override X-axis y (pixels, blank to accept): ").strip()
axes_override = {}
if raw_y:
axes_override["y_axis_x"] = int(raw_y)
if raw_x:
axes_override["x_axis_y"] = int(raw_x)
if axes_override:
result = extractor.extract(filepath, axes_override=axes_override)
if result:
all_results[filename] = result
print(f"\n✓ Successfully processed {filename}")
print(f" Extracted {result['num_points']} data points")
else:
print(f"\n✗ Failed to process {filename}")
print()
return all_results
def save_results(results, output_dir=".", output_filename="extracted_data.json"):
"""Save extracted data to JSON file"""
output_file = os.path.join(output_dir, output_filename)
with open(output_file, "w") as f:
json.dump(results, f, indent=2)
print(f"Results saved to {output_file}")
def save_csv_results(results, output_dir="."):
"""Save extracted data to CSV files for each image"""
for image_name, data in results.items():
csv_filename = os.path.join(
output_dir, f"{os.path.splitext(image_name)[0]}_data.csv"
)
with open(csv_filename, "w") as f:
f.write("x,y\n")
for point in data["data_points"]:
f.write(f"{point['x']},{point['y']}\n")
print(f"Data saved to {csv_filename}")
def visualize_results(results, output_dir="."):
"""Save images with extracted points overlaid"""
for image_name, data in results.items():
img = cv2.imread(data["image_path"])
if img is None:
print(f"Could not load image for visualization: {data['image_path']}")
continue
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plot_area = data["plot_area"]
plot_left = plot_area["left"]
plot_top = plot_area["top"]
plot_width = plot_area["width"]
plot_height = plot_area["height"]
axes = data.get("axes", {})
y_axis_x = axes.get("y_axis_x")
x_axis_y = axes.get("x_axis_y")
pixel_points = data["pixel_data_points"]
pixel_x = [p["x"] + plot_left for p in pixel_points]
pixel_y = [plot_top + (plot_height - p["y"]) for p in pixel_points]
fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(img_rgb)
rect = Rectangle(
(plot_left, plot_top),
plot_width,
plot_height,
linewidth=2,
edgecolor="green",
facecolor="none",
)
ax.add_patch(rect)
ax.scatter(pixel_x, pixel_y, c="red", s=12, alpha=0.6)
if y_axis_x is not None:
ax.axvline(y_axis_x, color="blue", linewidth=2, linestyle="--", alpha=0.9)
ax.text(
y_axis_x + 8,
plot_top + 20,
f"Y-axis x={y_axis_x}px",
color="blue",
fontsize=9,
bbox=dict(facecolor="white", alpha=0.7, edgecolor="none"),
)
if x_axis_y is not None:
ax.axhline(x_axis_y, color="orange", linewidth=2, linestyle="--", alpha=0.9)
ax.text(
plot_left + 8,
x_axis_y - 8,
f"X-axis y={x_axis_y}px",
color="orange",
fontsize=9,
bbox=dict(facecolor="white", alpha=0.7, edgecolor="none"),
)
ax.set_title(f"Extracted Points: {image_name}")
ax.set_xlim(0, img_rgb.shape[1])
ax.set_ylim(img_rgb.shape[0], 0)
ax.axis("off")
output_file = os.path.join(
output_dir, f"{os.path.splitext(image_name)[0]}_overlay.png"
)
plt.savefig(output_file, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Visualization saved to {output_file}")
def get_calibration_from_user():
"""Interactively get calibration parameters from user"""
print("\n" + "=" * 70)
print("AXIS CALIBRATION")
print("=" * 70)
print("Enter the axis ranges as shown in your diagrams.\n")
print("X-AXIS CALIBRATION:")
print("-" * 40)
try:
x_min = float(input("Enter X-axis minimum value: "))
x_max = float(input("Enter X-axis maximum value: "))
except ValueError:
print("Invalid input. Using default X range (0-1)")
x_min, x_max = 0, 1
print("\nY-AXIS CALIBRATION:")
print("-" * 40)
try:
y_min = float(input("Enter Y-axis minimum value: "))
y_max = float(input("Enter Y-axis maximum value: "))
except ValueError:
print("Invalid input. Using default Y range (0-1)")
y_min, y_max = 0, 1
return {"x_min": x_min, "x_max": x_max, "y_min": y_min, "y_max": y_max}
def main():
"""Main entry point for CLI"""
current_dir = os.getcwd()
output_dir = os.path.join(current_dir, "extracted_output")
images_dir_input = input("Images folder (default: current directory): ").strip()
images_dir = images_dir_input or current_dir
if not os.path.isdir(images_dir):
print(f"Images folder not found: {images_dir}")
return
os.makedirs(output_dir, exist_ok=True)
print("=" * 70)
print("Data Extraction from Diagram Images (Direct Real-World Coordinates)")
print("=" * 70)
print()
# Get calibration from user
calibration = get_calibration_from_user()
print(f"\nUsing calibration:")
print(f" X-axis: {calibration['x_min']} to {calibration['x_max']}")
print(f" Y-axis: {calibration['y_min']} to {calibration['y_max']}\n")
# Get sampling density preference
print("SAMPLING DENSITY:")
print("-" * 40)
max_points_input = input("Maximum points to extract (blank for auto): ").strip()
max_points = None
if max_points_input:
try:
max_points = int(max_points_input)
print(f"Will extract up to {max_points} points per image.\n")
except ValueError:
print("Invalid input. Using automatic sampling.\n")
else:
print("Using automatic sampling (typically 50-200 points).\n")
override_choice = input("Override detected axes per image? (y/n): ").strip().lower()
prompt_axis_override = override_choice in ("y", "yes")
results = process_all_images(
images_dir, calibration, prompt_axis_override, max_points
)
if results:
print("\n" + "=" * 70)
print("Summary of Results")
print("=" * 70)
for image_name, data in results.items():
print(f"\n{image_name}:")
print(f" Data points extracted: {data['num_points']}")
print(
f" Calibration: X=[{data['calibration']['x_min']}, {data['calibration']['x_max']}], Y=[{data['calibration']['y_min']}, {data['calibration']['y_max']}]"
)
print(f" First 5 points (real-world coordinates):")
for i, point in enumerate(data["data_points"][:5]):
print(f" [{i}] x={point['x']:.4f}, y={point['y']:.4f}")
# Save results
save_results(results, output_dir)
save_csv_results(results, output_dir)
visualize_choice = (
input("\nSave visualization overlays? (y/n): ").strip().lower()
)
if visualize_choice in ("y", "yes"):
visualize_results(results, output_dir)
print("\n" + "=" * 70)
print("Extraction complete!")
print("=" * 70)
else:
print("No images were successfully processed.")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,285 @@
"""Core diagram extraction functionality."""
import cv2
import numpy as np
class DiagramExtractor:
"""Extract data from diagram images with direct real-world coordinate conversion"""
def __init__(self, calibration=None, max_points=None):
"""
Initialize extractor with optional calibration parameters
Args:
calibration: Dict with x_min, x_max, y_min, y_max
If None, will use default values
max_points: Maximum number of points to extract (int)
If None, uses automatic sampling (min 50, or 1/5 of detected points)
Set to a lower number (e.g., 20, 50, 100) for sparser data
"""
self.calibration = calibration or {
"x_min": 0,
"x_max": 1,
"y_min": 0,
"y_max": 1,
}
self.max_points = max_points
def set_calibration(self, x_min, x_max, y_min, y_max):
"""Update calibration parameters"""
self.calibration = {
"x_min": x_min,
"x_max": x_max,
"y_min": y_min,
"y_max": y_max,
}
def extract(self, image_path, axes_override=None):
"""
Extract data points from a diagram image.
Directly converts pixel coordinates to real-world values.
Args:
image_path: Path to the PNG image
Returns:
dict: Contains extracted data with real-world coordinates
"""
# Load image
img = cv2.imread(image_path)
if img is None:
print(f"Error loading image: {image_path}")
return None
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
height, width = gray.shape
print(f"Processing image: {image_path}")
print(f"Image size: {width}x{height}")
# Use Canny edge detection to find curves
edges = cv2.Canny(gray, 50, 150)
# Detect horizontal and vertical lines (axes) using Hough as primary
y_axis_x = None
x_axis_y = None
min_line_length = int(min(width, height) * 0.4)
hough_lines = cv2.HoughLinesP(
edges,
1,
np.pi / 180,
threshold=120,
minLineLength=min_line_length,
maxLineGap=10,
)
vertical_candidates = []
horizontal_candidates = []
if hough_lines is not None:
for x1, y1, x2, y2 in hough_lines[:, 0]:
dx = abs(x1 - x2)
dy = abs(y1 - y2)
if dy > dx * 3:
vertical_candidates.append((x1, y1, x2, y2, dy))
elif dx > dy * 3:
horizontal_candidates.append((x1, y1, x2, y2, dx))
if vertical_candidates:
vertical_candidates.sort(key=lambda item: item[4], reverse=True)
top_vertical = vertical_candidates[:5]
xs = [int(round((x1 + x2) / 2)) for x1, y1, x2, y2, _ in top_vertical]
y_axis_x = min(xs)
if horizontal_candidates:
horizontal_candidates.sort(key=lambda item: item[4], reverse=True)
top_horizontal = horizontal_candidates[:5]
ys = [int(round((y1 + y2) / 2)) for x1, y1, x2, y2, _ in top_horizontal]
x_axis_y = max(ys)
# Fallback to morphology-based detection if Hough misses
if y_axis_x is None or x_axis_y is None:
kernel_h = cv2.getStructuringElement(cv2.MORPH_RECT, (50, 1))
kernel_v = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 50))
h_lines = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel_h)
v_lines = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel_v)
contours_h, _ = cv2.findContours(
h_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
contours_v, _ = cv2.findContours(
v_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
if y_axis_x is None and contours_v:
leftmost = min(contours_v, key=lambda c: cv2.boundingRect(c)[0])
x, y, w, h = cv2.boundingRect(leftmost)
y_axis_x = x
if x_axis_y is None and contours_h:
bottommost = max(
contours_h,
key=lambda c: cv2.boundingRect(c)[1] + cv2.boundingRect(c)[3],
)
x, y, w, h = cv2.boundingRect(bottommost)
x_axis_y = y + h
if axes_override:
if "y_axis_x" in axes_override and axes_override["y_axis_x"] is not None:
y_axis_x = int(axes_override["y_axis_x"])
if "x_axis_y" in axes_override and axes_override["x_axis_y"] is not None:
x_axis_y = int(axes_override["x_axis_y"])
if y_axis_x is None or x_axis_y is None:
print("Could not detect axes reliably. Using adaptive detection...")
y_axis_x = int(width * 0.08)
x_axis_y = int(height * 0.85)
print(f"Y-axis detected at x={y_axis_x} (pixels)")
print(f"X-axis detected at y={x_axis_y} (pixels)")
# Extract the plot area with minimal margins to include plots near edges
margin_right = max(5, int(width * 0.01))
margin_top = max(5, int(height * 0.01))
plot_left = y_axis_x
plot_right = width - margin_right
plot_top = margin_top
plot_bottom = x_axis_y
plot_width = plot_right - plot_left
plot_height = plot_bottom - plot_top
print(
f"Plot area: left={plot_left}, right={plot_right}, top={plot_top}, bottom={plot_bottom}"
)
print(f"Plot dimensions: {plot_width}x{plot_height} pixels")
# Extract edges in plot region
plot_edges = edges[plot_top:plot_bottom, plot_left:plot_right]
# Remove borders and axis lines to avoid captions/ticks
border_margin = 12
axis_band = 6
plot_edges[0:border_margin, :] = 0
plot_edges[-border_margin:, :] = 0
plot_edges[:, 0:border_margin] = 0
plot_edges[:, -border_margin:] = 0
x_axis_rel = x_axis_y - plot_top
y_axis_rel = y_axis_x - plot_left
if 0 <= x_axis_rel < plot_edges.shape[0]:
start = max(0, x_axis_rel - axis_band)
end = min(plot_edges.shape[0], x_axis_rel + axis_band + 1)
plot_edges[start:end, :] = 0
if 0 <= y_axis_rel < plot_edges.shape[1]:
start = max(0, y_axis_rel - axis_band)
end = min(plot_edges.shape[1], y_axis_rel + axis_band + 1)
plot_edges[:, start:end] = 0
# Find coordinates of edges (curve points)
curve_coords = np.where(plot_edges > 0)
if len(curve_coords[0]) == 0:
print("No edges detected in plot area. Trying color-based detection...")
plot_region = gray[plot_top:plot_bottom, plot_left:plot_right]
_, binary = cv2.threshold(plot_region, 200, 255, cv2.THRESH_BINARY_INV)
curve_coords = np.where(binary > 0)
if len(curve_coords[0]) == 0:
print("Error: Could not detect any curve in the image")
return None
# Convert pixel coordinates to data coordinates
pixel_y = curve_coords[0] # Row indices
pixel_x = curve_coords[1] # Column indices
# Invert y for proper coordinate system
pixel_y_inv = plot_height - pixel_y
# Combine and sample for uniform distribution
points = np.column_stack([pixel_x, pixel_y_inv])
if len(points) > 0:
# Sort by x coordinate
points = points[points[:, 0].argsort()]
# Group points by x-coordinate bins and take median y-value
# This centers the line even when edges are detected on both sides
x_min_pt, x_max_pt = points[:, 0].min(), points[:, 0].max()
# Determine number of bins based on desired samples
if self.max_points is not None:
n_bins = self.max_points
else:
n_bins = min(
max(50, len(points) // 5), len(points), x_max_pt - x_min_pt + 1
)
# Create bins
bin_width = max(1, (x_max_pt - x_min_pt) / n_bins)
centered_points = []
for i in range(int(n_bins)):
bin_start = x_min_pt + i * bin_width
bin_end = bin_start + bin_width
# Find all points in this x-range
mask = (points[:, 0] >= bin_start) & (points[:, 0] < bin_end)
bin_points = points[mask]
if len(bin_points) > 0:
# Use median x and median y to find line center
x_center = np.median(bin_points[:, 0])
y_center = np.median(bin_points[:, 1])
centered_points.append([x_center, y_center])
final_points = np.array(centered_points)
final_points = final_points[final_points[:, 0].argsort()]
# Convert pixel coordinates to real-world data values
x_scale = self.calibration["x_max"] - self.calibration["x_min"]
y_scale = self.calibration["y_max"] - self.calibration["y_min"]
data_x = (
self.calibration["x_min"] + (final_points[:, 0] / plot_width) * x_scale
)
data_y = (
self.calibration["y_min"] + (final_points[:, 1] / plot_height) * y_scale
)
# Create results dictionary
results = {
"image_path": image_path,
"image_size": {"width": width, "height": height},
"plot_area": {
"left": plot_left,
"right": plot_right,
"top": plot_top,
"bottom": plot_bottom,
"width": plot_width,
"height": plot_height,
},
"axes": {"y_axis_x": y_axis_x, "x_axis_y": x_axis_y},
"calibration": self.calibration,
"data_points": [
{"x": float(x), "y": float(y)} for x, y in zip(data_x, data_y)
],
"pixel_data_points": [
{"x": float(p[0]), "y": float(p[1])} for p in final_points
],
"num_points": len(final_points),
"raw_curve_points_count": len(curve_coords[0]),
}
return results
return None