import cv2 import numpy as np import open3d as o3d import matplotlib.pyplot as plt from scipy.optimize import leastsq from scipy.stats import circstd from Scripts import edges import datetime import os class CircleFitter: def __init__(self, point): """ CircleFitter class performs circle fitting operations on the given point cloud (pcd). """ self.pcd = point self.commonp = None self.datum = self.get_datum() def get_B(self, strip_width=20): points = self.pcd medianx = np.median(points[:, 0]) mediany = np.median(points[:, 1]) # Center point on Y axis strip_points = points[ (np.abs(points[:, 1] - mediany) < strip_width / 2) & (np.abs(points[:, 0] - medianx) < strip_width / 2) ] if len(strip_points) == 0: raise ValueError("No points found within the strip.") return np.min(strip_points[:, 2]) def get_datum(self): strip_width = 1 x_center = np.median(self.pcd[:, 0]) strip_points = self.pcd[np.abs(self.pcd[:, 0] - x_center) < strip_width / 2] self.datum = np.min(strip_points[:, 1]) return self.datum def calculate_error_metrics( self, x_points, y_points, xc, yc, r, circle_name="Circle" ): """ Calculates error metrics for circle fitting and writes to a txt file. Args: x_points, y_points: Points used for circle fitting xc, yc, r: Calculated circle center and radius circle_name: Circle name (Circle 1, Circle 2 etc.) """ n_points = len(x_points) # Distance from each point to circle center distances_to_center = np.sqrt((x_points - xc) ** 2 + (y_points - yc) ** 2) # Geometric error: Each point's deviation from the circle geometric_errors = np.abs(distances_to_center - r) # Error metrics mean_error = np.mean(geometric_errors) rms_error = np.sqrt(np.mean(geometric_errors**2)) std_deviation = np.std(geometric_errors) max_error = np.max(geometric_errors) min_error = np.min(geometric_errors) # Angular analysis angles_rad = np.arctan2(y_points - yc, x_points - xc) angles_deg = np.degrees(angles_rad) angles_deg[angles_deg < 0] += 360 # Normalize to 0-360 # Angular distribution metrics angle_range = np.max(angles_deg) - np.min(angles_deg) angle_mean = np.mean(angles_deg) # ✅ Circular standard deviation – correct method angle_std = np.degrees(circstd(angles_rad, high=2 * np.pi, low=0)) # Distribution in angular sectors (45° sectors) sectors = np.floor(angles_deg / 45).astype(int) sector_counts = np.bincount(sectors, minlength=8) # Write to TXT file timestamp = datetime.datetime.now().strftime("%d_%H%M") filename = f"{circle_name}{timestamp}.txt" mode = "a" if os.path.exists(filename) else "w" with open(filename, mode, encoding="utf-8") as f: f.write(f"\n{'=' * 60}\n") f.write(f"CIRCLE FITTING ANALYSIS - {circle_name}\n") f.write( f"Analysis Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n" ) f.write(f"{'=' * 60}\n\n") f.write(f"GENERAL INFORMATION:\n") f.write(f"Number of Points: {n_points}\n") f.write(f"Circle Center: ({xc:.4f}, {yc:.4f})\n") f.write(f"Radius: {r:.4f}\n\n") f.write(f"GEOMETRIC ERROR METRICS:\n") f.write(f"Mean Error: {mean_error:.6f}\n") f.write(f"RMS Error: {rms_error:.6f}\n") f.write(f"Standard Deviation: {std_deviation:.6f}\n") f.write(f"Maximum Error: {max_error:.6f}\n") f.write(f"Minimum Error: {min_error:.6f}\n\n") f.write(f"ANGULAR DISTRIBUTION ANALYSIS:\n") f.write(f"Angle Range: {angle_range:.2f}°\n") f.write(f"Angular Mean: {angle_mean:.2f}°\n") f.write(f"Angular Standard Deviation (circular): {angle_std:.2f}°\n\n") f.write(f"SECTOR DISTRIBUTION (45° sectors):\n") for i, count in enumerate(sector_counts): start_angle = i * 45 end_angle = (i + 1) * 45 f.write( f"Sector {i + 1} ({start_angle}°-{end_angle}°): {count} points\n" ) f.write(f"\n{'=' * 60}\n") print(f"Error metrics saved to file {filename}.") def get_distance(self, second_crc=True, z_distance_to_datum=102.1, reel_datum=None): """ Calculates the Euclidean distance of the circle center to the correct point and visualizes it. Draws the original pcd points and calculated centers. Args: second_crc (bool): Whether to use the center of the second circle. z_distance_to_datum (float): Z distance relative to datum. reel_datum (float, optional): Real datum value. Uses self.datum by default. Returns: distance (float): Distance of circle center. ok (bool): Checks if the distance is less than 3 mm. """ datum = self.datum # Select circle centers if second_crc: median = np.median(self.pcd[:, 0]) xc_outer, zc_outer = self.xc_outer_2, self.zc_outer_2 else: median = np.median(self.pcd[:, 0]) xc_outer, zc_outer = self.xc_outer, self.zc_outer # Median and z_center calculations z_center = datum + z_distance_to_datum # Euclidean distance distance = np.hypot(xc_outer - median, zc_outer - z_center) # Distance accuracy check ok = distance < 3 # Visualization plt.figure(figsize=(8, 8)) plt.scatter( self.pcd[:, 0], self.pcd[:, 1], s=1, color="blue", label="Original Points" ) plt.scatter( median, z_center, color="orange", label="z_center (Reference Point)" ) plt.scatter(xc_outer, zc_outer, color="red", label="Circle Center") plt.title("Circle Center and Reference Point") plt.xlabel("X") plt.ylabel("Z") plt.axis("equal") plt.legend() return distance, ok def fit_circle(self, x, y): """ Performs circle fitting on the given X and Y points. """ def calc_radius(xc, yc, x, y): return np.sqrt((x - xc) ** 2 + (y - yc) ** 2) def cost_function(params, x, y): xc, yc, r = params return calc_radius(xc, yc, x, y) - r def initial_guess(x, y): xc = np.mean(x) yc = np.mean(y) r = np.mean(np.sqrt((x - xc) ** 2 + (y - yc) ** 2)) return [xc, yc, r] guess = initial_guess(x, y) result, _ = leastsq(cost_function, guess, args=(x, y)) return result # xc, yc, r def fit_circles_and_plot( self, name, find_second_circle=True, val_x=0.18, val_z=0.796, delta_z=14, clc_metrics=False, ): """ Performs circle fitting operations on the point cloud in the X-Z plane and visualizes them. Args: find_second_circle (bool): Whether to find the second circle. val_x (float): Ratio on the X axis for dynamic filtering. val_z (float): Ratio on the Z axis for dynamic filtering. delta_z (float): Width of the filtering region on the Z axis. """ try: self.find_second_circle = find_second_circle # Points projected to the X-Z plane projected_points_2d = self.pcd[:, [0, 1]] # Get edge coordinates edge_coords = edges.process_and_visualize(projected_points_2d) # Scale edges scale = edges.get_scale() x2d, z2d = edge_coords[:, 1] / scale, edge_coords[:, 0] / scale # Dynamic filtering parameters min_x, max_x = ( np.min(projected_points_2d[:, 0]), np.max(projected_points_2d[:, 0]), ) min_z, max_z = ( np.min(projected_points_2d[:, 1]), np.max(projected_points_2d[:, 1]), ) x_min = min_x + val_x * (max_x - min_x) x_max = x_min + 26 z_min = min_z + val_z * (max_z - min_z) z_max = z_min + delta_z # First circle fitting mask_1 = (x2d > x_min) & (x2d < x_max) & (z2d > z_min) & (z2d < z_max) x_2d_1, z_2d_1 = x2d[mask_1], z2d[mask_1] xc_outer, zc_outer, r_outer = self.fit_circle(x_2d_1, z_2d_1) self.xc_outer, self.zc_outer = xc_outer, zc_outer # Calculate error metrics for first circle if clc_metrics: self.calculate_error_metrics( x_2d_1, z_2d_1, xc_outer, zc_outer, r_outer, name ) # Drawing circles theta = np.linspace(0, 2 * np.pi, 100) x_outer_circle = xc_outer + r_outer * np.cos(theta) z_outer_circle = zc_outer + r_outer * np.sin(theta) # Visualization fig, ax = plt.subplots(figsize=(8, 8)) ax.scatter(x2d, z2d, s=1, color="blue", label="Points") ax.plot( x_outer_circle, z_outer_circle, color="red", label=f"Circle 1 (R = {r_outer:.2f})", ) # Add filtering area as rectangle ax.add_patch( plt.Rectangle( (x_min, z_min), x_max - x_min, z_max - z_min, edgecolor="red", facecolor="none", linewidth=2, label="Filtering Region", ) ) if find_second_circle: # Second circle fitting zc_min_2 = zc_outer zc_max_2 = zc_outer + 5 mask_2 = ( (x2d > x_min) & (x2d < x_max) & (z2d > zc_min_2) & (z2d < zc_max_2) ) x_2d_2, z_2d_2 = x2d[mask_2], z2d[mask_2] xc_outer_2, zc_outer_2, r_outer_2 = self.fit_circle(x_2d_2, z_2d_2) self.xc_outer_2, self.zc_outer_2 = xc_outer_2, zc_outer_2 # Second circle drawing x_outer_circle_2 = xc_outer_2 + r_outer_2 * np.cos(theta) z_outer_circle_2 = zc_outer_2 + r_outer_2 * np.sin(theta) ax.plot( x_outer_circle_2, z_outer_circle_2, color="green", label=f"Circle 2 (R = {r_outer_2:.2f})", ) ax.set_title("Point Cloud, Circle Fitting and Filtering Area in X-Z Plane") ax.set_xlabel("X") ax.set_ylabel("Z") ax.axis("equal") ax.legend() # Return section if find_second_circle: return ( (xc_outer, zc_outer, r_outer * 2), (xc_outer_2, zc_outer_2, r_outer_2 * 2), fig, ax, ) else: return (xc_outer, zc_outer, r_outer * 2), fig, ax except Exception as e: print(f"Error in big_circle1.py: {e}") return None