import numpy as np
from svgpathtools import svg2paths
from scipy.special import binom
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
import math
from math import atan2, degrees, sqrt
from itertools import combinations
for i in range(n):
d_curve += np.outer(bernstein_poly(i, n-1, t), n * (points[i+1] - points[i]))
for i in range(n-1):
d2_curve += np.outer(bernstein_poly(i, n-2, t), n * (n-1) * (points[i+2] - 2*points[i+1] + points[i]))
return d_curve, d2_curve
db = DBSCAN(eps=tolerance, min_samples=2).fit(all_points)
labels = db.labels_
for label in set(labels):
if label != -1:
indices = np.where(labels == label)[0]
centroid = np.mean(all_points[indices], axis=0)
all_points[indices] = centroid
for curve in curves:
start, end = tuple(curve[0]), tuple(curve[-1])
if (start, end) not in seen_endpoints and (end, start) not in seen_endpoints:
unique_curves.append(curve)
seen_endpoints.add((start, end))
return np.array(unique_curves)
def remove_almost_equal_elements(lst, epsilon=0.1):
n = len(lst)
maparray = [False] * n
for i in range(n):
for j in range(i + 1, n):
if almost_equal(lst[i], lst[j], 5):
maparray[i] = True
maparray[j] = True
return [lst[i] for i in range(n) if not maparray[i]]
for point in slope_dict:
slope_dict[point] = remove_almost_equal_elements(slope_dict[point], 0.1)
corner_points = {}
for point in slope_dict:
if len(slope_dict[point]) == 1:
corner_points[point] = slope_dict[point][0]
bezier_curves = np.round(cubic_beziers, decimals=3)
def on_same_bezier_curve(p1, p2, haha):
for curve in haha:
if any(np.all(curve == p1, axis=1)) and any(np.all(curve == p2, axis=1)):
return True
return False
result_pairs = []
for pair in sorted_pairs:
p1, p2 = pair[0], pair[1]
if (p1 not in [p for pair in result_pairs for p in pair]) and (p2 not in [p for pair in result_pairs for p in pair]):
result_pairs.append((p1, p2))
if len(result_pairs) == 4:
break
control_points = [make_filler_curve(p1[0], p1[1], corner_points[p1], p2[0], p2[1], corner_points[p2])
for p1, p2 in result_pairs]
final_curves = np.vstack((cubic_beziers, np.array(control_points)))
plot_bezier_curves(final_curves, [])
instead of svg we have a csv
use this function to read csv
please use csv and give output
def read_csv(csv_path):
"""Reads a CSV file and organizes the points into paths."""
np_path_XYs = np.genfromtxt(csv_path, delimiter=',')
path_XYs = []
for i in np.unique(np_path_XYs[:, 0]):
npXYs = np_path_XYs[np_path_XYs[:, 0] == i][:, 1:]
XYs = []
for j in np.unique(npXYs[:, 0]):
XY = npXYs[npXYs[:, 0] == j][:, 1:]
XYs.append(XY)
path_XYs.append(XYs)
return path_XYs
please do so
Certainly! To adapt your existing code from processing SVG files to handling CSV files, we'll need to make several modifications. Here's a comprehensive guide to help you transition smoothly.
Assumptions about the CSV Structure
Before proceeding, it's essential to understand the structure of your CSV file. Based on the provided read_csv function, we'll assume the CSV has the following columns:
Path Identifier (i): Indicates different paths or groups of curves.
Sub-Path Identifier (j): Indicates different sub-paths within a path.
Point Coordinates: Subsequent columns represent the (x, y) coordinates of points defining the Bezier curves.
Each row in the CSV corresponds to a point in a Bezier curve, organized by path and sub-path identifiers.
Updated Workflow Overview
Read and Organize CSV Data: Use the provided read_csv function to read the CSV and organize points into paths.
Extract Bezier Curves from Points: Convert the organized points into cubic and quadratic Bezier curves.
Process Bezier Curves: Perform clustering, remove duplicates, calculate slopes, identify corner points, and create filler curves.
Plot the Final Bezier Curves: Visualize the original and filler Bezier curves.
Updated Code Implementation
Below is the complete updated code that incorporates reading from a CSV file instead of an SVG file:
python
import numpy as np
from scipy.special import binom
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
import math
from math import atan2, degrees, sqrt
from itertools import combinations
# Define the CSV file path
csv_file_path = 'path_to_your_file.csv' # Replace with your actual CSV file path
def bernstein_poly(i, n, t):
return binom(n, i) * (t**(n-i)) * ((1 - t)**i)
def bezier_curve(points, n_points=100):
n = len(points) - 1
t = np.linspace(0, 1, n_points)
curve = np.zeros((n_points, 2))
for i in range(n + 1):
curve += np.outer(bernstein_poly(i, n, t), points[i])
return curve
def bezier_derivatives(points, n_points=100):
n = len(points) - 1
t = np.linspace(0, 1, n_points)
d_curve = np.zeros((n_points, 2))
d2_curve = np.zeros((n_points, 2))
for i in range(n):
d_curve += np.outer(bernstein_poly(i, n-1, t), n * (points[i+1] - points[i]))
for i in range(n-1):
d2_curve += np.outer(bernstein_poly(i, n-2, t), n * (n-1) * (points[i+2] - 2*points[i+1] + points[i]))
return d_curve, d2_curve
def read_csv(csv_path):
"""Reads a CSV file and organizes the points into paths."""
np_path_XYs = np.genfromtxt(csv_path, delimiter=',')
path_XYs = []
for i in np.unique(np_path_XYs[:, 0]):
npXYs = np_path_XYs[np_path_XYs[:, 0] == i][:, 1:]
XYs = []
for j in np.unique(npXYs[:, 0]):
XY = npXYs[npXYs[:, 0] == j][:, 1:]
XYs.append(XY)
path_XYs.append(XYs)
return path_XYs
def extract_bezier_curves_from_csv(csv_path):
"""Extracts cubic and quadratic Bezier curves from CSV data."""
path_XYs = read_csv(csv_path)
cubic_bezier_points = []
quadratic_bezier_points = []
for path in path_XYs:
for sub_path in path:
# Determine if the sub_path represents a cubic or quadratic Bezier curve based on the number of points
if len(sub_path) == 4:
# Cubic Bezier: P0, P1, P2, P3
cubic_bezier_points.append(sub_path)
elif len(sub_path) == 3:
# Quadratic Bezier: P0, P1, P2
quadratic_bezier_points.append(sub_path)
else:
print(f"Unsupported number of points in sub-path: {len(sub_path)}")
cubic_bezier_points = np.array(cubic_bezier_points)
quadratic_bezier_points = np.array(quadratic_bezier_points)
return cubic_bezier_points, quadratic_bezier_points
def osculating_circle_center(points, threshold, n_points=100):
curve = bezier_curve(points, n_points)
d_curve, d2_curve = bezier_derivatives(points, n_points)
curvature = (d_curve[:, 0] * d2_curve[:, 1] - d_curve[:, 1] * d2_curve[:, 0]) / (d_curve[:, 0]**2 + d_curve[:, 1]**2)**1.5
radius_of_curvature = 1 / np.abs(curvature)
normal = np.zeros_like(d_curve)
normal[:, 0] = -d_curve[:, 1]
normal[:, 1] = d_curve[:, 0]
normal_direction = np.sign(curvature)
normal *= normal_direction[:, np.newaxis]
normal /= np.linalg.norm(normal, axis=1, keepdims=True)
centers = curve + normal * radius_of_curvature[:, np.newaxis]
distances = np.linalg.norm(centers - curve, axis=1)
valid_centers = centers[distances < threshold]
return valid_centers
def calculate_curvature(points, n_points=100):
d_curve, d2_curve = bezier_derivatives(points, n_points)
curvature = (d_curve[:, 0] * d2_curve[:, 1] - d_curve[:, 1] * d2_curve[:, 0]) / (d_curve[:, 0]**2 + d_curve[:, 1]**2)**1.5
return curvature
def plot_bezier_curves(cubic_points, quadratic_points, threshold=1.0, show_centres=False, size=10):
plt.figure(figsize=(size, size))
for points in cubic_points:
curve = bezier_curve(points)
centers = osculating_circle_center(points, threshold)
color = np.random.rand(3,) # Random color for each curve
plt.plot(curve[:, 0], curve[:, 1], label='Cubic Bezier', color=color)
# plt.plot(points[:, 0], points[:, 1], 'ro--') # Control points
if show_centres:
plt.plot(centers[:, 0], centers[:, 1], 'x', label='Osculating Circle Centers', color=color) # Osculating circle centers
for points in quadratic_points:
curve = bezier_curve(points)
centers = osculating_circle_center(points, threshold)
color = np.random.rand(3,) # Random color for each curve
plt.plot(curve[:, 0], curve[:, 1], label='Quadratic Bezier', color=color)
plt.plot(points[:, 0], points[:, 1], 'bo--') # Control points
if show_centres:
plt.plot(centers[:, 0], centers[:, 1], 'x', label='Osculating Circle Centers', color=color) # Osculating circle centers
# To avoid duplicate labels in the legend
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())
if show_centres:
plt.title('Bezier Curves with Osculating Circle Centres')
else:
plt.title('Bezier Curves')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid()
plt.show()
# Read and extract Bezier curves from CSV
cubic_beziers, quadratic_beziers = extract_bezier_curves_from_csv(csv_file_path)
# Initial plot without osculating circle centers
plot_bezier_curves(cubic_beziers, quadratic_beziers, size=5)
# Plot with osculating circle centers
plot_bezier_curves(cubic_beziers, quadratic_beziers, show_centres=True, threshold=100, size=5)
# Proceed with clustering and processing
tolerance = 0.5
startpoints = cubic_beziers[:, 0, :]
endpoints = cubic_beziers[:, -1, :]
all_points = np.vstack((startpoints, endpoints))
db = DBSCAN(eps=tolerance, min_samples=2).fit(all_points)
labels = db.labels_
for label in set(labels):
if label != -1:
indices = np.where(labels == label)[0]
centroid = np.mean(all_points[indices], axis=0)
all_points[indices] = centroid
cubic_beziers[:, 0, :] = all_points[:len(cubic_beziers)]
cubic_beziers[:, -1, :] = all_points[len(cubic_beziers):]
def get_unique_curves(curves):
unique_curves = []
seen_endpoints = set()
for curve in curves:
start, end = tuple(curve[0]), tuple(curve[-1])
if (start, end) not in seen_endpoints and (end, start) not in seen_endpoints:
unique_curves.append(curve)
seen_endpoints.add((start, end))
return np.array(unique_curves)
cubic_beziers = get_unique_curves(cubic_beziers)
# print(len(cubic_beziers))
def bezier_tangent_equations(P0, P1, P2, P3):
derivative_start = 3 * (P1 - P0)
derivative_end = 3 * (P3 - P2)
slope_start = derivative_start[1] / derivative_start[0] if derivative_start[0] != 0 else np.inf
slope_end = derivative_end[1] / derivative_end[0] if derivative_end[0] != 0 else np.inf
return slope_start, slope_end
slope_dict = {}
for cubic_bezier in cubic_beziers:
start_point = cubic_bezier[0]
end_point = cubic_bezier[-1]
slope_dict[tuple(np.round(start_point, decimals=4))] = []
slope_dict[tuple(np.round(end_point, decimals=4))] = []
for cubic_bezier in cubic_beziers:
start_point = cubic_bezier[0]
end_point = cubic_bezier[-1]
slope_start, slope_end = bezier_tangent_equations(cubic_bezier[0], cubic_bezier[1], cubic_bezier[2], cubic_bezier[3])
slope_dict[tuple(np.round(start_point, decimals=4))].append(slope_start)
slope_dict[tuple(np.round(end_point, decimals=4))].append(slope_end)
def almost_equal(a, b, threshold):
a_rad = math.atan(a) if a != np.inf else np.pi / 2
b_rad = math.atan(b) if b != np.inf else np.pi / 2
return abs(a_rad - b_rad) <= math.radians(threshold)
def remove_almost_equal_elements(lst, epsilon=0.1):
n = len(lst)
maparray = [False] * n
for i in range(n):
if maparray[i]:
continue
for j in range(i + 1, n):
if almost_equal(lst[i], lst[j], 5):
maparray[j] = True
return [lst[i] for i in range(n) if not maparray[i]]
for point in slope_dict:
slope_dict[point] = remove_almost_equal_elements(slope_dict[point], 0.1)
corner_points = {}
for point in slope_dict:
if len(slope_dict[point]) == 1:
corner_points[point] = slope_dict[point][0]
bezier_curves = np.round(cubic_beziers, decimals=3)
def on_same_bezier_curve(p1, p2, curves):
for curve in curves:
if any(np.all(curve == p1, axis=1)) and any(np.all(curve == p2, axis=1)):
return True
return False
def angle_between_slopes(slope1, slope2):
if slope1 == np.inf and slope2 == np.inf:
return 0
if slope1 == np.inf:
slope1 = math.tan(math.pi / 2 - 1e-6)
if slope2 == np.inf:
slope2 = math.tan(math.pi / 2 - 1e-6)
angle = math.atan(abs((slope2 - slope1) / (1 + slope1 * slope2)))
return math.degrees(angle)
def distance_between_points(p1, p2):
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
pairs = []
for (p1, s1), (p2, s2) in combinations(corner_points.items(), 2):
if not on_same_bezier_curve(p1, p2, bezier_curves):
angle = angle_between_slopes(s1, s2)
distance = distance_between_points(p1, p2)
pairs.append((p1, p2, angle, distance))
sorted_pairs = sorted(pairs, key=lambda x: (x[3], x[2]))
result_pairs = []
for pair in sorted_pairs:
p1, p2 = pair[0], pair[1]
if (p1 not in [p for pair in result_pairs for p in pair]) and (p2 not in [p for pair in result_pairs for p in pair]):
result_pairs.append((p1, p2))
if len(result_pairs) == 4:
break
def find_intersection(x1, y1, m1, x2, y2, m2):
if m1 == m2:
raise ValueError("Lines are parallel.")
if m1 == np.inf:
x_intersect = x1
y_intersect = m2 * (x_intersect - x2) + y2
elif m2 == np.inf:
x_intersect = x2
y_intersect = m1 * (x_intersect - x1) + y1
else:
x_intersect = (m1 * x1 - m2 * x2 + y2 - y1) / (m1 - m2)
y_intersect = m1 * (x_intersect - x1) + y1
return x_intersect, y_intersect
def make_filler_curve(x1, y1, m1, x2, y2, m2):
try:
x_int, y_int = find_intersection(x1, y1, m1, x2, y2, m2)
except ValueError:
# Handle parallel lines by choosing a midpoint or random point
x_int, y_int = (x1 + x2) / 2, (y1 + y2) / 2
cx1, cy1 = (x1 + x_int) / 2, (y1 + y_int) / 2
cx2, cy2 = (x2 + x_int) / 2, (y2 + y_int) / 2
return [(x1, y1), (cx1, cy1), (cx2, cy2), (x2, y2)]
control_points = [make_filler_curve(p1[0], p1[1], corner_points[p1], p2[0], p2[1], corner_points[p2])
for p1, p2 in result_pairs]
# Convert control points to cubic Bezier format
control_points = np.array(control_points)
final_curves = np.vstack((cubic_beziers, control_points))
# Plot the final curves
plot_bezier_curves(final_curves, quadratic_beziers)
Explanation of Changes
Reading from CSV:
Function Used: Replaced extract_bezier_curves with extract_bezier_curves_from_csv which utilizes the provided read_csv function to read and organize the CSV data.
Handling Bezier Types: The function distinguishes between cubic and quadratic Bezier curves based on the number of points:
Cubic Bezier: Requires 4 points (P0, P1, P2, P3).
Quadratic Bezier: Requires 3 points (P0, P1, P2).
Error Handling: Prints a message if a sub-path doesn't match expected Bezier types.
Plotting Adjustments:
Legend Improvements: Modified the plotting function to avoid duplicate labels in the legend.
Handling Osculating Circles: Ensured that osculating circles are only plotted when show_centres is True.
Slope Calculations Enhancements:
Handling Infinite Slopes: Modified the angle_between_slopes function to handle cases where slopes are infinite (np.inf), ensuring that vertical lines are correctly processed.
Intersection Handling:
Parallel Lines: Enhanced the find_intersection function to handle parallel lines gracefully by choosing a midpoint if an intersection cannot be found.
Final Curves Composition:
Combining Original and Filler Curves: Ensured that the final_curves array includes both the original cubic Bezier curves and the newly created filler curves.
Usage Instructions
Prepare Your CSV File:
Ensure your CSV file follows the expected structure:
First Column: Path identifier (i).
Second Column: Sub-path identifier (j).
Subsequent Columns: Point coordinates in pairs (x, y). For cubic Bezier curves, there should be 4 points; for quadratic, 3 points.
Update File Path:
Replace 'path_to_your_file.csv' with the actual path to your CSV file in the csv_file_path variable.
Run the Script:
Execute the script in your Python environment. It will:
Read and parse the CSV data.
Extract cubic and quadratic Bezier curves.
Plot the curves with and without osculating circle centers.
Perform clustering and processing to identify unique curves and corner points.
Create and plot filler curves based on identified corner points.
Additional Considerations
Data Validation: Ensure that your CSV data is clean and follows the expected format. The script includes basic error handling, but additional validation might be necessary depending on your data's complexity.
Customization: You can adjust parameters such as threshold, tolerance, and size in the plotting function to better suit your specific use case and visualize the curves effectively.
Performance: For very large CSV files with numerous Bezier curves, consider optimizing the clustering and duplicate removal steps to enhance performance.
Conclusion
By following the above changes and understanding their purposes, you should be able to effectively transition your Bezier curve processing from SVG files to CSV files. This adaptation leverages the power of CSV data manipulation while retaining the core functionalities of your original script.
If you encounter any issues or have further questions, feel free to ask!