Files
extract_plot_data_from_pic/extract_data_absolute.py
2026-02-10 13:34:22 +03:30

389 lines
14 KiB
Python

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 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()]
# 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.")