261 lines
8.7 KiB
Python
261 lines
8.7 KiB
Python
"""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, max_points=None
|
|
):
|
|
"""Process all PNG images in the directory"""
|
|
|
|
extractor = DiagramExtractor(calibration, max_points=max_points)
|
|
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")
|
|
|
|
# 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, max_points
|
|
)
|
|
|
|
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()
|