made uv package
This commit is contained in:
7
src/extract_plot_data/__init__.py
Normal file
7
src/extract_plot_data/__init__.py
Normal file
@@ -0,0 +1,7 @@
|
||||
"""Extract plot data from diagram images."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
from .extractor import DiagramExtractor
|
||||
|
||||
__all__ = ["DiagramExtractor"]
|
||||
242
src/extract_plot_data/cli.py
Normal file
242
src/extract_plot_data/cli.py
Normal file
@@ -0,0 +1,242 @@
|
||||
"""Command-line interface for plot data extraction."""
|
||||
|
||||
import os
|
||||
import json
|
||||
import cv2
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.patches import Rectangle
|
||||
|
||||
from .extractor import DiagramExtractor
|
||||
|
||||
|
||||
def process_all_images(directory, calibration=None, prompt_axis_override=False):
|
||||
"""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 and prompt_axis_override:
|
||||
axes = result.get("axes", {})
|
||||
detected_y_axis_x = axes.get("y_axis_x")
|
||||
detected_x_axis_y = axes.get("x_axis_y")
|
||||
|
||||
print(f"Detected axes for {filename}:")
|
||||
print(f" Y-axis x={detected_y_axis_x}px")
|
||||
print(f" X-axis y={detected_x_axis_y}px")
|
||||
|
||||
raw_y = input("Override Y-axis x (pixels, blank to accept): ").strip()
|
||||
raw_x = input("Override X-axis y (pixels, blank to accept): ").strip()
|
||||
|
||||
axes_override = {}
|
||||
if raw_y:
|
||||
axes_override["y_axis_x"] = int(raw_y)
|
||||
if raw_x:
|
||||
axes_override["x_axis_y"] = int(raw_x)
|
||||
|
||||
if axes_override:
|
||||
result = extractor.extract(filepath, axes_override=axes_override)
|
||||
|
||||
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_dir=".", output_filename="extracted_data.json"):
|
||||
"""Save extracted data to JSON file"""
|
||||
|
||||
output_file = os.path.join(output_dir, output_filename)
|
||||
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"]
|
||||
axes = data.get("axes", {})
|
||||
y_axis_x = axes.get("y_axis_x")
|
||||
x_axis_y = axes.get("x_axis_y")
|
||||
|
||||
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)
|
||||
|
||||
if y_axis_x is not None:
|
||||
ax.axvline(y_axis_x, color="blue", linewidth=2, linestyle="--", alpha=0.9)
|
||||
ax.text(
|
||||
y_axis_x + 8,
|
||||
plot_top + 20,
|
||||
f"Y-axis x={y_axis_x}px",
|
||||
color="blue",
|
||||
fontsize=9,
|
||||
bbox=dict(facecolor="white", alpha=0.7, edgecolor="none"),
|
||||
)
|
||||
|
||||
if x_axis_y is not None:
|
||||
ax.axhline(x_axis_y, color="orange", linewidth=2, linestyle="--", alpha=0.9)
|
||||
ax.text(
|
||||
plot_left + 8,
|
||||
x_axis_y - 8,
|
||||
f"X-axis y={x_axis_y}px",
|
||||
color="orange",
|
||||
fontsize=9,
|
||||
bbox=dict(facecolor="white", alpha=0.7, edgecolor="none"),
|
||||
)
|
||||
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}
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point for CLI"""
|
||||
current_dir = os.getcwd()
|
||||
output_dir = os.path.join(current_dir, "extracted_output")
|
||||
images_dir_input = input("Images folder (default: current directory): ").strip()
|
||||
images_dir = images_dir_input or current_dir
|
||||
if not os.path.isdir(images_dir):
|
||||
print(f"Images folder not found: {images_dir}")
|
||||
return
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
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")
|
||||
|
||||
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)
|
||||
|
||||
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, output_dir)
|
||||
save_csv_results(results, output_dir)
|
||||
|
||||
visualize_choice = (
|
||||
input("\nSave visualization overlays? (y/n): ").strip().lower()
|
||||
)
|
||||
if visualize_choice in ("y", "yes"):
|
||||
visualize_results(results, output_dir)
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("Extraction complete!")
|
||||
print("=" * 70)
|
||||
else:
|
||||
print("No images were successfully processed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
272
src/extract_plot_data/extractor.py
Normal file
272
src/extract_plot_data/extractor.py
Normal file
@@ -0,0 +1,272 @@
|
||||
"""Core diagram extraction functionality."""
|
||||
|
||||
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):
|
||||
"""
|
||||
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, axes_override=None):
|
||||
"""
|
||||
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) using Hough as primary
|
||||
y_axis_x = None
|
||||
x_axis_y = None
|
||||
|
||||
min_line_length = int(min(width, height) * 0.4)
|
||||
hough_lines = cv2.HoughLinesP(
|
||||
edges,
|
||||
1,
|
||||
np.pi / 180,
|
||||
threshold=120,
|
||||
minLineLength=min_line_length,
|
||||
maxLineGap=10,
|
||||
)
|
||||
|
||||
vertical_candidates = []
|
||||
horizontal_candidates = []
|
||||
|
||||
if hough_lines is not None:
|
||||
for x1, y1, x2, y2 in hough_lines[:, 0]:
|
||||
dx = abs(x1 - x2)
|
||||
dy = abs(y1 - y2)
|
||||
if dy > dx * 3:
|
||||
vertical_candidates.append((x1, y1, x2, y2, dy))
|
||||
elif dx > dy * 3:
|
||||
horizontal_candidates.append((x1, y1, x2, y2, dx))
|
||||
|
||||
if vertical_candidates:
|
||||
vertical_candidates.sort(key=lambda item: item[4], reverse=True)
|
||||
top_vertical = vertical_candidates[:5]
|
||||
xs = [int(round((x1 + x2) / 2)) for x1, y1, x2, y2, _ in top_vertical]
|
||||
y_axis_x = min(xs)
|
||||
|
||||
if horizontal_candidates:
|
||||
horizontal_candidates.sort(key=lambda item: item[4], reverse=True)
|
||||
top_horizontal = horizontal_candidates[:5]
|
||||
ys = [int(round((y1 + y2) / 2)) for x1, y1, x2, y2, _ in top_horizontal]
|
||||
x_axis_y = max(ys)
|
||||
|
||||
# Fallback to morphology-based detection if Hough misses
|
||||
if y_axis_x is None or x_axis_y is None:
|
||||
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)
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
if y_axis_x is None and contours_v:
|
||||
leftmost = min(contours_v, key=lambda c: cv2.boundingRect(c)[0])
|
||||
x, y, w, h = cv2.boundingRect(leftmost)
|
||||
y_axis_x = x
|
||||
|
||||
if x_axis_y is None and 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 axes_override:
|
||||
if "y_axis_x" in axes_override and axes_override["y_axis_x"] is not None:
|
||||
y_axis_x = int(axes_override["y_axis_x"])
|
||||
if "x_axis_y" in axes_override and axes_override["x_axis_y"] is not None:
|
||||
x_axis_y = int(axes_override["x_axis_y"])
|
||||
|
||||
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 with minimal margins to include plots near edges
|
||||
margin_right = max(5, int(width * 0.01))
|
||||
margin_top = max(5, int(height * 0.01))
|
||||
|
||||
plot_left = y_axis_x
|
||||
plot_right = width - margin_right
|
||||
plot_top = margin_top
|
||||
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
|
||||
Reference in New Issue
Block a user