improved point detection

This commit is contained in:
2026-02-13 00:01:27 +03:30
parent 44d35ebc86
commit f20fbc9d0b
4 changed files with 98 additions and 45 deletions

View File

@@ -74,6 +74,25 @@ 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
@@ -97,10 +116,11 @@ 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/`
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
@@ -178,9 +198,11 @@ for image_name, results in data.items():
```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)
# 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
@@ -204,34 +226,36 @@ result = extractor.extract(
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
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 `extract_data.py`:
Key parameters in `extractor.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 |
| `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 Canny edge detection thresholds lower
- Reduce DBSCAN eps value for finer clustering
- 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 points
- Increase DBSCAN eps value
### 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
@@ -245,7 +269,6 @@ All dependencies are automatically managed by UV and specified in [pyproject.tom
- pillow - Image manipulation
- matplotlib - Visualization
- scipy - Scientific computing
- scikit-learn - Machine learning (DBSCAN clustering)
Install with:
```bash

View File

@@ -11,7 +11,6 @@ dependencies = [
"pillow>=10.0.0",
"matplotlib>=3.7.0",
"scipy>=1.11.0",
"scikit-learn>=1.3.0",
]
[project.scripts]

View File

@@ -10,10 +10,12 @@ from matplotlib.patches import Rectangle
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"""
extractor = DiagramExtractor(calibration)
extractor = DiagramExtractor(calibration, max_points=max_points)
all_results = {}
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" 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)
results = process_all_images(
images_dir, calibration, prompt_axis_override, max_points
)
if results:
print("\n" + "=" * 70)

View File

@@ -2,19 +2,21 @@
import cv2
import numpy as np
from sklearn.cluster import DBSCAN
class DiagramExtractor:
"""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
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,
@@ -22,6 +24,7 @@ class DiagramExtractor:
"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"""
@@ -209,28 +212,38 @@ class DiagramExtractor:
# Sort by x coordinate
points = points[points[:, 0].argsort()]
# Sample points uniformly by x coordinate
n_samples = min(max(50, len(points) // 5), len(points))
indices = np.linspace(0, len(points) - 1, n_samples, dtype=int)
sampled_points = points[indices]
# 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()
# Further smoothing: group very close points
if len(sampled_points) > 1:
clustering = DBSCAN(eps=3, min_samples=1).fit(sampled_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()]
# Determine number of bins based on desired samples
if self.max_points is not None:
n_bins = self.max_points
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
x_scale = self.calibration["x_max"] - self.calibration["x_min"]