import numpy as np
import matplotlib.pyplot as plt
import cv2
import 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
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)
code
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 " "
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)
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)
Assistant
code
sharp_angles = [angle for angle in angles if angle < 60 or angle > 300]
if len(sharp_angles) >= 5:
return True
return False
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
def is_straight_line(XY, tolerance=0.05):
"""Checks if the points form a straight line."""
if len(XY) < 3:
return True
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
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 = x2 + y2
c = np.linalg.lstsq(A, b, rcond=None)[0]
xc = c[0] / 2
yc = c[1] / 2
r = np.sqrt(c[2] + xc2 + yc2)
return xc, yc, r
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)
code
return np.column_stack((x, y))
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)
def regularize_star(XY, num_points=5):
"""Regularizes the points to form a perfect star."""
centroid = np.mean(XY, axis=0)
code
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])
return np.array(star_points)
def regularize_straight_line(XY):
"""Regularizes the points to form a perfect straight line."""
return np.array([XY[0], XY[-1]])
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)
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 []
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']
code
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()
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}.")
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())
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)
if name == "main":
main()
explain how does this work?
Certainly! Let's walk through the Python script you've provided step-by-step to understand how it works. This script is designed to read point data from a CSV file, detect geometric shapes formed by these points, regularize these shapes (i.e., adjust them to perfect geometric forms), visualize both the original and regularized shapes with symmetry lines, and finally save the regularized shapes back to a CSV file.
Overview of the Workflow
Import Necessary Libraries: The script begins by importing essential libraries for numerical computations, image processing, plotting, and handling CSV files.
Read and Organize Data: It reads point data from a CSV file and organizes these points into distinct paths.
Shape Detection: Each path is analyzed to determine the type of geometric shape it represents (e.g., circle, square, star).
Shape Regularization: Detected shapes are adjusted to their ideal geometric forms.
Symmetry Line Calculation: For each regularized shape, symmetry lines are calculated and drawn.
Visualization: Both original and regularized shapes are plotted side by side for comparison, with symmetry lines overlaid on the regularized shapes.
Save Regularized Shapes: The regularized shapes are written back to a new CSV file.
Let's delve into each of these components in detail.
1. Importing Libraries
python
import numpy as np
import matplotlib.pyplot as plt
import cv2
import csv
NumPy (np): For numerical operations, especially handling arrays and mathematical computations.
Matplotlib (plt): For plotting and visualizing shapes.
OpenCV (cv2): For image processing tasks, particularly contour detection and shape approximation.
CSV (csv): For reading from and writing to CSV files.
2. Reading and Organizing Data
python
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 and organizes these points into separate paths.
Assumptions About CSV Structure:
The CSV likely has multiple columns where the first column indicates the path or shape identifier.
Subsequent columns represent the x and y coordinates of points.
Process:
Load Data: Uses np.genfromtxt to read the CSV data into a NumPy array, splitting by commas.
Identify Unique Paths: np.unique(np_path_XYs[:, 0]) finds all unique identifiers (e.g., shape IDs) in the first column.
Organize Points:
For each unique identifier i, it selects all rows corresponding to that identifier.
Excludes the first column (which is the identifier) to get (x, y) pairs.
Further organizes these points into subpaths based on another identifier j (assuming nested identifiers).
Return: A list of all paths, where each path contains one or more subpaths represented by their (x, y) coordinates.
3. Shape Detection
a. Overall Detection Function
python
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 geometric shape represented by a set of (x, y) points.
Process:
Convert Points to Contour:
Uses OpenCV's expected format for contours, reshaping the (x, y) points accordingly.
Calculate Perimeter:
cv2.arcLength: Computes the perimeter (arc length) of the contour. The second argument True indicates that the contour is closed.
Approximate Polygonal Curve:
cv2.approxPolyDP: Approximates the contour to a polygon with fewer vertices. The second parameter is the approximation accuracy (4% of the perimeter here).
Compute Area:
cv2.contourArea: Calculates the area enclosed by the contour.
Shape Classification:
Small Area Check:
If the area is less than 100 (units depend on the scaling of your data), it's considered insignificant and returns an empty string.
Straight Line Check:
If the points form a straight line (is_straight_line returns True), classify as "Straight Line".
Polygon Checks:
Quadrilaterals (4 vertices):
Further check if it's a square (is_square function).
If not a square, classify as "Rectangle".
Shapes with More than 5 Vertices:
Star Detection:
If the approximated polygon has characteristics of a star (is_star function), classify as "Star".
Circularity Calculation:
circularity = 4 * π * Area / Perimeter²: Measures how close the shape is to a perfect circle (1.0 is a perfect circle).
Purpose: Determines whether a given contour is a square.
Process:
Minimum Area Rectangle:
cv2.minAreaRect: Finds the smallest rectangle that can contain the contour, which may be rotated.
Box Points Extraction:
cv2.boxPoints: Retrieves the four vertices of the rectangle.
Compute Width and Height:
Calculates the Euclidean distance between consecutive box points to get width and height.
Aspect Ratio:
min(width, height) / max(width, height): For a square, this should be close to 1. The tolerance allows for slight deviations.
Area Ratio:
Contour Area / Rectangle Area: Ensures the contour occupies most of the rectangle's area, indicating a filled shape.
Final Check:
Both aspect ratio and area ratio must be within the specified tolerance to qualify as a square.
ii. Checking for a Star
python
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: Determines whether a given approximated polygon represents a star.
Process:
Vertex Count:
Stars typically have more vertices due to their intersecting lines.
The function checks for more than 8 vertices as an initial filter.
Angle Calculation:
For each consecutive triplet of points (p1, p2, p3), calculate the angle at p2.
Uses the calculate_angle function to compute these angles.
Sharp Angles Identification:
In stars, certain angles (e.g., the points where lines intersect) are very sharp or reflex angles.
The function identifies angles less than 60 degrees or greater than 300 degrees.
Classification:
If there are at least 5 such sharp angles, the shape is classified as a "Star".
iii. Calculating Angles between Points
python
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 lines p1p2 and p3p2.
Process:
Vector Calculation:
Constructs vectors from these points.
Dot Product & Magnitudes:
Uses the dot product formula to compute the cosine of the angle between vectors.
Angle Calculation:
Applies arccos to find the angle in radians and converts it to degrees.
iv. Checking for a Straight Line
python
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 set of points approximates a straight line.
Process:
Minimum Points Check:
If fewer than 3 points, it's trivially a straight line.
Total Path Length:
Sum of the distances between consecutive points.
Direct Distance:
Euclidean distance from the first to the last point.
Comparison:
If the difference between the total path length and the direct distance is within the specified tolerance, it's considered a straight line.
4. Shape Regularization
Once a shape is detected, it may be irregular due to imperfections in the input data. The script regularizes these shapes to their ideal geometric forms.
Purpose: Detects the shape type and returns both the detected shape and its regularized version.
Process:
Straight Line Check:
Immediately regularizes to a straight line if applicable.
Shape Detection:
Uses the previously discussed detect_shape function.
Regularization:
Depending on the detected shape, calls the corresponding regularization function.
If the shape isn't recognized, returns the original points unmodified.
b. Regularization Functions for Specific Shapes
i. Regularizing a Circle
python
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 a set of points to a perfect circle based on fitted parameters.
Process:
Circle Fitting:
Uses Kasa's method (kasa_circle_fitting) to determine the center (xc, yc) and radius r of the best-fit circle.
Point Generation:
Generates 100 points evenly distributed around the circle using parametric equations (x = xc + r*cos(t), y = yc + r*sin(t)).
Return:
Returns the newly generated circle points.
ii. Kasa's Circle Fitting Method
python
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:
Linear System Setup:
Constructs matrix A and vector b based on the circle equation: ( x^2 + y^2 = 2xcx + 2ycy + c ).
Least Squares Solution:
Solves for the parameters using np.linalg.lstsq, which minimizes the residuals of the equation.
Parameter Extraction:
Computes the center (xc, yc) and radius r from the solved parameters.
iii. Regularizing an Ellipse
python
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 points to form a perfect ellipse based on the bounding box.
Process:
Bounding Box Calculation:
Finds the minimum and maximum x and y values to determine the ellipse's bounding rectangle.
Center and Axes Lengths:
Calculates the center of the ellipse and the lengths of the major (width) and minor (height) axes.
Point Generation:
Uses parametric equations to generate 200 points around the ellipse.
iv. Regularizing a Rectangle
python
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 points to form a perfect axis-aligned rectangle based on the bounding box.
Process:
Determine Corners:
Identifies the bottom-left, bottom-right, top-right, and top-left corners using min and max x and y values.
Point Sequencing:
Ensures the rectangle is represented as a closed loop by repeating the first point at the end.
Purpose: Adjusts points to form a perfect square based on the bounding box.
Process:
Determine Minimum Side:
Chooses the smaller of the width and height to ensure all sides are equal.
Corner Points:
Constructs a square using the determined side length, starting from the minimum x and y values.
vi. Regularizing a Star
python
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]) # Close the star
return np.array(star_points)
Purpose: Adjusts points to form a perfect star with a specified number of points (default is 5).
Process:
Centroid Calculation:
Finds the center of the star.
Radius Determination:
Identifies the outer and inner radii based on the distances of points from the centroid.
Angle Distribution:
Evenly distributes angles around the circle (twice the number of points to alternate between outer and inner points).
Point Generation:
Alternates between placing points at the outer and inner radii to form the star's spikes.
Closing the Star:
Repeats the first point at the end to ensure the star is a closed loop.
vii. Regularizing a Straight Line
python
def regularize_straight_line(XY):
"""Regularizes the points to form a perfect straight line."""
return np.array([XY[0], XY[-1]])
Purpose: Adjusts points to form a straight line by simply connecting the first and last points.
Process:
Line Definition:
Returns an array with only the starting and ending points, effectively representing a straight line between them.
5. Symmetry Line Calculation
python
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: Identifies lines of symmetry for regularized shapes to visualize them.
Process:
Shapes with Clear Symmetry:
Circle & Square: Have both vertical and horizontal symmetry lines passing through the centroid.
Ellipse & Rectangle: Typically have horizontal and vertical symmetry lines (though rectangles may also have diagonal symmetry lines, this script only adds horizontal symmetry).
Star Symmetry:
Stars have multiple lines of symmetry corresponding to each of their points.
The function generates lines extending from the centroid outward at regular angular intervals (e.g., every 72 degrees for a 5-pointed star).
Default:
Shapes without defined symmetry lines return an empty list.
6. Visualization
a. Plotting Function
python
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: Displays the original and regularized shapes side by side, with symmetry lines overlaid on the regularized shapes. Also prints information about the detected shapes.
Process:
Figure Setup:
Creates a matplotlib figure with two subplots: one for original shapes and one for regularized shapes.
Defines a list of colors to differentiate between shapes.
Aspect Ratio:
Sets each subplot to have equal aspect ratios to accurately represent shapes.
Shape Detection and Plotting:
Iterates over each path and its corresponding regularized version.
Detects the shape type and prints it in bold.
Plots the original shape in the left subplot and the regularized shape in the right subplot.
Calls draw_symmetry_lines to overlay symmetry lines on the regularized shapes.
Titles and Display:
Sets appropriate titles for each subplot.
Renders the plots.
b. Drawing Symmetry Lines
python
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 symmetry lines on the regularized shapes within the plot and prints the number of symmetry lines for each shape.
Process:
Helper Function plot_line:
Simplifies the plotting of a line between two points with specified color and style.
Shape-specific Symmetry Lines:
Ellipse & Rectangle:
Draw horizontal and vertical lines passing through the center.
Each has 2 lines of symmetry.
Star:
Draws lines from the centroid outward to each "point" of the star.
The number of lines corresponds to the number of star points.
Others:
If the shape doesn't have defined symmetry lines (e.g., Circle might not need them explicitly since all lines are symmetrical), no lines are drawn.
Print Statements:
Outputs the number of symmetry lines for each detected shape.
7. Saving Regularized Shapes to CSV
python
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 shapes back to a CSV file with a similar structure to the input.
Process:
File Opening:
Opens the specified CSV file in write mode.
Iterate and Write:
Iterates through each path and its corresponding regularized subpaths.
For each point in the subpath, writes a row to the CSV starting with the subpath index i, followed by the x and y coordinates.
Result:
A CSV file where each row corresponds to a point in a specific subpath, similar to the input structure.
8. Main Execution Flow
python
def main():
input_csv = "problems/frag1.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)
if __name__ == "__main__":
main()
Purpose: Serves as the entry point of the script, orchestrating the entire workflow.
Process:
File Paths:
Defines the input CSV (problems/frag1.csv) containing the original point data.
Defines the output CSV (regularized_shapes.csv) where the regularized shapes will be saved.
Data Reading:
Calls read_csv to load and organize the original point data into paths.
Shape Detection and Regularization:
Iterates through each path and its subpaths.
For each set of points (XY), detects the shape and generates its regularized version.
Collects all regularized shapes in regularized_XYs.
Visualization:
Calls plot_shapes to display both original and regularized shapes, along with symmetry lines.
Saving Data:
Writes the regularized shapes to the specified output CSV using polylines2csv.
Summary
This script effectively takes in raw point data from a CSV file, identifies the geometric shapes formed by these points, adjusts them to their ideal forms, visualizes the transformations alongside indicates symmetry, and then exports the refined shapes for further use or analysis. Key components such as shape detection leverage OpenCV's powerful image processing capabilities, while regularization ensures that any imperfections in the data are smoothed out to produce clean, geometrically accurate representations.
Potential Enhancements
Dynamic Tolerance Levels: Adjusting tolerance levels dynamically based on the scale or variance of input data could improve detection accuracy.
Additional Shapes: Incorporating detection and regularization for more complex shapes (e.g., polygons with more sides, different types of stars).
Visualization Tweaks: Enhancing plots with labels, legends, or interactive elements for better clarity.
Error Handling: Adding more robust error handling when reading files or processing data to ensure the script fails gracefully under unexpected conditions.
Feel free to ask if you have specific questions about any part of the script or need further clarification on certain functions or methodologies used!