commit a4335d69dfc271d9fe42f5c3a6c4dbe6950f76ed Author: diaco Date: Tue Feb 10 13:18:03 2026 +0330 initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..2ad60e4 --- /dev/null +++ b/README.md @@ -0,0 +1,199 @@ +# Data Extraction from Diagram Images + +This toolkit extracts data points from PNG diagrams containing plots with x and y axes and curves/waves. + +## Files Overview + +- **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 + +## Quick Start + +### Step 1: Extract Data from Your Images + +The extraction script has already been run. It processes all PNG files in the directory and creates: + +```bash +python extract_data.py +``` + +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: + +```bash +python calibrate_and_visualize.py +``` + +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 + +## Understanding the Extracted Data + +### 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 + +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} +] +``` + +### Calibration to Real Values + +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`: + +```python +calibration = { + 'x_min': 0, + 'x_max': 100, + 'y_min': -10, + 'y_max': 10 +} +``` + +### Working with the JSON Data + +Load and process the extracted data programmatically: + +```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']}") + + # Access the data points + for point in results['normalized_data_points'][:5]: + print(f" x={point['x']:.4f}, y={point['y']:.4f}") +``` + +## Technical Details + +### Detection Method + +1. **Axis Detection**: Uses morphological operations to find horizontal and vertical lines +2. **Edge Detection**: Applies Canny edge detection to find curve boundaries +3. **Point Extraction**: Converts edge pixels to normalized coordinates +4. **Clustering**: Groups nearby pixels into single data points using DBSCAN +5. **Sorting**: Orders points by x-coordinate for consistency + +### Parameters + +Key parameters in `extract_data.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 | + +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 +- Check that curves aren't too light/faint + +### Too many noisy points +- Increase DBSCAN eps value +- Increase Canny high threshold + +### Axes not detected properly +- Check that axes are clearly visible dark lines +- May need to adjust morphological kernel sizes + +## Dependencies + +- opencv-python +- numpy +- pillow +- scipy +- scikit-learn +- matplotlib + +All dependencies are pre-installed in the virtual environment. + +## Questions or Issues? + +The extraction is based on image processing techniques: +- 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 + +--- + +**Output Summary**: You now have 269 and 1188 extracted data points from your diagrams in normalized coordinates, ready for calibration! diff --git a/extract.sh b/extract.sh new file mode 100755 index 0000000..a93ba00 --- /dev/null +++ b/extract.sh @@ -0,0 +1,3 @@ +#!/bin/bash +# Wrapper script to run extract_data_absolute.py with the virtual environment +.venv/bin/python extract_data_absolute.py "$@" diff --git a/extract_data_absolute.py b/extract_data_absolute.py new file mode 100644 index 0000000..a33af0b --- /dev/null +++ b/extract_data_absolute.py @@ -0,0 +1,372 @@ +import cv2 +import numpy as np +from PIL import Image +import matplotlib.pyplot as plt +from matplotlib.patches import Rectangle +import os +import json +from scipy import ndimage +from scipy.signal import find_peaks +from sklearn.cluster import DBSCAN + +class DiagramExtractor: + """Extract data from diagram images with direct real-world coordinate conversion""" + + def __init__(self, calibration=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 + """ + self.calibration = calibration or { + 'x_min': 0, + 'x_max': 1, + 'y_min': 0, + 'y_max': 1 + } + + 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): + """ + 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) + 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) + + # Find contours for axes + 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) + + # Find axis boundaries + y_axis_x = None + x_axis_y = None + + # Find leftmost vertical line (Y-axis) + if contours_v: + leftmost = min(contours_v, key=lambda c: cv2.boundingRect(c)[0]) + x, y, w, h = cv2.boundingRect(leftmost) + y_axis_x = x + + # Find bottommost horizontal line (X-axis) + if 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 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 + plot_left = y_axis_x + plot_right = width - int(width * 0.08) + plot_top = int(height * 0.08) + 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 axes from edges + plot_edges[0:5, :] = 0 + plot_edges[-5:, :] = 0 + plot_edges[:, 0:5] = 0 + plot_edges[:, -5:] = 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()] + + # 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] + + # 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()] + else: + final_points = sampled_points + + # 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 + + +def process_all_images(directory, calibration=None): + """Process all PNG images in the directory""" + + extractor = DiagramExtractor(calibration) + 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: + 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_file='extracted_data.json'): + """Save extracted data to JSON file""" + + 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'] + + 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) + 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 + } + + +if __name__ == "__main__": + current_dir = os.path.dirname(os.path.abspath(__file__)) + + 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") + + results = process_all_images(current_dir, calibration) + + 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) + save_csv_results(results, current_dir) + + visualize_choice = input("\nSave visualization overlays? (y/n): ").strip().lower() + if visualize_choice in ("y", "yes"): + visualize_results(results, current_dir) + + print("\n" + "=" * 70) + print("Extraction complete!") + print("=" * 70) + else: + print("No images were successfully processed.")