Time complexity of each and every algorithm #include <opencv2/opencv.hpp>
#include
#include
#include
#include
#include
#include
#include
#include
#include
using Point2D = cv::Point2d;
using Path = std::vector;
using Paths = std::vector;
// Class to handle CSV reading and writing
class CSVHandler {
public:
static Paths readCSV(const std::string& csvPath, double& yMaxGlobal);
static void writeCSV(const Paths& paths, const std::string& csvPath);
};
// Class to represent and process shapes
class Shape {
public:
Path points;
Path regularizedPoints;
std::string shapeType;
std::vector<std::pair<Point2D, Point2D>> symmetryLines;
Analyzing the time complexity of each component in your C++ program helps in understanding its scalability and performance characteristics. Below is a detailed breakdown of the time complexities for each class and their respective methods within your code. The analysis assumes that n represents the number of points in a single path (i.e., Path), and m represents the number of paths (Paths).
1. CSVHandler Class
a. readCSV(const std::string& csvPath, double& yMaxGlobal)
Purpose: Reads a CSV file containing multiple paths, parses the points, and stores them in a structured format.
Time Complexity:O(m * k)
m: Number of paths.
k: Average number of points per path.
Explanation:
File Reading: The method reads the file line by line, which is linear with respect to the number of lines L in the CSV.
Parsing: Each line is parsed, and points are added to a map structure. Assuming each line corresponds to a point, and there are m * k = L points in total, the overall complexity is O(L) = O(m * k).
b. writeCSV(const Paths& paths, const std::string& csvPath)
Purpose: Writes the regularized paths to a CSV file.
Time Complexity:O(m * k)
Explanation:
Iterates over each path and each point within the path to write to the file.
Nested iteration results in m * k operations.
2. Shape Class
a. Shape(const Path& pts)
Purpose: Constructor that initializes the Shape object with a given path.
Time Complexity:O(1)
Explanation:
Simply copies the path, which is a linear operation but considered O(1) in the context of object construction.
b. detectShape()
Purpose: Identifies the type of shape (e.g., Circle, Rectangle, Square, Star, Straight Line) based on the input points.
Time Complexity:O(k log k)
Explanation:
isStraightLine: Linear scan through points → O(k).
Contour Approximation (cv::approxPolyDP): Typically O(k log k) due to sorting steps involved in algorithms like Douglas-Peucker.
Area and Perimeter Calculations: Linear → O(k).
Shape-Specific Checks (e.g., isSquare, isStarShape): These involve linear scans or constant-time checks depending on the method, generally dominated by O(k log k).
Overall, the dominant factor is the contour approximation, making the method O(k log k).
c. regularizeShape()
Purpose: Regularizes the detected shape by approximating it with a standard geometric form.
Time Complexity:O(k) to O(k^2) depending on the shape.
Explanation:
Regularization Methods:
Circle (regularizeCircle):
Kasa Circle Fitting:O(k).
Point Generation: Constant O(1) per point, total O(n) where n is the number of points generated (typically fixed, e.g., 100).
Ellipse (regularizeEllipse):
Ellipse Fitting (cv::fitEllipse): Typically O(k) using methods like least squares.
Point Generation:O(1) since it's a fixed number of corners.
Star (regularizeStar):O(k) for centroid and radius calculations, plus O(n) for point generation.
Overall, most regularization methods operate in O(k) time, with point generation being a constant factor.
d. Helper Functions
i. calculateAngle(const Point2D& p1, const Point2D& p2, const Point2D& p3)
Time Complexity:O(1)
Explanation: Performs constant-time arithmetic operations to calculate the angle.
ii. isStraightLine(const Path& pts, double tolerance)
Time Complexity:O(k)
Explanation: Iterates through all points to calculate distances and check the straightness condition.
iii. isSquare(const std::vector<cv::Point>& contour, double tolerance)
Time Complexity:O(1) or O(c) where c is the number of contour points (typically small and constant).
Explanation: Uses OpenCV's minAreaRect, which operates in O(c) time, but since c is usually small (e.g., 4 points), it's treated as O(1).
iv. isStarShape(const std::vector<cv::Point>& approx)
Time Complexity:O(c) where c is the number of approximate contour points.
Explanation: Iterates through contour points to calculate angles. Typically c is a small constant (e.g., 10 points for a star), so it's O(1) in practice.
v. kasaCircleFitting(const Path& pts, double& xc, double& yc, double& radius)
Time Complexity:O(k^3)
Explanation:
Matrix Construction:O(k).
Solving Linear System: Using SVD (cv::solve), which has O(k^3) complexity for dense matrices.
However, since the system is of fixed size (3 variables), the effective complexity per point is O(k), making the overall complexity O(k).
3. Plotter Class
a. plotShapes(...)
Purpose: Visualizes original and regularized shapes side by side with annotations.
Time Complexity:O(m * k)
Explanation:
Transformation of Points: For each path, transforms each point → O(m * k).
Drawing Polylines and Circles: Each drawing operation per point is O(1), resulting in O(m * k) overall.
Symmetry Lines Calculation:
Centroid Calculation:O(k) per shape.
Drawing Lines: Constant time per line, total lines are usually fixed (e.g., 2 for circles).
Image Combination and Annotation: Linear with respect to image size but generally treated as O(1) relative to the number of shapes.
Overall, dominated by O(m * k) operations.
b. drawSymmetryLines(cv::Mat& img, const std::vector<std::pair<Point2D, Point2D>>& lines, const cv::Scalar& color)
Time Complexity:O(l) where l is the number of symmetry lines.
Explanation: Iterates over each line and draws it, resulting in linear time relative to the number of lines.
4. main Function
Purpose: Orchestrates reading CSV data, detecting and regularizing shapes, plotting, and writing output CSV.
Time Complexity:O(m * k^3)
Explanation:
Reading CSV:O(m * k).
Shape Detection and Regularization: For each of the m paths:
Detect Shape:O(k log k).
Regularize Shape:O(k).
Overall per shape: O(k log k).
Total for all shapes: O(m * k log k).
Plotting Shapes:O(m * k).
Writing CSV:O(m * k).
However, one critical consideration is within kasaCircleFitting, where solving the linear system has an effective complexity of O(k) per shape (since the system size is fixed). Thus, the total complexity remains O(m * k log k).
Note: The above assumes that all operations within each method are handled optimally. In cases where nested loops or higher complexities exist within helper functions, the overall complexity could increase. However, based on the provided code, O(m * k log k) is a reasonable upper bound.
Explanation: This command compiles the C++ program with C++17 standards and links against OpenCV libraries. It does not affect the runtime complexity of the algorithms.
Summary of Time Complexities
Class/Method
Time Complexity
Notes
CSVHandler
readCSV
O(m * k)
Linear with number of paths and points
writeCSV
O(m * k)
Linear with number of paths and points
Shape
Constructor
O(1)
Constant time
detectShape
O(k log k)
Dominated by contour approximation
regularizeShape
O(k)
Regularization methods are mostly linear
calculateAngle
O(1)
Constant time
isStraightLine
O(k)
Linear scan through points
isSquare
O(1) or O(c)
Contour size typically small and constant
isStarShape
O(1) or O(c)
Contour size typically small and constant
kasaCircleFitting
O(k)
Solving fixed-size linear system per point
Plotter
plotShapes
O(m * k)
Linear with number of paths and points
drawSymmetryLines
O(l)
Linear with number of symmetry lines
main
O(m * k log k)
Dominated by shape detection per path
Optimizations and Considerations
Contour Approximation (cv::approxPolyDP):
While typically O(k log k), certain optimizations or assumptions about the data can bring it closer to linear time.
Shape-Specific Regularizations:
If certain shapes are more prevalent, optimizing their regularization methods can yield performance gains.
Parallel Processing:
Since each path is processed independently, parallelizing the detectShape and regularizeShape steps can significantly reduce runtime on multi-core systems.
Early Exits:
In shape detection, incorporating early exit conditions can prevent unnecessary computations, especially for clearly identifiable shapes like straight lines.
Efficient Data Structures:
Ensuring that data structures used (e.g., vectors, maps) are optimized for the required operations can help in maintaining optimal time complexities.
Conclusion
Your program's overall time complexity is primarily driven by the shape detection process, which operates at O(m * k log k), where m is the number of paths and k is the number of points per path. Most other operations, such as reading/writing CSV files and plotting, operate at O(m * k), making the detection phase the bottleneck for large datasets.
To enhance performance, consider optimizing the contour approximation step, leveraging parallel processing, and implementing early termination in shape detection where possible.