made uv package

This commit is contained in:
2026-02-12 03:18:47 +03:30
parent 793afaffa4
commit ca779b3d33
8 changed files with 807 additions and 109 deletions

298
README.md
View File

@@ -2,127 +2,160 @@
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
- **calibrate_and_visualize.py** - Visualization and calibration tool for converting normalized coordinates to actual values
- **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
- Python 3.9 or higher
- [UV](https://github.com/astral-sh/uv) - Fast Python package manager
## Quick Start
## Installation
### Step 1: Extract Data from Your Images
The extraction script has already been run. It processes all PNG files in the directory and creates:
### Install UV (if not already installed)
```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:
- `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:
### Install Project Dependencies
```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:
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
## Usage
## Understanding the Extracted Data
### Command Line Interface
### Normalized Coordinates
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
Run the extraction tool directly:
Example from extracted_data.json:
```json
"normalized_data_points": [
{"x": 0.0120, "y": 0.6439},
{"x": 0.0130, "y": 0.5682},
{"x": 0.0130, "y": 0.6061}
]
```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
```
### Calibration to Real Values
### Python API
To convert normalized coordinates to actual values, you need to know what the axes represent.
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`:
Use the extraction functionality in your own Python code:
```python
calibration = {
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}")
```
### Working with the JSON Data
## Files Overview
Load and process the extracted data programmatically:
- **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
@@ -133,21 +166,48 @@ with open('extracted_data.json', 'r') as 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
for point in results['normalized_data_points'][:5]:
# 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 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
3. **Point Extraction**: Converts edge pixels to normalized coordinates
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
@@ -178,19 +238,43 @@ Adjust these if extraction quality is poor for your specific images.
## Dependencies
- opencv-python
- numpy
- pillow
- scipy
- scikit-learn
- matplotlib
All dependencies are automatically managed by UV and specified in [pyproject.toml](pyproject.toml):
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
- 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
- Digital diagrams work best
- For best results, ensure axes and curves are clearly visible with good contrast