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, [])
i want to convert this into cpp but only till
this function
plot_bezier_curves(extract_bezier_curves(file_path)[0], extract_bezier_curves(file_path)[1], show_centres=True, threshold=100, size = 5)
i converted the full script in cpp here's it
please just do the initial plotting
#include
#include
#include
#include
#include
#include
#include <unordered_set>
#include
#include
#include
#include
#include
// TinyXML2 for SVG parsing
#include "tinyxml2.h"
// Eigen for matrix and vector operations
#include <Eigen/Dense>
// mlpack for DBSCAN
#include <mlpack/core.hpp>
#include <mlpack/methods/dbscan/dbscan.hpp>
using namespace std;
using namespace Eigen;
using namespace tinyxml2;
using namespace mlpack;
// Structure to hold a point
struct Point {
double x;
double y;
// Function to compute binomial coefficients
double binomial_coefficient(int n, int k) {
if (k > n - k)
k = n - k;
double res = 1;
for(int i = 0; i < k; ++i){
res *= (n - i);
res /= (i + 1);
}
return res;
}
// Bernstein Polynomial
double bernstein_poly(int i, int n, double t){
return binomial_coefficient(n, i) * pow(t, n-i) * pow(1 - t, i);
}
// Function to evaluate a Cubic Bezier curve
vector evaluate_cubic_bezier(const vector& points, int n_points=100){
vector curve;
int n = 3; // Cubic
for(int step=0; step <= n_points; ++step){
double t = static_cast(step) / n_points;
double x = 0.0, y = 0.0;
for(int i=0; i<=n; ++i){
double bp = bernstein_poly(i, n, t);
x += bp * points[i].x;
y += bp * points[i].y;
}
curve.emplace_back(Point{ x, y });
}
return curve;
}
// Function to evaluate a Quadratic Bezier curve
vector evaluate_quadratic_bezier(const vector& points, int n_points=100){
vector curve;
int n = 2; // Quadratic
for(int step=0; step <= n_points; ++step){
double t = static_cast(step) / n_points;
double x = 0.0, y = 0.0;
for(int i=0; i<=n; ++i){
double bp = bernstein_poly(i, n, t);
x += bp * points[i].x;
y += bp * points[i].y;
}
curve.emplace_back(Point{ x, y });
}
return curve;
}
// Function to compute first and second derivatives for Cubic Bezier
tuple<vector, vector> compute_cubic_derivatives(const vector& points, int n_points=100){
vector first_derivative;
vector second_derivative;
int n = 3; // Cubic
// First derivative
for(int step=0; step <= n_points; ++step){
double t = static_cast<double>(step) / n_points;
double dx = 0.0, dy = 0.0;
for(int i=0; i < n; ++i){
double bp = bernstein_poly(i, n-1, t);
dx += bp * n * (points[i+1].x - points[i].x);
dy += bp * n * (points[i+1].y - points[i].y);
}
first_derivative.emplace_back(Point{ dx, dy });
}
// Second derivative
for(int step=0; step <= n_points; ++step){
double t = static_cast<double>(step) / n_points;
double d2x = 0.0, d2y = 0.0;
for(int i=0; i < n-1; ++i){
double bp = bernstein_poly(i, n-2, t);
d2x += bp * n * (n-1) * (points[i+2].x - 2*points[i+1].x + points[i].x);
d2y += bp * n * (n-1) * (points[i+2].y - 2*points[i+1].y + points[i].y);
}
second_derivative.emplace_back(Point{ d2x, d2y });
}
return make_tuple(first_derivative, second_derivative);
// Function to parse SVG and extract cubic and quadratic beziers
pair<vector<vector>, vector<vector>> extract_bezier_curves(const string& svg_file){
XMLDocument doc;
XMLError eResult = doc.LoadFile(svg_file.c_str());
if(eResult != XML_SUCCESS){
cout << "Error loading SVG file: " << svg_file << endl;
exit(1);
}
XMLElement* root = doc.FirstChildElement("svg");
if(root == nullptr){
cout << "No <svg> element found!" << endl;
exit(1);
}
vector<vector<Point>> cubic_bezier_curves;
vector<vector<Point>> quadratic_bezier_curves;
// Recursive function to find all <path> elements
function<void(XMLElement*)> find_paths = [&](XMLElement* element) {
for(XMLElement* child = element->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()){
if(strcmp(child->Name(), "path") == 0){
const char* d = child->Attribute("d");
if(d == nullptr){
continue;
}
string path_data(d);
cout << "Parsing path: " << path_data << endl; // Debugging Output
char current_command = '\0';
double x = 0.0, y = 0.0;
double start_x = 0.0, start_y = 0.0; // For 'Z'/'z'
size_t i = 0;
while(i < path_data.length()){
if(isalpha(path_data[i])){
current_command = path_data[i];
i++;
}
else{
// Parse numbers
vector<double> nums;
while(i < path_data.length() && (isdigit(path_data[i]) || path_data[i]=='.' || path_data[i]=='-' || path_data[i]==',' || isspace(path_data[i]))){
if(path_data[i] == ',' || isspace(path_data[i])){
i++;
continue;
}
size_t start_num = i;
// Handle negative numbers and decimal points
if(path_data[i] == '-'){
i++;
}
while(i < path_data.length() && (isdigit(path_data[i]) || path_data[i]=='.')){
i++;
}
string num_str = path_data.substr(start_num, i - start_num);
try{
double num = stod(num_str);
nums.push_back(num);
}
catch(...){
break;
}
}
switch(current_command){
case 'M':
case 'm':{
for(size_t j = 0; j + 1 < nums.size(); j += 2){
if(current_command == 'm'){
x += nums[j];
y += nums[j+1];
}
else{
x = nums[j];
y = nums[j+1];
}
start_x = x;
start_y = y;
// Subsequent coord pairs after 'M'/'m' are treated as 'L'/'l'
}
break;
}
case 'C':
case 'c':{
bool is_relative = (current_command == 'c');
for(size_t j = 0; j + 5 < nums.size(); j += 6){
vector<Point> bezier;
bezier.emplace_back(Point{ x, y });
double ctrl1_x = is_relative ? x + nums[j] : nums[j];
double ctrl1_y = is_relative ? y + nums[j+1] : nums[j+1];
double ctrl2_x = is_relative ? x + nums[j+2] : nums[j+2];
double ctrl2_y = is_relative ? y + nums[j+3] : nums[j+3];
double end_x = is_relative ? x + nums[j+4] : nums[j+4];
double end_y = is_relative ? y + nums[j+5] : nums[j+5];
bezier.emplace_back(Point{ ctrl1_x, ctrl1_y });
bezier.emplace_back(Point{ ctrl2_x, ctrl2_y });
bezier.emplace_back(Point{ end_x, end_y });
cubic_bezier_curves.emplace_back(bezier);
x = end_x;
y = end_y;
}
break;
}
case 'Q':
case 'q':{
bool is_relative = (current_command == 'q');
for(size_t j = 0; j + 3 < nums.size(); j += 4){
vector<Point> bezier;
bezier.emplace_back(Point{ x, y });
double ctrl_x = is_relative ? x + nums[j] : nums[j];
double ctrl_y = is_relative ? y + nums[j+1] : nums[j+1];
double end_x = is_relative ? x + nums[j+2] : nums[j+2];
double end_y = is_relative ? y + nums[j+3] : nums[j+3];
bezier.emplace_back(Point{ ctrl_x, ctrl_y });
bezier.emplace_back(Point{ end_x, end_y });
quadratic_bezier_curves.emplace_back(bezier);
x = end_x;
y = end_y;
}
break;
}
case 'Z':
case 'z':{
x = start_x;
y = start_y;
break;
}
// Handle other commands like 'L', 'l' if necessary
default:
// For unsupported commands, skip
break;
}
}
}
}
else{
// Recursive call for nested elements
find_paths(child);
}
}
};
// Start recursion from root
find_paths(root);
return make_pair(cubic_bezier_curves, quadratic_bezier_curves);
}
// Function to compute tangent slopes at start and end points of cubic beziers
map<string, vector> compute_tangent_slopes(const vector<vector>& cubic_beziers){
map<string, vector> slope_dict;
string file_path = argv[1];
// 1. Extract Bezier Curves from SVG
auto bezier_curves = extract_bezier_curves(file_path);
vector<vector<Point>> cubic_beziers = bezier_curves.first;
vector<vector<Point>> quadratic_beziers = bezier_curves.second;
cout << "Extracted " << cubic_beziers.size() << " cubic beziers and " << quadratic_beziers.size() << " quadratic beziers." << endl;
if(cubic_beziers.empty() && quadratic_beziers.empty()){
cout << "No Bézier curves found in the SVG." << endl;
return 1;
}
// 2. Flat Lists for Clustering
vector<Point> startpoints, endpoints;
for(const auto& bezier : cubic_beziers){
startpoints.emplace_back(bezier[0]);
endpoints.emplace_back(bezier[3]);
}
// Combine all points
vector<Point> all_points;
all_points.reserve(startpoints.size() + endpoints.size());
all_points.insert(all_points.end(), startpoints.begin(), startpoints.end());
all_points.insert(all_points.end(), endpoints.begin(), endpoints.end());
// 3. Prepare Data for mlpack DBSCAN
arma::mat data(2, all_points.size());
for (size_t i = 0; i < all_points.size(); ++i) {
data(0, i) = all_points[i].x;
data(1, i) = all_points[i].y;
}
// 4. Perform DBSCAN Clustering (Use the data created above)
double eps = 5.0; // Adjust based on your SVG scale
int minPts = 2;
// Correct usage of KDTree and DefaultPointSelection
using KDTree = mlpack::KDTree<mlpack::EuclideanDistance>; // Define the KDTree alias inside main
auto dbs = DBSCAN<KDTree, mlpack::tree::DefaultPointSelection<arma::Row<size_t>>>(eps, minPts); // Create DBSCAN instance
arma::Row<size_t> assignments;
dbs.Cluster(data, assignments);
// 5. Replace Points in Clusters with Centroids
map<size_t, vector<Point>> clusters;
for (size_t i = 0; i < assignments.n_elem; ++i) {
if (assignments[i] == -1) { // Check for noise label -1
continue;
}
clusters[assignments[i]].emplace_back(all_points[i]);
}
// Compute centroids
for(auto& [cluster_id, points] : clusters){
double sum_x = 0.0, sum_y = 0.0;
for(const auto& p : points){
sum_x += p.x;
sum_y += p.y;
}
double centroid_x = sum_x / points.size();
double centroid_y = sum_y / points.size();
for(auto& p : clusters[cluster_id]){
p.x = centroid_x;
p.y = centroid_y;
}
}
// Update startpoints and endpoints with clustered points
for (int i = 0; i < startpoints.size(); ++i) {
if (assignments[i] != -1) {
if (clusters.find(assignments[i]) != clusters.end()) {
startpoints[i] = clusters[assignments[i]][0];
}
}
}
// Update endpoints with clustered points
for (int i = 0; i < endpoints.size(); ++i) {
// Calculate the index in assignments for the endpoint
size_t endpoint_index = i + startpoints.size();
if (assignments[endpoint_index] != -1) {
if (clusters.find(assignments[endpoint_index]) != clusters.end()) {
endpoints[i] = clusters[assignments[endpoint_index]][0];
}
}
}
// Update cubic_beziers with clustered points
for(int i=0; i < cubic_beziers.size(); ++i){
cubic_beziers[i][0] = startpoints[i];
cubic_beziers[i][3] = endpoints[i];
}
// 6. Remove Duplicate Curves
// Function to get unique curves based on start and end points
auto get_unique_curves = [](const vector<vector<Point>>& curves) -> vector<vector<Point>>{
vector<vector<Point>> unique_curves;
unordered_set<string> seen_endpoints;
// Helper lambda to convert point to string
auto point_to_string = [](const Point& p) -> string{
stringstream ss;
ss << fixed << setprecision(4) << p.x << "," << p.y;
return ss.str();
};
for(const auto& curve : curves){
string start = point_to_string(curve[0]);
string end = point_to_string(curve[3]);
string key1 = start + "-" + end;
string key2 = end + "-" + start;
if(seen_endpoints.find(key1) == seen_endpoints.end() && seen_endpoints.find(key2) == seen_endpoints.end()){
unique_curves.push_back(curve);
seen_endpoints.insert(key1);
}
}
return unique_curves;
};
cubic_beziers = get_unique_curves(cubic_beziers);
cout << "After removing duplicates, " << cubic_beziers.size() << " cubic beziers remain." << endl;
if(cubic_beziers.empty()){
cout << "No unique cubic Bézier curves found after removing duplicates." << endl;
return 1;
}
// 7. Compute Tangent Slopes
map<string, vector<double>> slope_dict = compute_tangent_slopes(cubic_beziers);
// 8. Identify Corner Points
map<string, double> corner_points = identify_corners(slope_dict);
cout << "Identified " << corner_points.size() << " corner points." << endl;
if(corner_points.empty()){
cout << "No corner points identified." << endl;
}
// 9. Pair Corner Points
vector<tuple<string, string, double, double>> pairs; // p1, p2, angle, distance
for(auto it1 = corner_points.begin(); it1 != corner_points.end(); ++it1){
for(auto it2 = next(it1); it2 != corner_points.end(); ++it2){
string p1 = it1->first;
string p2 = it2->first;
// Check if on same bezier curve
if(on_same_bezier_curve(p1, p2, cubic_beziers)){
continue;
}
// Compute angle
double angle = 0.0;
if(isinf(it1->second) && isinf(it2->second)){
angle = 0.0;
}
else if(isinf(it1->second) || isinf(it2->second)){
angle = 90.0;
}
else{
double angle_rad = atan(abs((it2->second - it1->second) / (1 + it1->second * it2->second)));
angle = abs((angle_rad * 180.0) / M_PI);
}
// Compute distance
double distance = 0.0;
double x1_val, y1_val, x2_val, y2_val;
sscanf(p1.c_str(), "%lf,%lf", &x1_val, &y1_val);
sscanf(p2.c_str(), "%lf,%lf", &x2_val, &y2_val);
distance = sqrt(pow(x2_val - x1_val, 2) + pow(y2_val - y1_val, 2));
pairs.emplace_back(make_tuple(p1, p2, angle, distance));
}
}
// Sort pairs by distance and then by angle
sort(pairs.begin(), pairs.end(), [&](const tuple<string, string, double, double>& a, const tuple<string, string, double, double>& b) -> bool{
if(get<3>(a) != get<3>(b))
return get<3>(a) < get<3>(b);
return get<2>(a) < get<2>(b);
});
// Select top 4 non-overlapping pairs
vector<pair<string, string>> result_pairs;
unordered_set<string> used_points;
for(const auto& pair : pairs){
string p1 = get<0>(pair);
string p2 = get<1>(pair);
if(used_points.find(p1) == used_points.end() && used_points.find(p2) == used_points.end()){
result_pairs.emplace_back(make_pair(p1, p2));
used_points.insert(p1);
used_points.insert(p2);
if(result_pairs.size() == 4){
break;
}
}
}
cout << "Selected " << result_pairs.size() << " pairs for filler curves." << endl;
// 10. Generate Filler Curves
vector<vector<Point>> filler_curves;
for(const auto& pair : result_pairs){
// Parse points
double x1, y1, x2, y2;
double m1, m2;
sscanf(pair.first.c_str(), "%lf,%lf", &x1, &y1);
sscanf(pair.second.c_str(), "%lf,%lf", &x2, &y2);
m1 = corner_points[pair.first];
m2 = corner_points[pair.second];
// Create filler curve
vector<Point> filler = make_filler_curve(x1, y1, m1, x2, y2, m2);
filler_curves.emplace_back(filler);
}
// 11. Combine All Curves
vector<vector<Point>> final_curves = cubic_beziers;
final_curves.insert(final_curves.end(), filler_curves.begin(), filler_curves.end());
// 12. Write Curves to File for Plotting
write_curves_to_file(final_curves, quadratic_beziers, filler_curves, "processed_curves.dat");
cout << "Curves written to processed_curves.dat for plotting." << endl;
// Inform the user to use GNUplot for visualization
cout << "To visualize the curves, you can use GNUplot with the following commands:" << endl;
cout << "gnuplot> set title 'Processed Bézier Curves'" << endl;
cout << "gnuplot> set xlabel 'X'" << endl;
cout << "gnuplot> set ylabel 'Y'" << endl;
cout << "gnuplot> plot 'processed_curves.dat' with lines title 'Bézier Curves'" << endl;
return 0;
}
Translating Python's matplotlib-based plotting functionality to C++ requires leveraging external libraries, as C++ does not have built-in plotting capabilities. Below, I'll guide you through two primary approaches to achieve the initial plotting of Bézier curves in C++:
Using matplotlib-cpp: A C++ wrapper for Python's matplotlib.
Using GNUplot: Writing curve data to a file and plotting it externally with GNUplot.
I'll provide detailed instructions and sample code for both methods. You can choose the one that best fits your workflow and environment.
1. Using matplotlib-cpp
matplotlib-cpp is a lightweight C++ wrapper for Python's matplotlib. It allows you to leverage the powerful plotting capabilities of matplotlib directly from C++.
Step-by-Step Guide
a. Prerequisites
Install Python with matplotlib:
Ensure you have Python installed on your system along with the matplotlib library.
pip install matplotlib
Install Boost.Python:matplotlib-cpp relies on Boost.Python to interface with Python. Install Boost with Python support.
Ubuntu/Debian:
sudo apt-get install libboost-all-dev
macOS (using Homebrew):
brew install boost-python3
Windows:
You can download Boost from Boost Downloads and follow the installation instructions.
Download matplotlib-cpp:
Clone the repository or download the matplotlibcpp.h header file directly.
Assuming you have the matplotlibcpp.h file in your project directory, modify your C++ code to include and use it.
c. Sample C++ Code with matplotlib-cpp
Below is a modified version of your C++ code that includes initial plotting of the Bézier curves using matplotlib-cpp. This example focuses on extracting the Bézier curves and plotting them without proceeding to further processing steps.
#include <iostream>
#include <vector>
#include <cmath>
#include <tuple>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <map>
#include <functional>
// TinyXML2 for SVG parsing
#include "tinyxml2.h"
// Eigen for matrix and vector operations
#include <Eigen/Dense>
// Include matplotlib-cpp
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
using namespace std;
using namespace Eigen;
using namespace tinyxml2;
// Structure to hold a point
struct Point {
double x;
double y;
bool operator<(const Point& other) const {
return tie(x, y) < tie(other.x, other.y);
}
bool operator==(const Point& other) const {
return abs(x - other.x) < 1e-6 && abs(y - other.y) < 1e-6;
}
};
// Function to compute binomial coefficients
double binomial_coefficient(int n, int k) {
if (k > n - k)
k = n - k;
double res = 1;
for(int i = 0; i < k; ++i){
res *= (n - i);
res /= (i + 1);
}
return res;
}
// Bernstein Polynomial
double bernstein_poly(int i, int n, double t){
return binomial_coefficient(n, i) * pow(t, n-i) * pow(1 - t, i);
}
// Function to evaluate a Cubic Bezier curve
vector<Point> evaluate_cubic_bezier(const vector<Point>& points, int n_points=100){
vector<Point> curve;
int n = 3; // Cubic
for(int step=0; step <= n_points; ++step){
double t = static_cast<double>(step) / n_points;
double x = 0.0, y = 0.0;
for(int i=0; i<=n; ++i){
double bp = bernstein_poly(i, n, t);
x += bp * points[i].x;
y += bp * points[i].y;
}
curve.emplace_back(Point{ x, y });
}
return curve;
}
// Function to evaluate a Quadratic Bezier curve
vector<Point> evaluate_quadratic_bezier(const vector<Point>& points, int n_points=100){
vector<Point> curve;
int n = 2; // Quadratic
for(int step=0; step <= n_points; ++step){
double t = static_cast<double>(step) / n_points;
double x = 0.0, y = 0.0;
for(int i=0; i<=n; ++i){
double bp = bernstein_poly(i, n, t);
x += bp * points[i].x;
y += bp * points[i].y;
}
curve.emplace_back(Point{ x, y });
}
return curve;
}
// Function to compute first and second derivatives for Cubic Bezier
tuple<vector<Point>, vector<Point>> compute_cubic_derivatives(const vector<Point>& points, int n_points=100){
vector<Point> first_derivative;
vector<Point> second_derivative;
int n = 3; // Cubic
// First derivative
for(int step=0; step <= n_points; ++step){
double t = static_cast<double>(step) / n_points;
double dx = 0.0, dy = 0.0;
for(int i=0; i < n; ++i){
double bp = bernstein_poly(i, n-1, t);
dx += bp * n * (points[i+1].x - points[i].x);
dy += bp * n * (points[i+1].y - points[i].y);
}
first_derivative.emplace_back(Point{ dx, dy });
}
// Second derivative
for(int step=0; step <= n_points; ++step){
double t = static_cast<double>(step) / n_points;
double d2x = 0.0, d2y = 0.0;
for(int i=0; i < n-1; ++i){
double bp = bernstein_poly(i, n-2, t);
d2x += bp * n * (n-1) * (points[i+2].x - 2*points[i+1].x + points[i].x);
d2y += bp * n * (n-1) * (points[i+2].y - 2*points[i+1].y + points[i].y);
}
second_derivative.emplace_back(Point{ d2x, d2y });
}
return make_tuple(first_derivative, second_derivative);
}
// Function to compute curvature
vector<double> compute_curvature(const vector<Point>& first_derivative, const vector<Point>& second_derivative){
int n = first_derivative.size();
vector<double> curvature(n, 0.0);
for(int i=0; i<n; ++i){
double dx = first_derivative[i].x;
double dy = first_derivative[i].y;
double ddx = second_derivative[i].x;
double ddy = second_derivative[i].y;
double numerator = dx * ddy - dy * ddx;
double denominator = pow(dx*dx + dy*dy, 1.5);
if(denominator != 0){
curvature[i] = numerator / denominator;
}
else{
curvature[i] = 0.0;
}
}
return curvature;
}
// Function to parse SVG and extract cubic and quadratic beziers
pair<vector<vector<Point>>, vector<vector<Point>>> extract_bezier_curves(const string& svg_file){
XMLDocument doc;
XMLError eResult = doc.LoadFile(svg_file.c_str());
if(eResult != XML_SUCCESS){
cout << "Error loading SVG file: " << svg_file << endl;
exit(1);
}
XMLElement* root = doc.FirstChildElement("svg");
if(root == nullptr){
cout << "No <svg> element found!" << endl;
exit(1);
}
vector<vector<Point>> cubic_bezier_curves;
vector<vector<Point>> quadratic_bezier_curves;
// Recursive function to find all <path> elements
function<void(XMLElement*)> find_paths = [&](XMLElement* element) {
for(XMLElement* child = element->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()){
if(strcmp(child->Name(), "path") == 0){
const char* d = child->Attribute("d");
if(d == nullptr){
continue;
}
string path_data(d);
cout << "Parsing path: " << path_data << endl; // Debugging Output
char current_command = '\0';
double x = 0.0, y = 0.0;
double start_x = 0.0, start_y = 0.0; // For 'Z'/'z'
size_t i = 0;
while(i < path_data.length()){
if(isalpha(path_data[i])){
current_command = path_data[i];
i++;
}
else{
// Parse numbers
vector<double> nums;
while(i < path_data.length() && (isdigit(path_data[i]) || path_data[i]=='.' || path_data[i]=='-' || path_data[i]==',' || isspace(path_data[i]))){
if(path_data[i] == ',' || isspace(path_data[i])){
i++;
continue;
}
size_t start_num = i;
// Handle negative numbers and decimal points
if(path_data[i] == '-'){
i++;
}
while(i < path_data.length() && (isdigit(path_data[i]) || path_data[i]=='.')){
i++;
}
string num_str = path_data.substr(start_num, i - start_num);
try{
double num = stod(num_str);
nums.push_back(num);
}
catch(...){
break;
}
}
switch(current_command){
case 'M':
case 'm':{
for(size_t j = 0; j + 1 < nums.size(); j += 2){
if(current_command == 'm'){
x += nums[j];
y += nums[j+1];
}
else{
x = nums[j];
y = nums[j+1];
}
start_x = x;
start_y = y;
// Subsequent coord pairs after 'M'/'m' are treated as 'L'/'l'
}
break;
}
case 'C':
case 'c':{
bool is_relative = (current_command == 'c');
for(size_t j = 0; j + 5 < nums.size(); j += 6){
vector<Point> bezier;
bezier.emplace_back(Point{ x, y });
double ctrl1_x = is_relative ? x + nums[j] : nums[j];
double ctrl1_y = is_relative ? y + nums[j+1] : nums[j+1];
double ctrl2_x = is_relative ? x + nums[j+2] : nums[j+2];
double ctrl2_y = is_relative ? y + nums[j+3] : nums[j+3];
double end_x = is_relative ? x + nums[j+4] : nums[j+4];
double end_y = is_relative ? y + nums[j+5] : nums[j+5];
bezier.emplace_back(Point{ ctrl1_x, ctrl1_y });
bezier.emplace_back(Point{ ctrl2_x, ctrl2_y });
bezier.emplace_back(Point{ end_x, end_y });
cubic_bezier_curves.emplace_back(bezier);
x = end_x;
y = end_y;
}
break;
}
case 'Q':
case 'q':{
bool is_relative = (current_command == 'q');
for(size_t j = 0; j + 3 < nums.size(); j += 4){
vector<Point> bezier;
bezier.emplace_back(Point{ x, y });
double ctrl_x = is_relative ? x + nums[j] : nums[j];
double ctrl_y = is_relative ? y + nums[j+1] : nums[j+1];
double end_x = is_relative ? x + nums[j+2] : nums[j+2];
double end_y = is_relative ? y + nums[j+3] : nums[j+3];
bezier.emplace_back(Point{ ctrl_x, ctrl_y });
bezier.emplace_back(Point{ end_x, end_y });
quadratic_bezier_curves.emplace_back(bezier);
x = end_x;
y = end_y;
}
break;
}
case 'Z':
case 'z':{
x = start_x;
y = start_y;
break;
}
// Handle other commands like 'L', 'l' if necessary
default:
// For unsupported commands, skip
break;
}
}
}
}
else{
// Recursive call for nested elements
find_paths(child);
}
}
};
// Start recursion from root
find_paths(root);
return make_pair(cubic_bezier_curves, quadratic_bezier_curves);
}
// Function to plot Bezier curves using matplotlib-cpp
void plot_bezier_curves(const vector<vector<Point>>& cubic_curves, const vector<vector<Point>>& quadratic_curves, bool show_centres = false, double threshold = 1.0, double size = 10.0){
plt::figure_size(static_cast<int>(size*100), static_cast<int>(size*100));
// Plot cubic Bezier curves
for(const auto& bezier : cubic_curves){
vector<double> x, y;
for(const auto& p : bezier){
x.push_back(p.x);
y.push_back(p.y);
}
plt::plot(x, y, "r-"); // Red solid line for cubic
// Optionally, plot control points
// plt::plot(x, y, "ro--");
}
// Plot quadratic Bezier curves
for(const auto& bezier : quadratic_curves){
vector<double> x, y;
for(const auto& p : bezier){
x.push_back(p.x);
y.push_back(p.y);
}
plt::plot(x, y, "b-"); // Blue solid line for quadratic
// Optionally, plot control points
// plt::plot(x, y, "bo--");
}
// Titles and labels
if(show_centres){
plt::title("Bezier Curves with Osculating Circle Centres");
}
else{
plt::title("Bezier Curves");
}
plt::xlabel("X");
plt::ylabel("Y");
plt::grid(true);
plt::show();
}
int main(int argc, char* argv[]){
if(argc < 2){
cout << "Usage: " << argv[0] << " <svg_file>" << endl;
return 1;
}
string file_path = argv[1];
// 1. Extract Bezier Curves from SVG
auto bezier_curves = extract_bezier_curves(file_path);
vector<vector<Point>> cubic_beziers = bezier_curves.first;
vector<vector<Point>> quadratic_beziers = bezier_curves.second;
cout << "Extracted " << cubic_beziers.size() << " cubic beziers and " << quadratic_beziers.size() << " quadratic beziers." << endl;
if(cubic_beziers.empty() && quadratic_beziers.empty()){
cout << "No Bézier curves found in the SVG." << endl;
return 1;
}
// 2. Plot Bezier Curves
plot_bezier_curves(cubic_beziers, quadratic_beziers, false, 1.0, 10.0);
// If you want to show centres, you'll need to compute them as in the Python script
// For initial plotting, we are focusing on plotting the curves only
return 0;
}
d. Compile and Run
Save the Code:
Save the above code to a file, e.g., plot_bezier.cpp.
Ensure Header Files are Accessible:
Place matplotlibcpp.h in the same directory or adjust the include path accordingly.
Ensure tinyxml2.h and Eigen headers are installed and accessible.
Compile the Code:
Use g++ with appropriate flags. Here's an example command:
Adjust the Python include and library paths (/usr/include/python3.8 and -lpython3.8) based on your Python installation.
Ensure that Boost.Python and TinyXML2 are correctly linked (-lboost_python38 and -ltinyxml2). The exact library names may vary based on your installation and version.
Run the Executable:
./plot_bezier your_svg_file.svg
Replace your_svg_file.svg with the path to your SVG file containing Bézier curves.
e. Handling Osculating Circle Centres (Optional)
If you wish to replicate the second plotting call from Python that includes show_centres=True, you'll need to compute the osculating circle centers. This involves calculating the curvature and normal vectors, similar to your Python script. Implementing this in C++ would require additional functions for:
Calculating derivatives.
Computing curvature.
Determining normal vectors and circle centers.
Clustering centers (optional) to avoid overplotting.
Due to the complexity, it's recommended to first ensure that the basic plotting works before extending it to include osculating centers.
2. Using GNUplot
If integrating matplotlib-cpp seems cumbersome, another straightforward approach is to write the Bézier curve points to a file and use GNUplot to visualize them. This method separates data processing from visualization and is easier to manage.
a. Modify Your C++ Code to Write Curve Data
Enhance your C++ code to write the evaluated Bézier curves to a data file in a format suitable for GNUplot.
// Function to write curves to a data file for GNUplot
void write_curves_to_file(const vector<vector<Point>>& cubic_curves, const vector<vector<Point>>& quadratic_curves, const string& filename){
ofstream file(filename);
if(!file.is_open()){
cout << "Error opening file for writing: " << filename << endl;
return;
}
// Write cubic beziers
for(const auto& bezier : cubic_curves){
for(const auto& p : bezier){
file << p.x << " " << p.y << "\n";
}
file << "\n"; // Separator for GNUplot
}
// Write quadratic beziers
for(const auto& bezier : quadratic_curves){
for(const auto& p : bezier){
file << p.x << " " << p.y << "\n";
}
file << "\n"; // Separator for GNUplot
}
file.close();
}
b. Update the main Function
After extracting the Bézier curves, write them to a file before plotting.
int main(int argc, char* argv[]){
if(argc < 2){
cout << "Usage: " << argv[0] << " <svg_file>" << endl;
return 1;
}
string file_path = argv[1];
// 1. Extract Bezier Curves from SVG
auto bezier_curves = extract_bezier_curves(file_path);
vector<vector<Point>> cubic_beziers = bezier_curves.first;
vector<vector<Point>> quadratic_beziers = bezier_curves.second;
cout << "Extracted " << cubic_beziers.size() << " cubic beziers and " << quadratic_beziers.size() << " quadratic beziers." << endl;
if(cubic_beziers.empty() && quadratic_beziers.empty()){
cout << "No Bézier curves found in the SVG." << endl;
return 1;
}
// 2. Write Curves to File
string data_file = "bezier_curves.dat";
write_curves_to_file(cubic_beziers, quadratic_beziers, data_file);
cout << "Bezier curves written to " << data_file << endl;
// Optionally, you can automatically invoke GNUplot (requires GNUplot installed)
// Here's a simple example:
stringgnuplot_script = "set title 'Bezier Curves'\nset xlabel 'X'\nset ylabel 'Y'\nplot ";
int total_curves = cubic_beziers.size() + quadratic_beziers.size();
for(int i = 1; i <= total_curves; ++i){
gnuplot_script += "'" + data_file + "' index " + to_string(i-1) + " with lines";
if(i < total_curves){
gnuplot_script += ", ";
}
}
// Note: For simplicity, this example only writes the data and instructs the user to plot with GNUplot manually.
// Inform the user to use GNUplot for visualization
cout << "To visualize the curves, you can use GNUplot with the following commands:" << endl;
cout << "gnuplot> set title 'Bezier Curves'" << endl;
cout << "gnuplot> set xlabel 'X'" << endl;
cout << "gnuplot> set ylabel 'Y'" << endl;
cout << "gnuplot> plot for [i=0:" << (total_curves-1) << "] '" << data_file << "' index i with lines title 'Bezier " << "'\n" << endl;
return 0;
}
c. Compile and Run
Save the Code:
Save the modified code to plot_bezier_gnuplot.cpp.
Ensure that TinyXML2 and Eigen are correctly linked (-ltinyxml2 and -lEigen3).
Adjust include paths if necessary.
Run the Executable:
./plot_bezier_gnuplot your_svg_file.svg
d. Plot with GNUplot
After running the executable, follow these steps to plot the curves using GNUplot:
Open GNUplot:
gnuplot
Set Titles and Labels:
set title "Bezier Curves"
set xlabel "X"
set ylabel "Y"
Plot the Curves:
Assuming your data file is bezier_curves.dat and contains both cubic and quadratic curves separated by blank lines:
plot "bezier_curves.dat" index 0 with lines title 'Cubic Bezier', \
"bezier_curves.dat" index 1 with lines title 'Quadratic Bezier'
Explanation:
index 0: First Bézier curve block.
index 1: Second Bézier curve block.
Adjust the index accordingly based on the number of curves.
Explore and Customize:
You can customize colors, line styles, and add legends as needed. Refer to GNUplot's documentation for more details.
Conclusion
Plotting Bézier curves in C++ requires interfacing with external libraries or tools since C++ lacks built-in plotting capabilities akin to Python's matplotlib. The two primary methods discussed are:
matplotlib-cpp: Offers a Python-like plotting experience directly within C++. It's powerful but requires setting up dependencies like Boost.Python.
GNUplot: A robust plotting tool that can be easily invoked from C++ by writing data to files. It's straightforward and doesn't require embedding a plotting library within your C++ application.
Choose the method that best aligns with your project's requirements and your familiarity with the tools. If you prefer an integrated C++ solution with interactive plotting, matplotlib-cpp is suitable. However, if you prefer simplicity and external visualization, GNUplot is an excellent choice.
Additional Tips
Error Handling: Ensure your SVG files are well-formed and contain only supported Bézier commands (C, c, Q, q, etc.).
Performance Considerations: For large SVG files with numerous Bézier curves, optimize the curve evaluation and plotting sections to handle the data efficiently.
Extending Functionality: Once the initial plotting works, you can extend the C++ code to include further processing steps like computing curvature, clustering centers, and more, similar to your Python script.
Cross-Platform Compatibility: Ensure that the chosen plotting method (matplotlib-cpp or GNUplot) is compatible with your target operating systems.
Feel free to reach out if you encounter specific issues or need further assistance with any of the steps!