Certainly! Let's break down the provided Python script step by step to understand its functionality. This script is designed to read point data from a CSV file, detect geometric shapes formed by these points, regularize (standardize) these shapes, visualize both the original and regularized shapes along with their symmetry lines, and finally save the regularized shapes back to a CSV file.
Here's a comprehensive explanation of each part of the script:
1. Importing Necessary Libraries
import numpy as np
import matplotlib.pyplot as plt
import cv2
import csv
- NumPy (
numpy): For numerical operations and handling arrays.
- Matplotlib (
matplotlib.pyplot): For plotting and visualizing the shapes.
- OpenCV (
cv2): For image processing operations, particularly for shape detection.
- CSV (
csv): For reading from and writing to CSV files.
2. Reading CSV Data
Function: read_csv
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
Purpose:
- Reads a CSV file containing point data.
- Organizes the points into separate paths based on unique identifiers.
Assumptions:
- The CSV structure likely starts with path identifiers, followed by possibly sub-path identifiers, and then the (X, Y) coordinates.
Process:
- Load Data:
np.genfromtxt reads the CSV file into a NumPy array, assuming values are comma-separated.
- Unique Paths: Identifies unique values in the first column to separate different paths.
- Sub-Paths: For each unique path identifier, further separates points into sub-paths based on the next column.
- Organize Points: Collects the (X, Y) coordinates for each sub-path.
- Return: A list of paths, each containing a list of sub-paths with their (X, Y) points.
3. Shape Detection
Function: detect_shape
def detect_shape(XY):
"""Detects the shape type from the provided points."""
contour = np.array(XY, dtype=np.int32).reshape((-1, 1, 2))
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
area = cv2.contourArea(contour)
if area < 100:
return " "
if is_straight_line(XY):
return "Straight Line"
if len(approx) == 4:
if is_square(contour):
return "Square"
else:
return "Rectangle"
elif len(approx) > 5:
if is_star(approx):
return "Star"
circularity = 4 * np.pi * area / (peri * peri)
if circularity > 0.95:
return "Circle"
elif 0.8 <= circularity < 0.95:
ellipse = cv2.fitEllipse(contour)
major_axis, minor_axis = max(ellipse[1]), min(ellipse[1])
if major_axis / minor_axis > 1.05:
return "Ellipse"
else:
return "Circle"
return " "
Purpose:
- Determines the type of geometric shape formed by a set of (X, Y) points.
Process:
- Contour Formation: Converts the point set into a format suitable for OpenCV contour operations.
- Perimeter Calculation: Uses
cv2.arcLength to calculate the perimeter of the contour.
- Polygon Approximation: Simplifies the contour to a polygon with fewer vertices using the Ramer-Douglas-Peucker algorithm (
cv2.approxPolyDP).
- Area Calculation: Computes the area of the contour.
- Shape Identification:
- Small Area Check: Ignores shapes with an area less than 100.
- Straight Line Check: Uses
is_straight_line to determine if the shape is a straight line.
- Four Vertices: If the approximated polygon has four vertices, further checks if it's a square or rectangle using
is_square.
- More than Five Vertices:
- Checks for a star shape using
is_star.
- Calculates circularity to differentiate between circles and ellipses.
- Return: The identified shape as a string (e.g., "Circle", "Ellipse", "Square", "Rectangle", "Star", "Straight Line", or an empty string if not identified).
Helper Functions for Shape Detection
Function: is_square
def is_square(contour, tolerance=0.05):
"""Checks if the contour forms a square."""
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.intp(box)
width = np.linalg.norm(box[0] - box[1])
height = np.linalg.norm(box[1] - box[2])
aspect_ratio = min(width, height) / max(width, height)
contour_area = cv2.contourArea(contour)
rect_area = width * height
area_ratio = contour_area / rect_area
is_square_shape = abs(1 - aspect_ratio) < tolerance
is_filled = area_ratio > (1 - tolerance)
return is_square_shape and is_filled
Purpose:
- Determines whether a contour corresponds to a square.
Process:
- Minimum Area Rectangle: Finds the smallest rectangle that can enclose the contour.
- Aspect Ratio: Calculates the ratio between the width and height of the rectangle.
- Area Ratio: Compares the area of the contour to the area of the rectangle.
- Checks:
- The aspect ratio should be close to 1 within a specified tolerance.
- The area ratio should indicate that the contour nearly fills the rectangle.
Returns: True if both conditions are met (i.e., it's a square), else False.
Function: is_star
def is_star(approx):
"""Checks if the contour forms a star shape."""
num_vertices = len(approx)
if num_vertices > 8:
angles = []
for i in range(num_vertices):
p1 = approx[i][0]
p2 = approx[(i + 1) % num_vertices][0]
p3 = approx[(i + 2) % num_vertices][0]
angle = calculate_angle(p1, p2, p3)
angles.append(angle)
sharp_angles = [angle for angle in angles if angle < 60 or angle > 300]
if len(sharp_angles) >= 5:
return True
return False
Purpose:
- Identifies if the approximated polygon corresponds to a star shape.
Process:
- Vertex Count: A star typically has more than a certain number of vertices (here, more than 8).
- Angle Calculation: Computes the angles formed at each vertex.
- Sharp Angles: Counts the number of sharply acute or obtuse angles (indicative of star points).
- Threshold Check: If there are at least five sharp angles, it's likely a star.
Returns: True if it matches star characteristics, else False.
Function: calculate_angle
def calculate_angle(p1, p2, p3):
"""Calculates the angle between three points."""
a = np.array(p1)
b = np.array(p2)
c = np.array(p3)
ab = b - a
cb = b - c
cosine_angle = np.dot(ab, cb) / (np.linalg.norm(ab) * np.linalg.norm(cb))
angle = np.degrees(np.arccos(cosine_angle))
return angle
Purpose:
- Computes the angle at point
p2 formed by the line segments p2p1 and p2p3.
Process:
- Vector Calculation: Computes vectors
ab and cb from the given points.
- Dot Product: Uses the dot product formula to find the cosine of the angle between the vectors.
- Angle in Degrees: Converts the angle from radians to degrees.
Returns: The calculated angle in degrees.
Function: is_straight_line
def is_straight_line(XY, tolerance=0.05):
"""Checks if the points form a straight line."""
if len(XY) < 3:
return True
total_length = np.sum(np.sqrt(np.sum(np.diff(XY, axis=0)**2, axis=1)))
start_to_end = np.linalg.norm(XY[-1] - XY[0])
return (total_length - start_to_end) / total_length < tolerance
Purpose:
- Determines whether a sequence of points approximates a straight line.
Process:
- Minimum Points: If there are fewer than 3 points, it's considered a straight line.
- Total Path Length: Calculates the sum of distances between consecutive points.
- Direct Distance: Computes the direct distance from the starting point to the ending point.
- Deviation Check: If the difference between the total path length and the direct distance is within the specified tolerance, it's a straight line.
Returns: True if the points form a straight line, else False.
4. Shape Regularization
Regularizing shapes means adjusting the detected shapes to their ideal geometric forms (e.g., perfect circles, squares).
Function: detect_and_regularize_shape
def detect_and_regularize_shape(XY):
"""Detects the shape and returns the regularized points."""
if is_straight_line(XY):
return "Straight Line", regularize_straight_line(XY)
shape = detect_shape(XY)
if shape == "Circle":
regularized_XY = regularize_circle(XY)
elif shape == "Ellipse":
regularized_XY = regularize_ellipse(XY)
elif shape == "Rectangle":
regularized_XY = regularize_rectangle(XY)
elif shape == "Square":
regularized_XY = regularize_square(XY)
elif shape == "Star":
regularized_XY = regularize_star(XY)
else:
regularized_XY = XY
return shape, regularized_XY
Purpose:
- Detects the shape type and returns both the shape name and its regularized (standardized) version.
Process:
- Straight Line Check: If the points form a straight line, regularizes it to ensure it's perfectly straight between the first and last points.
- Shape Detection: Uses
detect_shape to identify the shape.
- Regularization: Based on the detected shape, calls the corresponding regularization function.
- Fallback: If the shape isn't recognized, returns the original points.
Returns: A tuple containing the shape name and the regularized (X, Y) points.
Regularization Functions
Function: regularize_circle
def regularize_circle(XY):
"""Regularizes the points to form a perfect circle."""
xc, yc, r = kasa_circle_fitting(XY)
t = np.linspace(0, 2 * np.pi, 100)
x_fit = xc + r * np.cos(t)
y_fit = yc + r * np.sin(t)
return np.vstack((x_fit, y_fit)).T
Purpose:
- Adjusts the points to form a perfect circle based on the fitted circle parameters.
Process:
- Circle Fitting: Uses Kasa's method (
kasa_circle_fitting) to find the center (xc, yc) and radius (r).
- Parametric Circle: Generates 100 points around the circle's circumference using polar coordinates.
- Return: The (X, Y) coordinates of the regularized circle.
Function: kasa_circle_fitting
def kasa_circle_fitting(XY):
"""Fits a circle to the points using Kasa's method."""
x = XY[:, 0]
y = XY[:, 1]
A = np.array([x, y, np.ones_like(x)]).T
b = x**2 + y**2
c = np.linalg.lstsq(A, b, rcond=None)[0]
xc = c[0] / 2
yc = c[1] / 2
r = np.sqrt(c[2] + xc**2 + yc**2)
return xc, yc, r
Purpose:
- Implements Kasa's method to fit a circle to a set of points.
Process:
- Formulate Linear System: Based on the circle equation ((x - xc)^2 + (y - yc)^2 = r^2), rearranged to linearly solve for (xc), (yc), and a term related to (r^2).
- Least Squares Solution: Uses
np.linalg.lstsq to solve the linear system.
- Calculate Circle Parameters: Derives the center coordinates (
xc, yc) and the radius (r) from the solution.
- Return: The center and radius of the fitted circle.
Function: regularize_ellipse
def regularize_ellipse(XY):
"""Regularizes the points to form a perfect ellipse."""
x_min, y_min = np.min(XY, axis=0)
x_max, y_max = np.max(XY, axis=0)
center = [(x_min + x_max) / 2, (y_min + y_max) / 2]
width = x_max - x_min
height = y_max - y_min
t = np.linspace(0, 2 * np.pi, 200)
x = center[0] + width/2 * np.cos(t)
y = center[1] + height/2 * np.sin(t)
return np.column_stack((x, y))
Purpose:
- Adjusts the points to form a perfect ellipse based on the bounding rectangle.
Process:
- Bounding Box: Finds the minimum and maximum X and Y values to determine the bounding rectangle.
- Ellipse Parameters: Calculates the center, width, and height of the ellipse.
- Parametric Ellipse: Generates 200 points around the ellipse's circumference using parametric equations.
- Return: The (X, Y) coordinates of the regularized ellipse.
Function: regularize_rectangle
def regularize_rectangle(XY):
"""Regularizes the points to form a perfect rectangle."""
x_min, y_min = np.min(XY, axis=0)
x_max, y_max = np.max(XY, axis=0)
regularized = np.array([
[x_min, y_min],
[x_max, y_min],
[x_max, y_max],
[x_min, y_max],
[x_min, y_min]
])
return regularized
Purpose:
- Adjusts the points to form a perfect rectangle based on the bounding box.
Process:
- Bounding Box: Identifies the minimum and maximum X and Y values.
- Rectangle Corners: Defines the four corners of the rectangle using these bounds.
- Closure: Adds the starting point at the end to close the rectangle.
- Return: The (X, Y) coordinates of the regularized rectangle.
Function: regularize_square
def regularize_square(XY):
"""Regularizes the points to form a perfect square."""
x_min, y_min = np.min(XY, axis=0)
x_max, y_max = np.max(XY, axis=0)
side_length = min(x_max - x_min, y_max - y_min)
reg_XY = np.array([
[x_min, y_min],
[x_min + side_length, y_min],
[x_min + side_length, y_min + side_length],
[x_min, y_min + side_length],
[x_min, y_min]
])
return reg_XY
Purpose:
- Adjusts the points to form a perfect square based on the bounding box.
Process:
- Bounding Box: Finds the minimum and maximum X and Y values.
- Side Length: Chooses the smaller of the width or height to maintain equal sides.
- Square Corners: Defines the four corners of the square using the calculated side length.
- Closure: Adds the starting point at the end to close the square.
- Return: The (X, Y) coordinates of the regularized square.
Function: regularize_star
def regularize_star(XY, num_points=5):
"""Regularizes the points to form a perfect star."""
centroid = np.mean(XY, axis=0)
radii = np.linalg.norm(XY - centroid, axis=1)
outer_radius = np.max(radii)
inner_radius = np.min(radii)
angles = np.linspace(0, 2*np.pi, 2*num_points, endpoint=False)
star_points = []
for i, angle in enumerate(angles):
r = outer_radius if i % 2 == 0 else inner_radius
x = centroid[0] + r * np.cos(angle)
y = centroid[1] + r * np.sin(angle)
star_points.append([x, y])
star_points.append(star_points[0]) # Closing the star
return np.array(star_points)
Purpose:
- Adjusts the points to form a perfect star with a specified number of points (default is 5).
Process:
- Centroid: Computes the center of the star by averaging the (X, Y) coordinates.
- Radii Calculation: Determines the maximum (outer radius) and minimum (inner radius) distances from the centroid to the points.
- Angle Division: Divides the full circle (0 to (2\pi)) into intervals based on
num_points to position the star points correctly.
- Point Generation: Alternates between outer and inner radii to create the star's spikes and indentations.
- Closure: Adds the starting point at the end to close the star shape.
- Return: The (X, Y) coordinates of the regularized star.
Function: regularize_straight_line
def regularize_straight_line(XY):
"""Regularizes the points to form a perfect straight line."""
return np.array([XY[0], XY[-1]])
Purpose:
- Simplifies a sequence of points to a perfect straight line between the first and last points.
Process:
- Endpoints: Selects the first and last points of the input.
- Return: An array containing only these two points, representing a straight line.
5. Symmetry Line Calculation and Drawing
Function: calculate_symmetry_lines
def calculate_symmetry_lines(XY, shape_type):
"""Calculates symmetry lines for the given shape."""
if shape_type in ["Circle", "Ellipse", "Square", "Rectangle"]:
centroid = np.mean(XY, axis=0)
if shape_type == "Circle" or shape_type == "Square":
return [
([centroid[0], np.min(XY[:, 1])], [centroid[0], np.max(XY[:, 1])]), # Vertical
([np.min(XY[:, 0]), centroid[1]], [np.max(XY[:, 0]), centroid[1]]) # Horizontal
]
elif shape_type == "Ellipse" or shape_type == "Rectangle":
return [
([np.min(XY[:, 0]), centroid[1]], [np.max(XY[:, 0]), centroid[1]]) # Horizontal
]
elif shape_type == "Star":
centroid = np.mean(XY, axis=0)
angles = np.linspace(0, 2*np.pi, 5, endpoint=False)
lines = []
for angle in angles:
x = centroid[0] + np.cos(angle) * 1000
y = centroid[1] + np.sin(angle) * 1000
lines.append(([centroid[0], centroid[1]], [x, y]))
return lines
return []
Purpose:
- Determines the symmetry lines based on the detected shape.
Process:
- Common Shapes:
- Circle & Square: Both have both vertical and horizontal symmetry.
- Ellipse & Rectangle: Generally have horizontal symmetry.
- Star:
- Generates lines radiating from the centroid at equal angular intervals (based on the number of star points).
- Uses a large multiplier (1000) to extend the lines visually.
- Return: A list of line segments, each defined by a start and end point.
Function: draw_symmetry_lines
def draw_symmetry_lines(ax, shape, reg_XY, color):
def plot_line(ax, start, end, color):
ax.plot([start[0], end[0]], [start[1], end[1]], color=color, linestyle='--', linewidth=1)
if shape == "Ellipse":
x_min, y_min = np.min(reg_XY, axis=0)
x_max, y_max = np.max(reg_XY, axis=0)
center_x, center_y = (x_min + x_max) / 2, (y_min + y_max) / 2
plot_line(ax, [x_min, center_y], [x_max, center_y], color)
plot_line(ax, [center_x, y_min], [center_x, y_max], color)
# Print number of symmetry lines
print(f" - {shape} has 2 lines of symmetry.")
elif shape == "Rectangle":
x_min, y_min = np.min(reg_XY, axis=0)
x_max, y_max = np.max(reg_XY, axis=0)
plot_line(ax, [(x_min + x_max)/2, y_min], [(x_min + x_max)/2, y_max], color)
plot_line(ax, [x_min, (y_min + y_max)/2], [x_max, (y_min + y_max)/2], color)
# Print number of symmetry lines
print(f" - {shape} has 2 lines of symmetry.")
elif shape == "Star":
num_points = len(reg_XY) // 2
for i in range(num_points):
start_point = reg_XY[i]
end_point = reg_XY[(i + num_points) % len(reg_XY)]
plot_line(ax, start_point, end_point, color)
# Print number of symmetry lines
print(f" - {shape} has {num_points} lines of symmetry.")
else:
print(f" - No specific symmetry lines defined for {shape}.")
Purpose:
- Draws the calculated symmetry lines on the plot for visualization.
Process:
- Define
plot_line: A nested helper function to plot a dashed line between two points.
- Shape-specific Drawing:
- Ellipse & Rectangle: Draw vertical and horizontal symmetry lines based on the bounding box.
- Star: Draws multiple radiating lines based on the number of points in the star.
- Others: Currently, only prints that no symmetry lines are defined.
- Console Output: Prints the number of symmetry lines for the shape.
6. Plotting Shapes
Function: plot_shapes
def plot_shapes(path_XYs, regularized_XYs):
"""Plots original and regularized shapes with symmetry lines, and prints information about detected shapes."""
fig, ax = plt.subplots(1, 2, tight_layout=True, figsize=(16, 8))
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
for a in ax:
a.set_aspect('equal')
# Print shapes detected and regularized in bold
print("\033[1mShapes Detected and Regularized:\033[0m")
for i, (orig_XYs, reg_XYs) in enumerate(zip(path_XYs, regularized_XYs)):
color = colors[i % len(colors)]
for XY, reg_XY in zip(orig_XYs, reg_XYs):
shape_type, _ = detect_and_regularize_shape(XY)
# Print the name of the detected shape
print(f"- {shape_type}")
ax[0].plot(XY[:, 0], XY[:, 1], c=color, linewidth=2)
ax[1].plot(reg_XY[:, 0], reg_XY[:, 1], c=color, linewidth=2)
# Draw symmetry lines and count them
draw_symmetry_lines(ax[1], shape_type, reg_XY, 'k')
ax[0].set_title('Original Shapes')
ax[1].set_title('Regularized Shapes with Symmetry Lines')
plt.show()
Purpose:
- Visualizes both the original and regularized shapes side by side and prints detected shapes to the console.
Process:
- Figure Setup: Creates a matplotlib figure with two subplots (columns) for original and regularized shapes.
- Aspect Ratio: Sets both plots to have equal aspect ratios to accurately represent shapes.
- Console Output: Prints a bold header indicating that shapes are being detected and regularized.
- Loop Through Shapes:
- Iterates over original and regularized shape pairs.
- Assigns different colors to different shapes for clarity.
- Detects and regularizes each shape.
- Plots the original shape on the first subplot and the regularized shape on the second.
- Draws symmetry lines on the regularized shapes.
- Prints the detected shape type.
- Titles: Adds titles to both subplots for clarity.
- Display: Shows the plots.
Console Output Example:
Shapes Detected and Regularized:
- Circle
- Circle has 2 lines of symmetry.
- Rectangle
- Rectangle has 2 lines of symmetry.
- Star
- Star has 5 lines of symmetry.
7. Writing Regularized Shapes to CSV
Function: polylines2csv
def polylines2csv(paths_XYs, csv_path):
"""Writes the regularized shapes to a CSV file."""
with open(csv_path, 'w', newline='') as f:
writer = csv.writer(f)
for path_XYs in paths_XYs:
for i, XY in enumerate(path_XYs):
for point in XY:
writer.writerow([i] + point.tolist())
Purpose:
- Saves the regularized (standardized) shapes back into a CSV file.
Process:
- File Opening: Opens the specified CSV file in write mode.
- CSV Writing: For each path and its sub-paths, writes each (X, Y) point preceded by a sub-path identifier.
- Structure: Each row in the CSV will have a sub-path number followed by the X and Y coordinates.
Example CSV Output:
0, 100.0, 200.0
0, 150.0, 200.0
0, 150.0, 250.0
...
8. Main Execution Flow
Function: main
def main():
input_csv = "problems/isolated.csv"
output_csv = "regularized_shapes.csv"
path_XYs = read_csv(input_csv)
regularized_XYs = []
for path in path_XYs:
reg_XYs = []
for XY in path:
_, reg_XY = detect_and_regularize_shape(XY)
reg_XYs.append(reg_XY)
regularized_XYs.append(reg_XYs)
plot_shapes(path_XYs, regularized_XYs)
polylines2csv(regularized_XYs, output_csv)
Purpose:
- Coordinates the entire process from reading the input CSV to writing the regularized shapes back to a new CSV.
Process:
- File Paths:
- Input:
"problems/isolated.csv" — the CSV file containing the original point data.
- Output:
"regularized_shapes.csv" — the CSV file to save the regularized shapes.
- Reading Data: Calls
read_csv to load and organize the point data into paths.
- Regularizing Shapes:
- Iterates through each path and its sub-paths.
- Detects and regularizes each shape using
detect_and_regularize_shape.
- Collects the regularized shapes into
regularized_XYs.
- Visualization: Calls
plot_shapes to display both original and regularized shapes with symmetry lines.
- Saving Data: Writes the regularized shapes to the output CSV using
polylines2csv.
Execution Entry Point
if __name__ == "__main__":
main()
Purpose:
- Ensures that the
main function is executed only when the script is run directly, not when imported as a module.
9. Summary of Script Workflow
-
Data Input:
- Reads points from
problems/isolated.csv, organizing them into structured paths and sub-paths.
-
Shape Detection and Regularization:
- For each set of points:
- Detects the geometric shape (e.g., circle, ellipse, rectangle, square, star, straight line).
- Regularizes the shape to its perfect form (e.g., perfect circle, square).
-
Visualization:
- Plots original shapes on the left.
- Plots regularized shapes with symmetry lines on the right.
- Outputs detected shape types and their symmetry information to the console.
-
Data Output:
- Saves the regularized shapes to
regularized_shapes.csv for further use or analysis.
10. Potential Use Cases
- Graphic Design: Standardizing hand-drawn shapes for digital applications.
- Computer Vision: Preprocessing shapes detected in images for classification or recognition tasks.
- Data Analysis: Cleaning and organizing geometric data for studies in geometry or pattern recognition.
- CAD Applications: Converting free-form shapes into standard geometric primitives for design purposes.
11. Considerations and Improvements
-
CSV Format: The script assumes a specific CSV structure. Ensure that the input CSV aligns with this format or modify the read_csv function accordingly.
-
Shape Detection Robustness: While the script covers basic shapes, more complex or irregular shapes might not be accurately detected or regularized.
-
Error Handling: Currently, the script doesn't include extensive error handling. Incorporating try-except blocks can make it more robust against malformed data or unexpected inputs.
-
Performance: For large datasets, performance optimizations (e.g., vectorization, efficient data structures) might be necessary.
-
User Input: Making file paths configurable via command-line arguments or user prompts can enhance flexibility.
-
Extensibility: Adding support for additional shapes or enhancing the regularization process (e.g., allowing for rotation) can broaden the script's applicability.
This script provides a solid foundation for processing and standardizing geometric shapes from point data. By understanding each component, you can tailor it to fit specific requirements or extend its capabilities further.