Compare commits
2 Commits
ca779b3d33
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| f20fbc9d0b | |||
| 44d35ebc86 |
21
LICENSE
Normal file
21
LICENSE
Normal 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.
|
||||||
61
README.md
61
README.md
@@ -74,6 +74,25 @@ for point in result['data_points']:
|
|||||||
print(f"x={point['x']:.4f}, y={point['y']:.4f}")
|
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
|
## Files Overview
|
||||||
|
|
||||||
- **src/extract_plot_data/** - Main package directory
|
- **src/extract_plot_data/** - Main package directory
|
||||||
@@ -97,10 +116,11 @@ uv run extract-plot-data
|
|||||||
The tool will:
|
The tool will:
|
||||||
1. Ask for an images folder (defaults to the current directory)
|
1. Ask for an images folder (defaults to the current directory)
|
||||||
2. Ask for axis calibration values (min/max for X and Y axes)
|
2. Ask for axis calibration values (min/max for X and Y axes)
|
||||||
3. Optionally prompt per image to override detected axis pixel positions
|
3. Ask for maximum points to extract (blank for automatic sampling)
|
||||||
4. Process all PNG files in the chosen images folder
|
4. Optionally prompt per image to override detected axis pixel positions
|
||||||
5. Extract data points and convert to real-world coordinates
|
5. Process all PNG files in the chosen images folder
|
||||||
6. Save results to JSON and CSV files in `extracted_output/`
|
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
|
### Step 3: Review Results
|
||||||
|
|
||||||
@@ -178,9 +198,11 @@ for image_name, results in data.items():
|
|||||||
```python
|
```python
|
||||||
from extract_plot_data import DiagramExtractor
|
from extract_plot_data import DiagramExtractor
|
||||||
|
|
||||||
# Create extractor with custom calibration
|
# Create extractor with custom calibration and sampling density
|
||||||
extractor = DiagramExtractor()
|
extractor = DiagramExtractor(
|
||||||
extractor.set_calibration(x_min=0, x_max=100, y_min=-10, y_max=10)
|
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
|
# Process multiple images
|
||||||
import glob
|
import glob
|
||||||
@@ -204,34 +226,36 @@ result = extractor.extract(
|
|||||||
|
|
||||||
1. **Axis Detection**: Uses Hough line detection (with morphology fallback) to find axes
|
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 real-world coordinates using calibration
|
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
|
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
|
||||||
@@ -245,7 +269,6 @@ All dependencies are automatically managed by UV and specified in [pyproject.tom
|
|||||||
- pillow - Image manipulation
|
- pillow - Image manipulation
|
||||||
- matplotlib - Visualization
|
- matplotlib - Visualization
|
||||||
- scipy - Scientific computing
|
- scipy - Scientific computing
|
||||||
- scikit-learn - Machine learning (DBSCAN clustering)
|
|
||||||
|
|
||||||
Install with:
|
Install with:
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ name = "extract-plot-data"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
description = "Extract data points from diagram images with automatic axis detection"
|
description = "Extract data points from diagram images with automatic axis detection"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
license = {text = "MIT"}
|
||||||
requires-python = ">=3.9"
|
requires-python = ">=3.9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"opencv-python>=4.8.0",
|
"opencv-python>=4.8.0",
|
||||||
@@ -10,7 +11,6 @@ dependencies = [
|
|||||||
"pillow>=10.0.0",
|
"pillow>=10.0.0",
|
||||||
"matplotlib>=3.7.0",
|
"matplotlib>=3.7.0",
|
||||||
"scipy>=1.11.0",
|
"scipy>=1.11.0",
|
||||||
"scikit-learn>=1.3.0",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
|
|||||||
@@ -10,10 +10,12 @@ from matplotlib.patches import Rectangle
|
|||||||
from .extractor import DiagramExtractor
|
from .extractor import DiagramExtractor
|
||||||
|
|
||||||
|
|
||||||
def process_all_images(directory, calibration=None, prompt_axis_override=False):
|
def process_all_images(
|
||||||
|
directory, calibration=None, prompt_axis_override=False, max_points=None
|
||||||
|
):
|
||||||
"""Process all PNG images in the directory"""
|
"""Process all PNG images in the directory"""
|
||||||
|
|
||||||
extractor = DiagramExtractor(calibration)
|
extractor = DiagramExtractor(calibration, max_points=max_points)
|
||||||
all_results = {}
|
all_results = {}
|
||||||
|
|
||||||
for filename in os.listdir(directory):
|
for filename in os.listdir(directory):
|
||||||
@@ -201,10 +203,26 @@ def main():
|
|||||||
print(f" X-axis: {calibration['x_min']} to {calibration['x_max']}")
|
print(f" X-axis: {calibration['x_min']} to {calibration['x_max']}")
|
||||||
print(f" Y-axis: {calibration['y_min']} to {calibration['y_max']}\n")
|
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()
|
override_choice = input("Override detected axes per image? (y/n): ").strip().lower()
|
||||||
prompt_axis_override = override_choice in ("y", "yes")
|
prompt_axis_override = override_choice in ("y", "yes")
|
||||||
|
|
||||||
results = process_all_images(images_dir, calibration, prompt_axis_override)
|
results = process_all_images(
|
||||||
|
images_dir, calibration, prompt_axis_override, max_points
|
||||||
|
)
|
||||||
|
|
||||||
if results:
|
if results:
|
||||||
print("\n" + "=" * 70)
|
print("\n" + "=" * 70)
|
||||||
|
|||||||
@@ -2,19 +2,21 @@
|
|||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.cluster import DBSCAN
|
|
||||||
|
|
||||||
|
|
||||||
class DiagramExtractor:
|
class DiagramExtractor:
|
||||||
"""Extract data from diagram images with direct real-world coordinate conversion"""
|
"""Extract data from diagram images with direct real-world coordinate conversion"""
|
||||||
|
|
||||||
def __init__(self, calibration=None):
|
def __init__(self, calibration=None, max_points=None):
|
||||||
"""
|
"""
|
||||||
Initialize extractor with optional calibration parameters
|
Initialize extractor with optional calibration parameters
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
calibration: Dict with x_min, x_max, y_min, y_max
|
calibration: Dict with x_min, x_max, y_min, y_max
|
||||||
If None, will use default values
|
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 {
|
self.calibration = calibration or {
|
||||||
"x_min": 0,
|
"x_min": 0,
|
||||||
@@ -22,6 +24,7 @@ class DiagramExtractor:
|
|||||||
"y_min": 0,
|
"y_min": 0,
|
||||||
"y_max": 1,
|
"y_max": 1,
|
||||||
}
|
}
|
||||||
|
self.max_points = max_points
|
||||||
|
|
||||||
def set_calibration(self, x_min, x_max, y_min, y_max):
|
def set_calibration(self, x_min, x_max, y_min, y_max):
|
||||||
"""Update calibration parameters"""
|
"""Update calibration parameters"""
|
||||||
@@ -209,28 +212,38 @@ class DiagramExtractor:
|
|||||||
# Sort by x coordinate
|
# Sort by x coordinate
|
||||||
points = points[points[:, 0].argsort()]
|
points = points[points[:, 0].argsort()]
|
||||||
|
|
||||||
# Sample points uniformly by x coordinate
|
# Group points by x-coordinate bins and take median y-value
|
||||||
n_samples = min(max(50, len(points) // 5), len(points))
|
# This centers the line even when edges are detected on both sides
|
||||||
indices = np.linspace(0, len(points) - 1, n_samples, dtype=int)
|
x_min_pt, x_max_pt = points[:, 0].min(), points[:, 0].max()
|
||||||
sampled_points = points[indices]
|
|
||||||
|
|
||||||
# Further smoothing: group very close points
|
# Determine number of bins based on desired samples
|
||||||
if len(sampled_points) > 1:
|
if self.max_points is not None:
|
||||||
clustering = DBSCAN(eps=3, min_samples=1).fit(sampled_points)
|
n_bins = self.max_points
|
||||||
labels = clustering.labels_
|
|
||||||
|
|
||||||
# Get cluster centers
|
|
||||||
unique_labels = np.unique(labels)
|
|
||||||
final_points = []
|
|
||||||
for label in unique_labels:
|
|
||||||
cluster_points = sampled_points[labels == label]
|
|
||||||
center = cluster_points.mean(axis=0)
|
|
||||||
final_points.append(center)
|
|
||||||
|
|
||||||
final_points = np.array(final_points)
|
|
||||||
final_points = final_points[final_points[:, 0].argsort()]
|
|
||||||
else:
|
else:
|
||||||
final_points = sampled_points
|
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
|
# Convert pixel coordinates to real-world data values
|
||||||
x_scale = self.calibration["x_max"] - self.calibration["x_min"]
|
x_scale = self.calibration["x_max"] - self.calibration["x_min"]
|
||||||
|
|||||||
Reference in New Issue
Block a user