Certainly! Let's walk through the provided Python script step by step to understand its purpose, functionality, and how each part contributes to the overall process. This script primarily deals with processing and manipulating Bézier curves extracted from an SVG file. Here's a comprehensive breakdown:
1. Overview
The script aims to:
- Extract Bézier Curves: Read an SVG file and extract both cubic and quadratic Bézier curves.
- Analyze Curves: Compute properties like curvature and osculating circles.
- Cluster Endpoints: Use clustering to group similar endpoints of curves.
- Identify Corners: Detect points where curves meet with distinct slopes, indicating potential corners or intersections.
- Create Filler Curves: Generate new Bézier curves to fill or smooth these corners.
- Visualize Results: Plot the original and modified curves for visualization.
2. Detailed Breakdown
Imports and Setup
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
file_path = '../problems/occlusion2.svg'
Bézier Curve Utilities
Bernstein Polynomial
def bernstein_poly(i, n, t):
return binom(n, i) * (t**(n-i)) * ((1 - t)**i)
- Purpose: Computes the Bernstein polynomial basis, essential for defining Bézier curves.
- Parameters:
i: Current term.
n: Degree of the polynomial.
t: Parameter ranging from 0 to 1.
Bézier Curve Generation
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
- Purpose: Generates points along a Bézier curve defined by control points.
- Parameters:
points: Control points of the Bézier curve.
n_points: Number of points to compute along the curve.
Bézier Curve Derivatives
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
- Purpose: Computes the first and second derivatives of a Bézier curve, essential for curvature calculations.
- Parameters:
points: Control points.
n_points: Number of derivative points to compute.
SVG Bézier Curve Extraction
def extract_bezier_curves(svg_file):
paths, _ = svg2paths(svg_file)
cubic_bezier_points = []
quadratic_bezier_points = []
for path in paths:
for segment in path:
if segment.__class__.__name__ == 'CubicBezier':
cubic_bezier_points.append([
(segment.start.real, segment.start.imag),
(segment.control1.real, segment.control1.imag),
(segment.control2.real, segment.control2.imag),
(segment.end.real, segment.end.imag)
])
elif segment.__class__.__name__ == 'QuadraticBezier':
quadratic_bezier_points.append([
(segment.start.real, segment.start.imag),
(segment.control.real, segment.control.imag),
(segment.end.real, segment.end.imag)
])
cubic_bezier_points = np.array(cubic_bezier_points)
quadratic_bezier_points = np.array(quadratic_bezier_points)
return cubic_bezier_points, quadratic_bezier_points
- Purpose: Parses the SVG file to extract cubic and quadratic Bézier curve segments.
- Process:
- Parsing Paths: Uses
svg2paths to read SVG paths.
- Segment Identification: Iterates through each path segment, identifying whether it's a
CubicBezier or QuadraticBezier.
- Control Points Extraction: For each identified segment, extracts its control points.
- Conversion to NumPy Arrays: Converts the lists of control points into NumPy arrays for easier manipulation.
Osculating Circle Centers and Curvature
Osculating Circle Center Calculation
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
- Purpose: Calculates the centers of osculating circles along the Bézier curve.
- Osculating Circle: The circle that best "fits" the curve at a given point, providing insight into the curve's curvature.
- Parameters:
points: Control points of the Bézier curve.
threshold: Maximum allowed distance from the curve to consider a center valid.
n_points: Number of points along the curve to compute.
- Process:
- Curve and Derivatives: Computes the curve points and their first and second derivatives.
- Curvature Calculation: Uses the derivatives to calculate curvature at each point.
- Radius of Curvature: Inversely related to curvature; higher curvature means smaller radius.
- Normal Vectors: Determines the normal direction to the curve at each point.
- Center Calculation: Computes potential centers by moving along the normal direction by the radius of curvature.
- Filtering: Only retains centers within the specified
threshold distance from the curve.
Curvature Calculation
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
- Purpose: Directly computes the curvature of the Bézier curve.
- Parameter:
points: Control points of the Bézier curve.
n_points: Number of points along the curve to compute.
Plotting Bézier Curves
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 == True:
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 == True:
plt.plot(centers[:, 0], centers[:, 1], 'x', label='Osculating Circle Centers', color=color) # Osculating circle centers
#plt.legend()
if(show_centres == True):
plt.title('Bezier Curves with Osculating Circle Centres')
else:
plt.title('Bezier Curves')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid()
plt.show()
Initial Plotting
plot_bezier_curves(extract_bezier_curves(file_path)[0], extract_bezier_curves(file_path)[1], size = 5)
plot_bezier_curves(extract_bezier_curves(file_path)[0], extract_bezier_curves(file_path)[1], show_centres=True, threshold=100, size = 5)
- Purpose:
- First Plot: Displays the extracted cubic and quadratic Bézier curves.
- Second Plot: Displays the same curves along with their osculating circle centers, using a larger threshold (
100).
Clustering Endpoints to Remove Duplicates
cubic_beziers = extract_bezier_curves(file_path)[0]
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):]
- Purpose:
- Clustering: Groups similar start and end points of cubic Bézier curves to eliminate duplicates or minor variations.
- Approach:
- Extract Endpoints: Separates the start and end points of all cubic Bézier curves.
- Combine Points: Stacks all start and end points into a single array.
- DBSCAN Clustering: Applies DBSCAN to cluster points within the specified
tolerance (eps=0.5). Points not belonging to any cluster are labeled -1 (noise).
- Centroid Calculation: For each cluster (excluding noise), computes the centroid and reassigns all points in the cluster to this centroid, effectively merging nearby points.
- Update Bézier Curves: Updates the start and end points of the cubic Béziers with these centroids to ensure consistency.
Removing Duplicate Curves
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)
- Purpose: Eliminates duplicate Bézier curves based on their start and end points.
- Process:
- Initialization: Creates a list for unique curves and a set to track seen endpoints.
- Iteration: For each curve, checks if its start and end points (in both possible orders) have been seen before.
- Addition: If not, adds the curve to the unique list and marks its endpoints as seen.
- Conversion: Returns the unique curves as a NumPy array.
Calculating Tangent Slopes at Endpoints
Bézier Tangent Equations
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 Dictionary Construction
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)
- Purpose:
- Initialization: Sets up a dictionary (
slope_dict) where keys are rounded start and end points of curves, and values are lists of slopes at those points.
- Population: Iterates through each cubic Bézier curve, computes the tangent slopes at start and end, and appends these slopes to the corresponding points in the dictionary.
Filtering Similar Slopes
Almost Equal Slopes
def almost_equal(a, b, threshold):
a_rad = math.atan(a)
b_rad = math.atan(b)
return abs(a_rad - b_rad) <= math.radians(threshold)
Removing Almost Equal Elements
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]]
Note: The function uses a fixed threshold of 5 degrees inside almost_equal, irrespective of the epsilon parameter. This might be an oversight.
Applying Slope Filtering
for point in slope_dict:
slope_dict[point] = remove_almost_equal_elements(slope_dict[point], 0.1)
- Purpose: For each point in
slope_dict, removes slopes that are almost equal, ensuring that only distinct slopes remain.
- Process: Iterates through each point's slope list and applies the
remove_almost_equal_elements function.
Identifying Corner Points
corner_points = {}
for point in slope_dict:
if len(slope_dict[point]) == 1:
corner_points[point] = slope_dict[point][0]
- Purpose: Identifies "corner points" where only one distinct slope remains after filtering.
- Interpretation: Points with a single unique slope likely indicate smooth transitions, whereas points with multiple slopes might indicate corners or intersections.
Preparing Bézier Curves for Further Processing
bezier_curves = np.round(cubic_beziers, decimals=3)
- Purpose: Rounds the coordinates of cubic Bézier curves to three decimal places for consistency and to facilitate comparison.
Helper Function to Check Curves
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
Angle Between Slopes
def angle_between_slopes(slope1, slope2):
angle = math.atan(abs((slope2 - slope1) / (1 + slope1 * slope2)))
return math.degrees(angle)
Distance Between Points
def distance_between_points(p1, p2):
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
- Purpose: Computes the Euclidean distance between two points.
- Parameters:
p1, p2: Tuples representing (x, y) coordinates.
Pairing Corner Points
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]))
- Purpose:
- Pairing: Forms all possible pairs of corner points.
- Filtering: Excludes pairs that belong to the same Bézier curve.
- Computing Metrics: For each valid pair, calculates the angle between their slopes and the distance between the points.
- Sorting: Orders pairs primarily by distance and secondarily by angle.
Selecting Top Pairs Without Overlapping Points
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
- Purpose:
- Selection: Chooses the top four closest pairs of corner points without overlapping (i.e., no point is used in more than one pair).
- Reasoning: Ensures that each selected pair is distinct and likely represents distinct corners or intersections in the SVG.
Creating Filler Bézier Curves
Intersection Finder
def find_intersection(x1, y1, m1, x2, y2, m2):
if m1 == m2:
raise ValueError("Lines are parallel.")
x_intersect = (m1 * x1 - m2 * x2 + y2 - y1) / (m1 - m2)
y_intersect = m1 * (x_intersect - x1) + y1
return x_intersect, y_intersect
Filler Curve Creation
def make_filler_curve(x1, y1, m1, x2, y2, m2):
x_int, y_int = find_intersection(x1, y1, m1, x2, y2, m2)
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)]
Generating Filler Curves
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)))
- Purpose:
- Filler Generation: Creates new Bézier curves for each selected pair of corner points.
- Combining Curves: Merges the original cubic Bézier curves with the newly created filler curves to form the final set of curves.
Final Plotting
plot_bezier_curves(final_curves, [])
- Purpose: Visualizes the combined set of original and filler Bézier curves, effectively showing the enhanced or modified SVG path.
3. Summary of Workflow
-
Data Extraction:
- Load and parse the SVG file.
- Extract cubic and quadratic Bézier curves.
-
Preprocessing:
- Compute curve points and derivatives.
- Calculate curvature and osculating circles.
- Plot initial curves with optional osculating centers.
-
Endpoint Clustering:
- Cluster start and end points of cubic Béziers to identify and merge duplicates.
- Update Bézier curves with clustered (merged) endpoints.
-
Curve Deduplication:
- Remove duplicate curves based on unique start and end points.
-
Slope Analysis:
- Calculate tangent slopes at each curve's endpoints.
- Filter out similar slopes to identify distinct directional changes.
-
Corner Detection:
- Identify points where only one distinct slope exists, likely indicating corners or junctions.
-
Corner Pairing and Filler Generation:
- Pair nearby corner points that are not on the same curve.
- Generate new Bézier curves (fillers) to bridge these corners smoothly.
-
Final Visualization:
- Plot the original and filler Bézier curves to visualize the enhancements.
4. Practical Applications
This script can be particularly useful in scenarios such as:
- SVG Optimization: Simplifying or refining SVG paths by removing duplicates and smoothing transitions.
- Graphic Design: Automatically enhancing vector graphics by filling gaps or smoothing corners.
- Computer Graphics Research: Studying the properties of vector paths, such as curvature and continuity.
- Path Editing Tools: Providing automated assistance in graphic design software for path manipulation.
5. Potential Enhancements
While the script is comprehensive, there are areas where it could be improved or extended:
- Quadratic Bézier Handling: Currently, filler curves are only generated for cubic Béziers. Extending this to handle quadratic Béziers could make the script more versatile.
- Threshold Parameterization: The
remove_almost_equal_elements function uses a fixed threshold inside almost_equal, which might be better parameterized.
- Error Handling: Incorporating more robust error handling, especially for cases like parallel lines where intersections aren't possible.
- Performance Optimizations: For very large SVG files, optimizing loops and computations could enhance performance.
- User Interface: Adding parameters or a GUI could make the script more user-friendly and customizable.
6. Conclusion
This Python script provides a robust framework for extracting, analyzing, and enhancing Bézier curves from SVG files. By leveraging mathematical concepts like curvature and tangent slopes, combined with clustering techniques, it effectively identifies and smooths corners or intersections within vector graphics. The resulting visualizations offer clear insights into the structure and modifications applied to the original SVG paths.